2014-12-03 75 views
2

我有一个疑难问题。看了很多论坛和主题,但我不明白如何创建一个类文件像JSON数据加载:加载JSON数据到Android listpreference

{"city":[{"id":"1","name":"London"},{"id":"2","name":"Berlin"},{"id":"3","name":"New York"}],"success":1} 

一种用于ListPreference列表将一个值保存到共享首选项文件。 像我保存的网址:

<string name="URL">192.168.1.100/data</string> 

没有不赞成的方法(findPreference("city"))。 我使用偏好XML是

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 

    <PreferenceCategory android:title="@string/settings_menu" > 

     <ListPreference 
      android:defaultValue="192.168.1.100/data" 
      android:entries="@array/URLArray" 
      android:entryValues="@array/URLValues" 
      android:key="URL" 
      android:summary="@string/filter_for_searches" 
      android:title="@string/your_country" /> 


     <ListPreference 
      android:defaultValue="" 
      android:entries="@array/listArray" 
      android:entryValues="@array/listValues" 
      android:key="city" 
      android:title="@string/your_city"/> 

     <ListPreference 
      android:defaultValue="" 
      android:entries="@array/listLang" 
      android:entryValues="@array/listLangValues" 
      android:key="Language" 
      android:summary="" 
      android:title="@string/select_your_language" /> 


    </PreferenceCategory> 

</PreferenceScreen> 

,并提前我的源代码

package com.sono.famlocator; 

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.ListActivity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.ListView; 


public class CityLoader extends ListActivity { 

    A cls2= new A(); 


    JSONArray city; 
    JSONObject jsonobject; 
    PrefAdapter adapter; 

    private ProgressDialog pDialog; 
    private String loader; 

    JSONParser jParser = new JSONParser(); 
    ArrayList<HashMap<String, String>> cList; 

    public static String url2; 
    public static String country; 
    static final String TAG_SUCCESS = "success"; 
    static final String TAG_EVENTS = "city"; 
    static final String TAG_ID = "id"; 
    static final String TAG_NAME = "name"; 

    static final String TAG_LOADER = "TAG_LOADER"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listview_f_all); 

     cls2.url(this); 
     cls2.country(this); 
     country = A.country; 
     url2 = A.url2; 
     loader = "http://" + url2 + "/get_citylist.php"; 


     String title = getResources().getString(R.string.app_name); 

     setTitle(title + " - Country"); 

     cList = new ArrayList<HashMap<String, String>>(); 

     new LoadCity().execute(); 
    } 

    public boolean isOnline() { 

     Context context = getApplicationContext(); 
     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo ni = cm.getActiveNetworkInfo(); 

     if (ni != null && ni.isConnected()) 
      return true; 
     else 
      return false; 
    } 


    public class LoadCity extends AsyncTask<String, String, String> { 


     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(CityLoader.this); 
      pDialog.setMessage("Loading. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     /** 
     * getting All city from url 
     * */ 
     protected String doInBackground(String... args) { 
      if (isOnline()) { 

       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("country", country)); 


       JSONObject json = jParser.makeHttpRequest(loader, "GET", params); 

       Log.d("All Events: ", json.toString()); 

       try { 
        int success = json.getInt(TAG_SUCCESS); 
        if (success == 1) { 

         city = json.getJSONArray(TAG_EVENTS); 

         for (int i = 0; i < city.length(); i++) { 

          jsonobject = city.getJSONObject(i); 

          //key for adapter 
          String key = "CITY"; 

          String id = jsonobject.getString(TAG_ID); 
          String name = jsonobject.getString(TAG_NAME); 

          HashMap<String, String> map = new HashMap<String, String>(); 

          map.put(TAG_LOADER, key); 
          map.put(TAG_ID, id); 
          map.put(TAG_NAME, name); 


          cList.add(map); 

         } 
        } else { 

        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
      return null; 
     } 


     protected void onPostExecute(final String file_url) { 


      pDialog.dismiss(); 
      ListView lv = getListView(); 
      adapter = new PrefAdapter(CityLoader.this, cList); 
      lv.setAdapter(adapter); 

     } 
    } 

} 

感谢和我的英语不好对不起!

回答

2

那么,在简单的情况下,当你想支持API < 11并使用PreferenceActivity这是你可以填充你的ListPreference从JSON对象中读取数据:

MainActivity.java

package com.example.abc; 

import java.util.ArrayList; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.os.Bundle; 
import android.preference.ListPreference; 
import android.preference.PreferenceActivity; 
import android.util.Log; 

public class MainActivity extends PreferenceActivity { 

    private static final String TAG = MainActivity.class.getSimpleName(); 

    @SuppressWarnings("deprecation") 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     addPreferencesFromResource(R.xml.preferences); 

     ArrayList<String> entries = new ArrayList<>(); 
     ArrayList<String> entryValues = new ArrayList<>(); 

     String jsonString = "{\"city\":[{\"id\":\"1\",\"name\":\"London\"},{\"id\":\"2\",\"name\":\"Berlin\"},{\"id\":\"3\",\"name\":\"New York\"}],\"success\":1}"; 
     try { 
      JSONObject json = new JSONObject(jsonString); 
      JSONArray jsonArray = json.getJSONArray("city"); 
      for(int i = 0; i < jsonArray.length(); ++i) { 
       JSONObject cityObject = (JSONObject) jsonArray.get(i); 
       entryValues.add(cityObject.getString("id")); 
       entries.add(cityObject.getString("name")); 
      } 
     } catch (JSONException e) { 
      Log.i(TAG ,"Improper JSON string"); 
     } 

     ListPreference listPreference = (ListPreference) findPreference("CityList"); 
     listPreference.setEntries(entries.toArray(new String[entries.size()])); 
     listPreference.setEntryValues(entryValues.toArray(new String[entryValues.size()])); 
    } 

} 

喜好.XML

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 

     <ListPreference 
      android:key="CityList" 
      android:title="Cities" /> 

</PreferenceScreen> 
+0

嗯,问题是我必须在我的应用程序中使用API​​ 11来处理其他事情,并且即时使用PreferenceFragment,我无法使用FindPreference ... 但是,无论如何,最好的办法是让代码不压制任何东西。 – Sono 2014-12-03 21:06:44

+0

好吧,如果你想使用API​​ lvl 11作为最低要求的sdk,那么请使用PreferenceFragment,然后按照本教程[PreferenceFragment](http://android-er.blogspot.com/2012/07/example-of-使用-preferencefragment.html)。你有样品的整个工作代码。只需复制并粘贴到IDE。它显示必须使用PreferenceFragment创建应用程序。在这个'PreferenceFragment'中,你可以使用我放在解决方案的'onCreate'方法中的代码来解析JSON对象并把结果放到'ListPreference'中。 – 2014-12-03 21:23:35

+0

'PreferenceFragment'方法'findPreference'不被弃用 - 而且它自API 11以来就可用。 – 2014-12-03 21:25:45

0

查看有关findPreference方法弃用的信息findPreference。 如果您使用的API低于11,则必须遵循PreferenceActivity(和findPreference弃用的方法)或实施自定义PreferenceFragment PreferenceFragment。否则使用PreferenceFragment API。要设置在ListPreference中显示的值,请使用ListPreference类的setEntriessetEntryValues方法。

+0

谢谢为了答案,但我找到了很多指南,只是我无法理解他们......你能举个例子吗? – Sono 2014-12-03 13:57:04

0
public static void callWebService() { 

    try { 

     // make web service connection 
     HttpPost request = new HttpPost(
       "http://ptk.com/mobile/Service.svc/PostComments"); 
     request.setHeader("Accept", "application/json"); 
     request.setHeader("Content-type", "application/json"); 
     // Build JSON string 
     JSONStringer TestApp = new JSONStringer().object() 
       .key("NewsItemId").value("1").key("Comments") 
       .value("manish").key("FullName").value("androidhub") 
       .key("Location").value("india").key("Email") 
       .value("[email protected]").key("Type") 
       .value("News").endObject(); 
     StringEntity entity = new StringEntity(TestApp.toString()); 

     Log.d("****Parameter Input****", "Webservice Testing:" + TestApp); 
     request.setEntity(entity); 
     // Send request to WCF service 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpResponse response = httpClient.execute(request); 

     Log.d("WebInvoke", "Saving: " + response.getStatusLine().toString()); 
     // Get the status of web service 
     BufferedReader rd = new BufferedReader(new InputStreamReader(
       response.getEntity().getContent())); 
     // print status in log 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      Log.d("****Status Line***", "Webservice Response: " + line); 

     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
     Log.d("****Status Line***", 
       "Webservice Exception: " + e.getMessage()); 
    } 

} 
+0

我没有得到这个意思:/请问你能解释一下这对我有什么用? – Sono 2014-12-03 21:08:19