2

I'm looking for a good tutorial to parse JSON into Listview in Android.

The problem is my JSON file is like this

[{"location_id":"823","company_id":"41","name":"Milj\u00f8station","address":"Aldersro \/ Aldersro 8","place":"","postal":"5700","city":"Svendborg","monday":"","tuesday":"","wednesday":"","thursday":"","friday":"","saturday":"","sunday":"","type":"2","lat":"55.061426149085","lng":"10.5927246809006","nocar":"0","distance":"0.00023254303859579"}]

Most tutorials starting with a Json array, and later the data. I know there is a lot of examples but i couldn't find some it that match my problem.

I added code, but still it's not working, here is my 3 classes.

SingleMenuItemActivity

public class SingleMenuItemActivity  extends Activity {

// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String name = in.getStringExtra(TAG_NAME);
    String cost = in.getStringExtra(TAG_EMAIL);
    String description = in.getStringExtra(TAG_PHONE_MOBILE);

    // Displaying all values on the screen
    TextView lblName = (TextView) findViewById(R.id.name_label);
    TextView lblCost = (TextView) findViewById(R.id.email_label);
    TextView lblDesc = (TextView) findViewById(R.id.mobile_label);

    lblName.setText(name);
    lblCost.setText(cost);
    lblDesc.setText(description);
} }

JSONParser

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
} }

AndroidJSONParserActvity

public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "http://webservice.xxx.com/webservice/getLocationList.php?lat=55.061424255371094&lng=10.592724800109863";

// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";



// contacts JSONArray
JSONArray contacts = null;

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

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

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String location_id = c.getString(TAG_Location);
            String company_id = c.getString(TAG_Company);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADDRESS);
            String place = c.getString(TAG_PLACE);  
            String postal = c.getString(TAG_POSTAL);
            String city = c.getString(TAG_CITY);
            String monday = c.getString(TAG_MONDAY);
            String tuesday = c.getString(TAG_TUESDAY);
            String wednesday = c.getString(TAG_WEDNESDAY);  
            String thursday = c.getString(TAG_THURSDAY);
            String friday = c.getString(TAG_FRIDAY);
            String saturday = c.getString(TAG_SATURDAY);
            String sunday = c.getString(TAG_SUNDAY);
            String type = c.getString(TAG_TYPE);
            String lat = c.getString(TAG_LAT);
            String lng = c.getString(TAG_LNG);
            String nocar = c.getString(TAG_NOCAR);


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

            // adding each child node to HashMap key => value
            map.put(TAG_Location, location_id);
            map.put(TAG_Company, company_id);
            map.put(TAG_NAME, name);
            map.put(TAG_ADDRESS, address);
            map.put(TAG_PLACE, place);
            map.put(TAG_POSTAL, postal);
            map.put(TAG_CITY, city);
            map.put(TAG_MONDAY, monday);
            map.put(TAG_TUESDAY, tuesday);
            map.put(TAG_WEDNESDAY, wednesday);
            map.put(TAG_THURSDAY, thursday);
            map.put(TAG_FRIDAY, friday);
            map.put(TAG_SATURDAY, saturday);
            map.put(TAG_SUNDAY, sunday);
            map.put(TAG_TYPE, type);
            map.put(TAG_LAT, lat);
            map.put(TAG_LNG, lng);
            map.put(TAG_NOCAR, nocar);

                // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_NAME, TAG_LAT, TAG_Company }, new int[] {
                    R.id.name, R.id.email, R.id.mobile });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_Location, cost);
            in.putExtra(TAG_Company, description);
            startActivity(in);

        }
    });
} }

Error in Log Cat

     02-06 10:06:19.025: D/AbsListView(9115): Get MotionRecognitionManager 02-06 10:06:19.705: D/dalvikvm(9115): GC_CONCURRENT freed 206K, 6% free 12315K/12999K, paused 13ms+14ms, total 40ms 02-06 10:06:19.725: E/JSON Parser(9115): Error parsing data org.json.JSONException: Value [{"nocar":"0","company_id":"41","postal":"5700","thursday":"","monday":"","lng":"10.5927246809006","type":"2","city":"Svendborg","location_id":"823","distance":"0.00023254303859579","wednesday":"","address":"Aldersro \/ Aldersro 8","sunday":"","name":"Miljøstation","saturday":"","friday":"","tuesday":"","place":"","lat":"55.061426149085"},
02-06 10:06:19.730: D/AndroidRuntime(9115): Shutting down VM
02-06 10:06:19.730: W/dalvikvm(9115): threadid=1: thread exiting with uncaught exception (group=0x4100f2a0)
02-06 10:06:19.740: E/AndroidRuntime(9115): FATAL EXCEPTION: main
02-06 10:06:19.740: E/AndroidRuntime(9115): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.jsonparsing/com.androidhive.jsonparsing.AndroidJSONParsingActivity}: java.lang.NullPointerException
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.os.Looper.loop(Looper.java:137)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.main(ActivityThread.java:4898)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at java.lang.reflect.Method.invokeNative(Native Method)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at java.lang.reflect.Method.invoke(Method.java:511)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at dalvik.system.NativeStart.main(Native Method)
02-06 10:06:19.740: E/AndroidRuntime(9115): Caused by: java.lang.NullPointerException
02-06 10:06:19.740: E/AndroidRuntime(9115):     at com.androidhive.jsonparsing.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:69)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.Activity.performCreate(Activity.java:5206)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
02-06 10:06:19.740: E/AndroidRuntime(9115):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
02-06 10:06:19.740: E/AndroidRuntime(9115):     ... 11 more
3
  • 1
    Put the whole stack trace and only the code relevant to your question. We also have our work to do. Commented Feb 6, 2013 at 9:11
  • Man, do you think your English is not good? If so, try to use correct grammar, use upper I for I, not the lower i. Show us some efforts of yours. Commented Feb 6, 2013 at 9:31
  • You are making Web call on Main UI Thread. That's also a reason of Exception. To resolve it, you should implement Threading mechanism, best way of threading is to implement Web call by using AsyncTask. Commented Feb 6, 2013 at 9:38

3 Answers 3

3

because your webservice returning an JSONArray instead of JSONObject but you are trying to convert it to JSONObject . change your getJSONFromUrl method return type to JSONArray instead of JSONObject as :

public JSONArray getJSONFromUrl(String url) {
 JSONArray jsonarr=null;
    // Making HTTP request

    // try parse the string to a JSONArray
    try {
        jsonarr = new JSONArray(json);
    } catch (JSONException e) {

    }

    // return JSON String
    return jsonarr;  //<<<< return JSONArray instead of JSONObject
}

and call getJSONFromUrl as from onCreate of Activity :

 JSONArray json = jParser.getJSONFromUrl(url);

try {

    // looping through All Contacts
    for(int i = 0; i < json.length(); i++){
        JSONObject c = json.getJSONObject(i);

        // put your parsing code here
    }
} catch (JSONException e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

3 Comments

just tested it and it failed again :(
@LeythHisham : post your latest code . i think you are using contacts jsonArray instead json to get value from Array
well you are 100% right, the code working now. thank you very much for help. I see what u ment now with jsonArray and jsonObject.
1

I used the same tutorial once and i solved problem by replacing code in JSONParser class in your try-catch block. This is class is anyway useless, you can type this in onCreate() or write method in your AndroidJSONParserActivity class:

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i(".......",_response);
JSONObject json = new JSONObject(_response);
JSONArray jarray = json.getJSONArray("array_name");
for(int i=0;i<jarray.length();i++)
{
    JSONObject jb = (JSONObject) jarray.get(i);
    String name = jb.getString("name");
}

Anyway, you should do parsing in seperate thread instead of UI, with AsyncTask

Comments

0
try{
        // String t;
        Boolean found=false;

            JSONArray jArray = new JSONArray(result);
         int jArrayLength = jArray.length(); 
       ArrayList<String> listContents = new ArrayList<String>(jArrayLength);

            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
               // t[i]=json_data.getString("hotelname");


            listContents.add(json_data.getString("hotelname"));







            }






            arr = new String[listContents.size()];
            for(int i=0;i<listContents.size();i++)
                arr[i]= listContents.get(i);
             setListAdapter(new ArrayAdapter<String>(this,
                     android.R.layout.simple_list_item_1,arr));




    }
    catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }




}

public void onListItemClick( ListView parent, View v, int position, long id) { Intent myIntent = new Intent(getBaseContext(), Hotelinfo.class); myIntent.putExtra("hotelname",arr[position]);

        startActivity(myIntent);
        }

}

6 Comments

What do you suggest in your answer? I mean What's the mistake user has made in code.
I think he is running app on latest version of android and he is doing Http server request on main thread thats why he is facing problem.He should use Async task for this
that's the thing you should include in your answer to get upvote :) Otherwise simply code is not good as perfect answer.
Actually i don't need upvote i am just trying to help.And secondly He is doing this thing "populating list" in a complicated way i have given him the simple code to do the same thing
But why don't you describe it inside answer, other than placing comments here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.