android - 明智地从 JSON 类别中获取数据

标签 android json android-listview

我正在编写一个应用程序,其中我从 JSON 中获取数据,并且我能够获取类别列表,但每当我点击任何类别时未获得该特定类别下的产品列表总是获得空白 Activity

JSON:

[
{
"categoryId": "1",
"categoryTitle": "SmartPhones", "SmartPhones": [
        {
            "itemId": "1",
            "itemTitle": "Galaxy Mega 5.8"
        },
        {
            "itemId": "2",
            "itemTitle": "Galaxy Mega 6.3"
        }
    ]
},
{
"categoryId": "2",
"categoryTitle": "Tablets", "Tablets": [
        {
            "itemId": "1",
            "itemTitle": "Galaxy Note 510"
        },
        {
            "itemId": "2",
            "itemTitle": "Galaxy Note 800"
        }
    ]
}
]

AlbumsActivity.java [用于类别]:

public class AlbumsActivity 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>> albumsList;

    // albums JSONArray
    JSONArray albums = null;

    // albums JSON url
    private static final String URL_ALBUMS = "my.json"; //providing proper URL

    // ALL JSON node names
    private static final String TAG_ID = "categoryId";
    private static final String TAG_NAME = "categoryTitle";


    @Override
    public 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(AlbumsActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

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

        // Loading Albums JSON in Background Thread
        new LoadAlbums().execute();

        // get listview
        ListView lv = getListView();

        /**
         * Listview item click listener
         * TrackListActivity will be lauched by passing album id
         * */
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {
                // on selecting a single album
                // TrackListActivity will be launched to show tracks inside the album
                Intent i = new Intent(getApplicationContext(), TrackListActivity.class);

                // send album id to tracklist activity to get list of songs under that album
                String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
                i.putExtra("album_id", album_id);               

                startActivity(i);
            }
        });     
    }

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

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

        /**
         * getting Albums JSON
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // getting JSON string from URL
            String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                    params);

            // Check your log cat for JSON reponse
            Log.d("Albums JSON: ", "> " + json);

            try {               
                albums = new JSONArray(json);

                if (albums != null) {
                    // looping through All albums
                    for (int i = 0; i < albums.length(); i++) {
                        JSONObject c = albums.getJSONObject(i);

                        // Storing each json item values in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);


                        // 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_NAME, name);


                        // adding HashList to ArrayList
                        albumsList.add(map);
                    }
                }else{
                    Log.d("Albums: ", "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 albums
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AlbumsActivity.this, albumsList,
                            R.layout.list_item_albums, new String[] { TAG_ID,
                                    TAG_NAME }, new int[] {
                                    R.id.album_id, R.id.album_name });

                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

TrackListActivity.java [用于产品]:

public class TrackListActivity 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>> tracksList;

    // tracks JSONArray
    JSONArray albums = null;

    // Album id
    String album_id, album_name;

    // tracks JSON url
    // id - should be posted as GET params to get track list (ex: id = 5)
    private static final String URL_ALBUMS = "my.json"; //providing proper url

    // ALL JSON node names

    private static final String TAG_ID = "itemId";
    private static final String TAG_NAME = "itemTitle";
    private static final String TAG_ALBUM = "categoryId";

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

        cd = new ConnectionDetector(getApplicationContext());

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

        // Get album id
        Intent i = getIntent();
        album_id = i.getStringExtra("album_id");

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

        // Loading tracks in Background Thread
        new LoadTracks().execute();

        // get listview
        ListView lv = getListView();

        /**
         * Listview on item click listener
         * SingleTrackActivity will be lauched by passing album id, song id
         * */
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {
                // On selecting single track get song information
                Intent i = new Intent(getApplicationContext(), SingleTrackActivity.class);

                // to get song information
                // both album id and song is needed
                String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
                String song_id = ((TextView) view.findViewById(R.id.song_id)).getText().toString();

                Toast.makeText(getApplicationContext(), "Album Id: " + album_id  + ", Song Id: " + song_id, Toast.LENGTH_SHORT).show();

                i.putExtra("album_id", album_id);
                i.putExtra("song_id", song_id);

                startActivity(i);
            }
        }); 

    }

    /**
     * Background Async Task to Load all tracks under one album
     * */
    class LoadTracks extends AsyncTask<String, String, String> {

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

        /**
         * getting tracks json and parsing
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // post album id as GET parameter
            params.add(new BasicNameValuePair(TAG_ID, album_id));

            // getting JSON string from URL
            String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                    params);

            // Check your log cat for JSON reponse
            Log.d("Track List JSON: ", json);

            try {
                JSONObject jObj = new JSONObject(json);
                if (jObj != null) {
                    String album_id = jObj.getString(TAG_ID);
                    album_name = jObj.getString(TAG_ALBUM);


                    if (albums != null) {
                        // looping through All songs
                        for (int i = 0; i < albums.length(); i++) {
                            JSONObject c = albums.getJSONObject(i);

                            // Storing each json item in variable
                            String song_id = c.getString(TAG_ID);
                            String name = c.getString(TAG_NAME);


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

                            // adding each child node to HashMap key => value
                            map.put("album_id", album_id);
                            map.put(TAG_ID, song_id);                           
                            map.put(TAG_NAME, name);


                            // adding HashList to ArrayList
                            tracksList.add(map);
                        }
                    } else {
                        Log.d("Albums: ", "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 tracks
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            TrackListActivity.this, tracksList,
                            R.layout.list_item_tracks, new String[] { "album_id", TAG_ID,
                                    TAG_NAME }, new int[] {
                                    R.id.album_id, R.id.song_id, R.id.album_name });
                    // updating listview
                    setListAdapter(adapter);

                    // Change Activity Title with Album name
                    setTitle(album_name);
                }
            });

        }

    }
}

最佳答案

您将来自网络服务的 JSON 读取到一个 JSONObject 中,但是您发布的 JSON 是一个 JSONArray。尝试这样的事情来解析你的 JSON...

            JSONArray jObj = new JSONArray(json);
            if (jObj != null) {
                for(int i = 0; i < jObj.length(); i++) {
                   JSONObject cat = jObj.getJSONObject(i);
                   String id = cat.getString("categoryId");
                   String title = cat.getString("categoryTitle");
                   JSONArray devices = cat.optJSONArray(title, null);

                   for(int j=0; i<devices.length(); j++) {
                       //get itemId and itemTitle
                   }
                }
            }

关于android - 明智地从 JSON 类别中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141256/

相关文章:

android - 在对话框的 ListView 中获取数据时出错?

android - 如何在 intent-filter 的数据标签中指定方案特定部分?

java - 安卓/Java : Set textview with char from index of string

javascript - 传递的 Json 不被 Controller 接受

java - 如何在java中解码具有 'default'类属性的json字符串?

java - 使用微调器过滤 map 标记

java - ListView 中的按钮 OnClickListener

java - android 在新线程中运行类

java - 使用 http-post 和 AsyncTask 将数据插入 MySQL 不起作用

android - 带有大图像的 ListView 非常慢