获取JSON数据到列表 [英] Fetch JSON Data into List

查看:212
本文介绍了获取JSON数据到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只得到第一个事件的天使在名称列表,无论我做第二或第三个事件或任何其他事件挖掘..

我想,只要用户不敲击事件本田汽车需要出示天使A和B,每当用户做水龙头的事件塔塔汽车需要出示天使C&放大器; ð....我在我的JSON大约200事件和1000的天使,有50某些事件或某种有200天使,但我需要显示窃听事件只天使.....

JSON: -

  [
    {
     eventName的:本田汽车,
     angelList:[
    {
    angelID:1,
        angelName:天使A
    },
    {
    angelID:2,
        angelName:天使B
    }
    ]
   },
    {
     eventName的:塔塔汽车
     angelList:[
    {
    angelID:1,
        angelName:天使C
    },
    {
    angelID:2,
        angelName:天使D
    }
    ]
   }
 ]

为例,首先是事件名称本田汽车,有两个天使天使A,B和第二个事件名称是塔塔汽车公司,这一事件有两个天使天使,即C,天使ð....,我的问题是,每当我做轻按塔塔汽车公司获得天使A,天使的B列表,而不是显示天使C,天使ð...

code: -

  //创建JSON解析器对象
        JSONParser jsonParser =新JSONParser();        ArrayList的<&HashMap的LT;字符串,字符串>> angelsList;        //天使JSONArray
        JSONArray arrayAngels = NULL;保护字符串doInBackground(字符串参数... args){
                清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
                // URL从获取JSON字符串
                JSON字符串= jsonParser.makeHtt prequest(EventsActivity.URL_JSON,GET,则params);
                的JSONObject jsonData;
                尝试{
                    jsonData =新JSONArray(JSON).getJSONObject(0);
                    arrayAngels = jsonData.optJSONArray(angelList);                    如果(arrayAngels!= NULL){                        //通过所有天使循环
                        的for(int i = 0; I< arrayAngels.length();我++){
                            JSONObject的C = arrayAngels.getJSONObject(I)
                            //存储在变量中的每个JSON项值
                            字符串名称= c.getString(ANGEL_NAME);
                            //创建新的HashMap
                            HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                            //将每个子节点的HashMap键=>值
                            map.put(ANGEL_NAME,名);
                            //添加HashList到ArrayList的
                            angelsList.add(地图);
                        }
                    }
                }赶上(JSONException E){
                    e.printStackTrace();
               }
                返回null;
            }

完成code: -

 公共类AngelsActivity扩展ListActivity {        //连接器
        ConnectionDetector CD;        //警报对话框经理
        AlertDialogManager警报=新AlertDialogManager();        //进度对话框
        私人ProgressDialog pDialog;        //创建JSON解析器对象
        JSONParser jsonParser =新JSONParser();        ArrayList的<&HashMap的LT;字符串,字符串>> angelsList;        //天使JSONArray
        JSONArray arrayAngels = NULL;        字符串intentEvents = NULL;        公共静态最后弦乐LOG_TAG =AngelsActivity;        // JSON节点名称
        私有静态最后弦乐ANGEL_NAME =angelName;        @覆盖
        公共无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.activity_list);            CD =新ConnectionDetector(getApplicationContext());            //检查互联网连接
            如果(!cd.isConnectingToInternet()){
                //没有Internet连接present
                alert.showAlertDialog(AngelsActivity.this,网络连接错误
                        请连接的Internet连接,FALSE);
                //停止执行回code
                返回;
            }            //获取事件名称使用意图(来自EventsActivity)
            意向I = getIntent();
            intentEvents =(i.getStringExtra(EVENT_NAME));            //为哈希映射的ListView
            angelsList =新的ArrayList<&HashMap的LT;字符串,字符串>>();            //加载天使JSON在后台线程
            新LoadAngels()执行();            //获取列表视图
            ListView控件LV = getListView();            lv.setOnItemClickListener(新android.widget.AdapterView.OnItemClickListener(){
                @覆盖
                公共无效onItemClick(适配器视图<>为arg0,观景,INT ARG2,
                        长ARG3){                }
            });
        }        / **
         *背景异步任务通过HTTP请求加载所有天使
         * * /
        类LoadAngels扩展的AsyncTask<字符串,字符串,字符串> {            / **
             *启动后台线程显示进度对话框之前
             * * /
            @覆盖
            在preExecute保护无效(){
                super.on preExecute();
                pDialog =新ProgressDialog(AngelsActivity.this);
                pDialog.setMessage(加载数据......);
                pDialog.setIndeterminate(假);
                pDialog.setCancelable(假);
                pDialog.show();
            }            保护字符串doInBackground(字符串参数... args){
                清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
                // URL从获取JSON字符串
                JSON字符串= jsonParser.makeHtt prequest(EventsActivity.URL_JSON,GET,则params);
                JSONArray jsonData;
                尝试{
                    jsonData =新JSONArray(JSON);
                    对于(INT J = 0; J< jsonData.length(); J ++){
                        arrayAngels = jsonData.getJSONObject(J).optJSONArray(angelList);                    如果(arrayAngels!= NULL){                        //通过所有天使循环
                        的for(int i = 0; I< arrayAngels.length();我++){
                            Log.d(AngelsActivity.LOG_TAGarrayAngels.length+ arrayAngels.length());
                            JSONObject的C = arrayAngels.getJSONObject(I)
                            //存储在变量中的每个JSON项值
                            字符串名称= c.getString(ANGEL_NAME);
                            //创建新的HashMap
                            HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                            //将每个子节点的HashMap键=>值
                            map.put(ANGEL_NAME,名);
                            //添加HashList到ArrayList的
                            angelsList.add(地图);
                        }
                    }
                    }
                }赶上(JSONException E){
                    e.printStackTrace();
               }
                返回null;
            }            / **
             *在完成后台任务之后辞退进度对话框
             * ** /
            保护无效onPostExecute(字符串FILE_URL){
                //让所有天使后关闭该对话框
                pDialog.dismiss();
                //从后台线程更新界面
                runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        / **
                         *更新解析JSON数据到ListView控件
                         * * /
                        ListAdapter适配器=新SimpleAdapter(
                                AngelsActivity.this,angelsList,
                                R.layout.list_item,
                                新的String [] {} ANGEL_NAME,
                                新的INT [] {R.id.name});                        //更新列表视图
                        setListAdapter(适配器);                        与事件名称//改变活动标题
                        的setTitle(intentEvents);
                    }
                });
            }
        }
    }


解决方案

在您的适配器,变化
jsonData =新JSONArray(JSON).getJSONObject(0); jsonData =新JSONArray(JSON).getJSONObject(yourPosition);

Getting only first Event's Angel Names in a List, either i do tap on second or third event or any other Event..

i want whenever user do tap on Event Honda Motors need to show Angel A & B, and whenever user do tap on Event Tata Motors need to show Angel C & D....i have around 200 events in my json and over 1000 angels, some events having 50 or some having 200 angels, but i need to show Angels for tapped Event only.....

JSON :-

[
    {
     "eventName" : "Honda Motors",
     "angelList" : [
    {
    "angelID": "1",
        "angelName": "Angel A"
    },
    {
    "angelID": "2",
        "angelName": "Angel B"
    }
    ]
   },


    {
     "eventName" : "Tata Motors",
     "angelList" : [
    {
    "angelID": "1",
        "angelName": "Angel C"
    },
    {
    "angelID": "2",
        "angelName": "Angel D"
    }
    ]
   }
 ]

for an example, first EventName is Honda Motors, having two Angels Angel A, B and second EventName is Tata Motors, this event has two more Angels namely Angel C, Angel D .... and my issue is whenever i do tap on Tata Motors getting Angel A, Angel B in a List, instead of showing Angel C, Angel D...

Code :-

// Creating JSON Parser object
        JSONParser jsonParser = new JSONParser();

        ArrayList<HashMap<String, String>> angelsList;

        // angels JSONArray
        JSONArray arrayAngels = null;

protected String doInBackground(String... args) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                String json = jsonParser.makeHttpRequest(EventsActivity.URL_JSON, "GET", params);
                JSONObject jsonData;
                try {
                    jsonData = new JSONArray(json).getJSONObject(0);
                    arrayAngels = jsonData.optJSONArray("angelList");

                    if (arrayAngels != null) {

                        // looping through all angels
                        for (int i = 0; i < arrayAngels.length(); i++) {
                            JSONObject c = arrayAngels.getJSONObject(i);
                            // Storing each json item values in variable
                            String name = c.getString(ANGEL_NAME);                            
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();
                            // adding each child node to HashMap key => value
                            map.put(ANGEL_NAME, name);                          
                            // adding HashList to ArrayList
                            angelsList.add(map);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
               }
                return null;
            }

Complete code:-

public class AngelsActivity extends ListActivity {

        // Connection detector
        ConnectionDetector cd;

        // Alert dialog manager
        AlertDialogManager alert = new AlertDialogManager();

        // Progress Dialog
        private ProgressDialog pDialog;

        // Creating JSON Parser object
        JSONParser jsonParser = new JSONParser();

        ArrayList<HashMap<String, String>> angelsList;

        // angels JSONArray
        JSONArray arrayAngels = null;

        String intentEvents = null;

        public static final String LOG_TAG = "AngelsActivity";

        // JSON node names
        private static final String ANGEL_NAME = "angelName";

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

            cd = new ConnectionDetector(getApplicationContext());

            // Check for internet connection
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                alert.showAlertDialog(AngelsActivity.this, "Internet Connection Error",
                        "Please connect to working Internet connection", false);
                // stop executing code by return
                return;
            }

            // Get EventName using Intent (from EventsActivity)
            Intent i = getIntent();
            intentEvents = (i.getStringExtra("event_name"));

            // Hashmap for ListView
            angelsList = new ArrayList<HashMap<String, String>>();

            // Loading Angels JSON in Background Thread
            new LoadAngels().execute();

            // get listview
            ListView lv = getListView();

            lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                        long arg3) {

                }
            });     
        }

        /**
         * Background Async Task to Load all Angels by making http request
         * */
        class LoadAngels extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(AngelsActivity.this);
                pDialog.setMessage("Loading Data ...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            protected String doInBackground(String... args) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                String json = jsonParser.makeHttpRequest(EventsActivity.URL_JSON, "GET", params);
                JSONArray jsonData;
                try {
                    jsonData = new JSONArray(json);
                    for (int j = 0; j < jsonData.length(); j++) {
                        arrayAngels = jsonData.getJSONObject(j).optJSONArray("angelList");

                    if (arrayAngels != null) {

                        // looping through all angels
                        for (int i = 0; i < arrayAngels.length(); i++) {
                            Log.d(AngelsActivity.LOG_TAG, "arrayAngels.length " + arrayAngels.length());
                            JSONObject c = arrayAngels.getJSONObject(i);
                            // Storing each json item values in variable
                            String name = c.getString(ANGEL_NAME);                            
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();
                            // adding each child node to HashMap key => value
                            map.put(ANGEL_NAME, name);                          
                            // adding HashList to ArrayList
                            angelsList.add(map);
                        }
                    }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
               }
                return null;
            }

            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all angels
                pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */
                        ListAdapter adapter = new SimpleAdapter(
                                AngelsActivity.this, angelsList,
                                R.layout.list_item, 
                                new String[] {ANGEL_NAME}, 
                                new int[] {R.id.name });

                        // updating listview
                        setListAdapter(adapter);

                        // Change activity Title with Event Name
                        setTitle(intentEvents);
                    }
                });
            }
        }
    }

解决方案

In your adapter, change jsonData = new JSONArray(json).getJSONObject(0); by jsonData = new JSONArray(json).getJSONObject(yourPosition);

这篇关于获取JSON数据到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆