android - 将 JSON 数据加载到 android listpreference

标签 android json sharedpreferences listpreference

我有一个问题。我已经阅读了很多论坛和主题,但我不明白如何创建一个类文件来加载 JSON 数据,例如:

{"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);

        }
    }

}

提前致谢,并对我的英语不好表示歉意!

最佳答案

好吧,在最简单的情况下,当您想要支持 API <11 并使用 PreferenceActivity 时,您可以通过以下方式使用从 JSON 对象读取的数据填充 ListPreference:

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>

关于android - 将 JSON 数据加载到 android listpreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27272583/

相关文章:

sql - Postgresql:通过通配符和带索引的比较运算符在 JSON 数组中查找值

android - sharedpreferences 返回空值

android - 隐藏应用程序图标并运行它

Android:直接启动正在开发的 Activity/fragment

java - 使用 MVVM 架构从 FireStore 检索数据

json - 使用 JSON 进行 HTTP 响应

java - ScaleGestureDetector 不工作不显示任何内容

javascript - 需要从ajax加载的JSON对象动态构建 Angular 复选框

android - 这是在 android 的本地内存中存储自定义数组列表的更好方法

java - 共享首选项不应用更改