Advertisement
samadhanmedge

JSON Parsing

Dec 29th, 2012
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.09 KB | None | 0 0
  1. // AlbumsActivity.java
  2. package com.example.jsonapp;
  3.  
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7.  
  8. import org.apache.http.NameValuePair;
  9. import org.json.JSONArray;
  10. import org.json.JSONException;
  11. import org.json.JSONObject;
  12.  
  13. import android.app.ListActivity;
  14. import android.app.ProgressDialog;
  15. import android.content.Intent;
  16. import android.os.AsyncTask;
  17. import android.os.Bundle;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.widget.AdapterView;
  21. import android.widget.ListAdapter;
  22. import android.widget.ListView;
  23. import android.widget.SimpleAdapter;
  24. import android.widget.TextView;
  25.  
  26. import com.example.helper.AlertDialogManager;
  27. import com.example.helper.ConnectionDetector;
  28. import com.example.helper.JSONParser;
  29.  
  30. public class AlbumsActivity extends ListActivity {
  31.     // Connection detector
  32.     ConnectionDetector cd;
  33.    
  34.     // Alert dialog manager
  35.     AlertDialogManager alert = new AlertDialogManager();
  36.    
  37.     // Progress Dialog
  38.     private ProgressDialog pDialog;
  39.  
  40.     // Creating JSON Parser object
  41.     JSONParser jsonParser = new JSONParser();
  42.  
  43.     ArrayList<HashMap<String, String>> albumsList;
  44.  
  45.     // albums JSONArray
  46.     JSONArray albums = null;
  47.  
  48.     // albums JSON url
  49.     private static final String URL_ALBUMS = "http://api.androidhive.info/songs/albums.php";
  50.  
  51.     // ALL JSON node names
  52.     private static final String TAG_ID = "id";
  53.     private static final String TAG_NAME = "name";
  54.     private static final String TAG_SONGS_COUNT = "songs_count";
  55.  
  56.     @Override
  57.     public void onCreate(Bundle savedInstanceState) {
  58.         super.onCreate(savedInstanceState);
  59.         setContentView(R.layout.activity_albums);
  60.        
  61.         cd = new ConnectionDetector(getApplicationContext());
  62.          
  63.         // Check for internet connection
  64.         if (!cd.isConnectingToInternet()) {
  65.             // Internet Connection is not present
  66.             alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
  67.                     "Please connect to working Internet connection", false);
  68.             // stop executing code by return
  69.             return;
  70.         }
  71.  
  72.         // Hashmap for ListView
  73.         albumsList = new ArrayList<HashMap<String, String>>();
  74.  
  75.         // Loading Albums JSON in Background Thread
  76.         new LoadAlbums().execute();
  77.        
  78.         // get listview
  79.         ListView lv = getListView();
  80.        
  81.         /**
  82.          * Listview item click listener
  83.          * TrackListActivity will be lauched by passing album id
  84.          * */
  85.         lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
  86.             @Override
  87.             public void onItemClick(AdapterView<?> arg0, View view, int arg2,
  88.                     long arg3) {
  89.                 // on selecting a single album
  90.                 // TrackListActivity will be launched to show tracks inside the album
  91.                 Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
  92.                
  93.                 // send album id to tracklist activity to get list of songs under that album
  94.                 String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
  95.                 i.putExtra("album_id", album_id);              
  96.                
  97.                 startActivity(i);
  98.             }
  99.         });    
  100.     }
  101.  
  102.     /**
  103.      * Background Async Task to Load all Albums by making http request
  104.      * */
  105.     class LoadAlbums extends AsyncTask<String, String, String> {
  106.  
  107.         /**
  108.          * Before starting background thread Show Progress Dialog
  109.          * */
  110.         @Override
  111.         protected void onPreExecute() {
  112.             super.onPreExecute();
  113.             pDialog = new ProgressDialog(AlbumsActivity.this);
  114.             pDialog.setMessage("Listing Albums ...");
  115.             pDialog.setIndeterminate(false);
  116.             pDialog.setCancelable(false);
  117.             pDialog.show();
  118.         }
  119.  
  120.         /**
  121.          * getting Albums JSON
  122.          * */
  123.         protected String doInBackground(String... args) {
  124.             // Building Parameters
  125.             List<NameValuePair> params = new ArrayList<NameValuePair>();
  126.  
  127.             // getting JSON string from URL
  128.             String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
  129.                     params);
  130.  
  131.             // Check your log cat for JSON reponse
  132.             Log.d("Albums JSON: ", "> " + json);
  133.  
  134.             try {              
  135.                 albums = new JSONArray(json);
  136.                
  137.                 if (albums != null) {
  138.                     // looping through All albums
  139.                     for (int i = 0; i < albums.length(); i++) {
  140.                         JSONObject c = albums.getJSONObject(i);
  141.  
  142.                         // Storing each json item values in variable
  143.                         String id = c.getString(TAG_ID);
  144.                         String name = c.getString(TAG_NAME);
  145.                         String songs_count = c.getString(TAG_SONGS_COUNT);
  146.  
  147.                         // creating new HashMap
  148.                         HashMap<String, String> map = new HashMap<String, String>();
  149.  
  150.                         // adding each child node to HashMap key => value
  151.                         map.put(TAG_ID, id);
  152.                         map.put(TAG_NAME, name);
  153.                         map.put(TAG_SONGS_COUNT, songs_count);
  154.  
  155.                         // adding HashList to ArrayList
  156.                         albumsList.add(map);
  157.                     }
  158.                 }else{
  159.                     Log.d("Albums: ", "null");
  160.                 }
  161.  
  162.             } catch (JSONException e) {
  163.                 e.printStackTrace();
  164.             }
  165.  
  166.             return null;
  167.         }
  168.  
  169.         /**
  170.          * After completing background task Dismiss the progress dialog
  171.          * **/
  172.         protected void onPostExecute(String file_url) {
  173.             // dismiss the dialog after getting all albums
  174.             pDialog.dismiss();
  175.             // updating UI from Background Thread
  176.             runOnUiThread(new Runnable() {
  177.                 public void run() {
  178.                     /**
  179.                      * Updating parsed JSON data into ListView
  180.                      * */
  181.                     ListAdapter adapter = new SimpleAdapter(
  182.                             AlbumsActivity.this, albumsList,
  183.                             R.layout.list_item_albums, new String[] { TAG_ID,
  184.                                     TAG_NAME, TAG_SONGS_COUNT }, new int[] {
  185.                                     R.id.album_id, R.id.album_name, R.id.songs_count });
  186.                    
  187.                     // updating listview
  188.                     setListAdapter(adapter);
  189.                 }
  190.             });
  191.  
  192.         }
  193.  
  194.     }
  195. }
  196.  
  197. //activity_albums.xml
  198. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  199.     android:layout_width="fill_parent"
  200.     android:layout_height="fill_parent"
  201.     android:orientation="vertical"
  202.     android:background="#ffffff">
  203.  
  204.     <ListView
  205.         android:id="@+id/list"
  206.         android:layout_width="fill_parent"
  207.         android:layout_height="wrap_content"
  208.         android:divider="#b5b5b5"
  209.         android:dividerHeight="1dp"
  210.         android:cacheColorHint="#00000000" >
  211.     </ListView>
  212.  
  213. </LinearLayout>
  214.  
  215. //activity_tracks.xml
  216. <?xml version="1.0" encoding="utf-8"?>
  217. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  218.     android:layout_width="fill_parent"
  219.     android:layout_height="fill_parent"
  220.     android:orientation="vertical"
  221.     android:background="#ffffff">
  222.    
  223.     <ListView
  224.         android:id="@android:id/list"
  225.         ></ListView>
  226.    
  227.  
  228. </LinearLayout>
  229.  
  230.  
  231. //list_item_albums.xml
  232. <?xml version="1.0" encoding="utf-8"?>
  233. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  234.     android:id="@+id/RelativeLayout1"
  235.     android:layout_width="fill_parent"
  236.     android:layout_height="wrap_content"
  237.     android:orientation="vertical" >
  238.  
  239.     <TextView
  240.         android:id="@+id/album_id"
  241.         android:layout_width="fill_parent"
  242.         android:layout_height="wrap_content"
  243.         android:visibility="gone" />
  244.  
  245.     <TextView
  246.         android:id="@+id/album_name"
  247.         android:layout_width="fill_parent"
  248.         android:layout_height="wrap_content"
  249.         android:textSize="16dip"
  250.         android:textColor="#000000"
  251.         android:paddingTop="15dip"
  252.         android:paddingBottom="15dip"
  253.         android:paddingLeft="10dip"
  254.         android:textStyle="bold"/>
  255.  
  256.     <TextView
  257.         android:id="@+id/songs_count"
  258.         android:layout_width="wrap_content"
  259.         android:layout_height="wrap_content"
  260.         android:layout_alignParentRight="true"
  261.         android:textColor="#ffffff"
  262.         android:textStyle="bold"
  263.         android:background="#9ed321"
  264.         android:paddingRight="3dip"
  265.         android:paddingLeft="3dip" />
  266.  
  267. </RelativeLayout>
  268.  
  269.  
  270.  
  271. //log
  272.  
  273. 12-29 11:32:13.611: W/Trace(1507): Unexpected value from nativeGetEnabledTags: 0
  274. 12-29 11:32:13.649: W/Trace(1507): Unexpected value from nativeGetEnabledTags: 0
  275. 12-29 11:32:14.309: D/dalvikvm(1507): GC_FOR_ALLOC freed 62K, 7% free 2571K/2752K, paused 47ms, total 50ms
  276. 12-29 11:32:14.319: I/dalvikvm-heap(1507): Grow heap (frag case) to 3.229MB for 635812-byte allocation
  277. 12-29 11:32:14.449: D/dalvikvm(1507): GC_FOR_ALLOC freed 1K, 6% free 3190K/3376K, paused 122ms, total 122ms
  278. 12-29 11:32:14.589: D/dalvikvm(1507): GC_CONCURRENT freed <1K, 6% free 3202K/3376K, paused 5ms+73ms, total 146ms
  279. 12-29 11:32:14.609: D/AndroidRuntime(1507): Shutting down VM
  280. 12-29 11:32:14.609: W/dalvikvm(1507): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
  281. 12-29 11:32:14.629: E/AndroidRuntime(1507): FATAL EXCEPTION: main
  282. 12-29 11:32:14.629: E/AndroidRuntime(1507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonapp/com.example.jsonapp.AlbumsActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
  283. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
  284. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
  285. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
  286. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
  287. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.os.Handler.dispatchMessage(Handler.java:99)
  288. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.os.Looper.loop(Looper.java:137)
  289. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ActivityThread.main(ActivityThread.java:5039)
  290. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at java.lang.reflect.Method.invokeNative(Native Method)
  291. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at java.lang.reflect.Method.invoke(Method.java:511)
  292. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
  293. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  294. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at dalvik.system.NativeStart.main(Native Method)
  295. 12-29 11:32:14.629: E/AndroidRuntime(1507): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
  296. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ListActivity.onContentChanged(ListActivity.java:243)
  297. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:273)
  298. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.Activity.setContentView(Activity.java:1881)
  299. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at com.example.jsonapp.AlbumsActivity.onCreate(AlbumsActivity.java:58)
  300. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.Activity.performCreate(Activity.java:5104)
  301. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
  302. 12-29 11:32:14.629: E/AndroidRuntime(1507):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
  303. 12-29 11:32:14.629: E/AndroidRuntime(1507):     ... 11 more
  304. 12-29 11:32:28.329: I/Process(1507): Sending signal. PID: 1507 SIG: 9
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement