android – 从JSON获取数据到List View

android – 从JSON获取数据到List View,第1张

概述我试图从 JSON获取数据到ListView,但每次我得到空白页,既没有获得类别列表也没有错误. 我是Android的新手,并尝试使用JSON制作多级ListView, 在我的情况下,我想只使用JSON实现这一点:类别>项目>详情 但我在第一个屏幕上遇到问题,甚至无法获取类别 JSON: { "categoryId": "1", "categoryTitle": { "SmartP 我试图从 JSON获取数据到ListVIEw,但每次我得到空白页,既没有获得类别列表也没有错误.

我是Android的新手,并尝试使用JsON制作多级ListVIEw,

在我的情况下,我想只使用JsON实现这一点:类别>项目>详情

但我在第一个屏幕上遇到问题,甚至无法获取类别

JsON:

{    "categoryID": "1","categoryTitle": { "SmartPhones": [            {                "itemID": "1","itemTitle": "galaxy Mega 5.8"            },{                "itemID": "2","itemTitle": "galaxy Mega 6.3"            }        ]    },"categoryID": "2","categoryTitle": { "tablets": [        {            "itemID": "1","itemTitle": "galaxy Note 510"        },{            "itemID": "2","itemTitle": "galaxy Note 800"        }    ]}}

谢谢@Segi给我正确的JsON格式

活动代码:

public class CategorIEsActivity extends ListActivity {// Connection detectorConnectionDetector cd;// Alert dialog managerAlertDialogManager alert = new AlertDialogManager();// Progress Dialogprivate ProgressDialog pDialog;// Creating JsON Parser objectJsONParser JsonParser = new JsONParser();ArrayList<HashMap<String,String>> categorIEsList;// albums JsONArrayJsONArray categorIEs = null;// albums JsON urlprivate static final String URL_CATEGORIES = "my.Json"; // provIDing proper URL// ALL JsON node namesprivate static final String TAG_ID = "categoryID";private static final String TAG_Title = "categoryTitle";@OverrIDepublic voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_albums);    cd = new ConnectionDetector(getApplicationContext());    // Check for internet connection    if (!cd.isConnectingToInternet()) {        // Internet Connection is not present        alert.showAlertDialog(CategorIEsActivity.this,"Internet Connection Error","Please connect to working Internet connection",false);        // stop executing code by return        return;    }    // Hashmap for ListVIEw    categorIEsList = new ArrayList<HashMap<String,String>>();    // Loading CategorIEs JsON in Background Thread    new LoadCategorIEs().execute();    // get ListvIEw    ListVIEw lv = getListVIEw();    /**     * ListvIEw item click Listener     * ProductListActivity will be lauched by passing category ID     * */    lv.setonItemClickListener(new androID.Widget.AdapterVIEw.OnItemClickListener() {        @OverrIDe        public voID onItemClick(AdapterVIEw<?> arg0,VIEw vIEw,int arg2,long arg3) {            // on selecting a single category            // ProductListActivity will be launched to show products insIDe the category            Intent i = new Intent(getApplicationContext(),TrackListActivity.class);            // send category ID to productList activity to get List of products under that category            String category_ID = ((TextVIEw) vIEw.findVIEwByID(R.ID.album_ID)).getText().toString();            i.putExtra("category_ID",category_ID);                         startActivity(i);        }    });     }/** * Background Async Task to Load all CategorIEs by making http request * */class LoadCategorIEs extends AsyncTask<String,String,String> {    /**     * Before starting background thread Show Progress Dialog     * */    @OverrIDe    protected voID onPreExecute() {        super.onPreExecute();        pDialog = new ProgressDialog(CategorIEsActivity.this);        pDialog.setMessage("Listing CategorIEs ...");        pDialog.setIndeterminate(false);        pDialog.setCancelable(false);        pDialog.show();    }    /**     * getting CategorIEs JsON     * */    protected String doInBackground(String... args) {        // Building Parameters        List<nameValuePair> params = new ArrayList<nameValuePair>();        // getting JsON string from URL        String Json = JsonParser.makehttpRequest(URL_CATEGORIES,"GET",params);        // Check your log cat for JsON reponse        Log.d("CategorIEs JsON: ","> " + Json);        try {                           categorIEs = new JsONArray(Json);            if (categorIEs != null) {                // looPing through all categorIEs                for (int i = 0; i < categorIEs.length(); i++) {                    JsONObject c = categorIEs.getJsONObject(i);                    // Storing each Json item values in variable                    String ID = c.getString(TAG_ID);                    String Title = c.getString(TAG_Title);                    // creating new HashMap                    HashMap<String,String> map = new HashMap<String,String>();                    // adding each child node to HashMap key => value                    map.put(TAG_ID,ID);                    map.put(TAG_Title,Title);                    // adding HashList to ArrayList                    categorIEsList.add(map);                }            }else{                Log.d("CategorIEs: ","null");            }        } 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 categorIEs        pDialog.dismiss();        // updating UI from Background Thread        runOnUiThread(new Runnable() {            public voID run() {                /**                 * Updating parsed JsON data into ListVIEw                 * */                listadapter adapter = new SimpleAdapter(                        CategorIEsActivity.this,categorIEsList,R.layout.List_item_albums,new String[] { TAG_ID,TAG_Title },new int[] {                                R.ID.category_ID,R.ID.category_Title });                // updating ListvIEw                setlistadapter(adapter);      }     });   }  }}

logcat的:

06-15 12:21:27.124: D/dalvikvm(786): GC_FOR_ALLOC freed 68K,8% free 2488K/2680K,paused 173ms,total 213ms06-15 12:21:27.174: I/dalvikvm-heap(786): Grow heap (frag case) to 3.152MB for 635812-byte allocation06-15 12:21:27.264: D/dalvikvm(786): GC_FOR_ALLOC freed 1K,6% free 3108K/3304K,paused 89ms,total 89ms06-15 12:21:27.354: D/dalvikvm(786): GC_CONCURRENT freed <1K,6% free 3111K/3304K,paused 5ms+3ms,total 95ms06-15 12:21:28.274: I/Choreographer(786): Skipped 41 frames!  The application may be doing too much work on its main thread.06-15 12:21:28.874: I/Choreographer(786): Skipped 123 frames!  The application may be doing too much work on its main thread.06-15 12:21:29.044: D/gralloc_goldfish(786): Emulator without GPU emulation detected.06-15 12:21:29.134: D/dalvikvm(786): GC_CONCURRENT freed 19K,4% free 3478K/3620K,paused 8ms+38ms,total 268ms06-15 12:21:30.894: I/Choreographer(786): Skipped 51 frames!  The application may be doing too much work on its main thread.06-15 12:20:36.624: D/CategorIEs JsON:(786): > {06-15 12:20:36.624: D/CategorIEs JsON:(786):     "categoryID": "1",06-15 12:20:36.624: D/CategorIEs JsON:(786):     "categoryTitle": {06-15 12:20:36.624: D/CategorIEs JsON:(786):         "SmartPhones": [06-15 12:20:36.624: D/CategorIEs JsON:(786):             {06-15 12:20:36.624: D/CategorIEs JsON:(786):                 "itemID": "1",06-15 12:20:36.624: D/CategorIEs JsON:(786):                 "itemTitle": "galaxy Mega 5.8"06-15 12:20:36.624: D/CategorIEs JsON:(786):             },06-15 12:20:36.624: D/CategorIEs JsON:(786):             {06-15 12:20:36.624: D/CategorIEs JsON:(786):                 "itemID": "2",06-15 12:20:36.624: D/CategorIEs JsON:(786):                 "itemTitle": "galaxy Mega 6.3"06-15 12:20:36.624: D/CategorIEs JsON:(786):             }06-15 12:20:36.624: D/CategorIEs JsON:(786):         ]06-15 12:20:36.624: D/CategorIEs JsON:(786):     },06-15 12:20:36.624: D/CategorIEs JsON:(786):     "categoryID": "2",06-15 12:20:36.624: D/CategorIEs JsON:(786):     "categoryTitle": {"tablets": [06-15 12:20:36.624: D/CategorIEs JsON:(786):         {06-15 12:20:36.624: D/CategorIEs JsON:(786):             "itemID": "1",06-15 12:20:36.624: D/CategorIEs JsON:(786):             "itemTitle": "galaxy Note 510"06-15 12:20:36.624: D/CategorIEs JsON:(786):         },06-15 12:20:36.624: D/CategorIEs JsON:(786):         {06-15 12:20:36.624: D/CategorIEs JsON:(786):             "itemID": "2",06-15 12:20:36.624: D/CategorIEs JsON:(786):             "itemTitle": "galaxy Note 800"06-15 12:20:36.624: D/CategorIEs JsON:(786):         }06-15 12:20:36.624: D/CategorIEs JsON:(786):     ]}06-15 12:20:36.624: D/CategorIEs JsON:(786): }06-15 12:20:36.814: W/System.err(786): org.Json.JsONException: Value {"categoryTitle":{"SmartPhones":[{"itemID":"1","itemTitle":"galaxy Mega 5.8"},{"itemID":"2","itemTitle":"galaxy Mega 6.3"}]},"categoryID":"2"} of type org.Json.JsONObject cannot be converted to JsONArray06-15 12:20:36.824: W/System.err(786):  at org.Json.JsON.typeMismatch(JsON.java:111)06-15 12:20:36.836: W/System.err(786):  at org.Json.JsONArray.<init>(JsONArray.java:91)06-15 12:20:36.836: W/System.err(786):  at org.Json.JsONArray.<init>(JsONArray.java:103)06-15 12:20:36.904: W/System.err(786):  at com.my.Json.CategorIEsActivity$LoadCategorIEs.doInBackground(CategorIEsActivity.java:135)06-15 12:20:36.904: W/System.err(786):  at com.my.Json.CategorIEsActivity$LoadCategorIEs.doInBackground(CategorIEsActivity.java:1)06-15 12:20:36.914: W/System.err(786):  at androID.os.AsyncTask.call(AsyncTask.java:287)06-15 12:20:36.914: W/System.err(786):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)06-15 12:20:36.925: W/System.err(786):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)06-15 12:20:36.925: W/System.err(786):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)06-15 12:20:36.934: W/System.err(786):  at java.lang.Thread.run(Thread.java:856)06-15 12:20:45.984: D/inputEventConsistencyVerifIEr(786): KeyEvent: ACTION_UP but key was not down.06-15 12:20:45.984: D/inputEventConsistencyVerifIEr(786):   in androID.vIEw.VIEwRootImpl@40de89c806-15 12:20:45.984: D/inputEventConsistencyVerifIEr(786):   0: sent at 106936000000,KeyEvent { action=ACTION_UP,keyCode=KEYCODE_MENU,scanCode=229,MetaState=0,flags=0x8,repeatCount=0,eventTime=106936,downTime=106820,deviceid=0,source=0x101 }

注意:获取空白活动,而不是将数据导入ListVIEw,没有收到任何错误

解决方法 JsON是有效的,但不合逻辑,应该是这样的
[{"categoryID": "1","categoryTitle": "SmartPhones","SmartPhones": [        {            "itemID": "1","itemTitle": "galaxy Mega 5.8"        },"itemTitle": "galaxy Mega 6.3"        }    ]},{"categoryID": "1","categoryTitle": "tablets","tablets": [        {            "itemID": "1","itemTitle": "galaxy Mega 6.3"        }    ]}]

那么代码将是:

if (categorIEs != null) {                // looPing through All albums                for (int i = 0; i < categorIEs.length(); i++) {                    JsONObject onecategory = categorIEs.getJsONObject(i);                    String categoryname = onecategory.getString(TAG_ID);                    String catTitle = onecategory.getString( TAG_Title );                    JsONArray categoryTitle = onecategory.getJsONArray(catTitle);                    for( int i = 0 ; i < categoryTitle.length() ; i++ )                    {                         JsONObject item = categoryTitle.getJsONObject(i);                         String ID = item.getString("itemID");                         String name = item.getString("itemTitle");                         // creating new HashMap                         HashMap<String,String>();                         // adding each child node to HashMap key => value                         map.put(TAG_ID,ID);                         map.put(TAG_Title,name);                    }                    // adding HashList to ArrayList                    categorIEsList.add(map);                }            }else{                Log.d("CategorIEs: ","null");            }
总结

以上是内存溢出为你收集整理的android – 从JSON获取数据到List View全部内容,希望文章能够帮你解决android – 从JSON获取数据到List View所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1140952.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存