Skip to content Skip to sidebar Skip to footer

How To Retrieve Data From Json Array And Display In Textview?

I've been using the coding from an example from this link: The code is as shown below: public class food extends ListActivity { @Override public void onCreate(Bundle saved

Solution 1:

You are already getting strings in below code, Why don't you use that.

for(int i=0;i<jArray.length();i++){
            json_data = jArray.getJSONObject(i);
            fd_id=json_data.getInt("FOOD_ID");
            fd_name=json_data.getString("FOOD_NAME");
          }

//fdname and fd_id you are getting it right,

If your code is not working then add what problem you are facing.

according to your response/result from the server below code is working for me and giving output in string ,

try {    
          String response ="[{\"FOOD_ID\":\"1\",\"FOOD_NAME\":\"Rice\"},{\"FOOD_ID\":\"2\",\"FOOD_NAME\":\"Daal\"}] ";
           JSONArray array;

            array = new JSONArray(response);

           for (int i =0; i < array.length(); i++) {
             JSONObject obj = array.getJSONObject(0);
             String id_fd = obj.getString("FOOD_ID");
             String name_fd = obj.getString("FOOD_NAME");
             Log.d("JSONArray", id_fd+"   "+name_fd);
        }} catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

please use it according to your need.

Solution 2:

The root cause of the error a NullPointerException. This means that you are trying to use an object that has the value null. Usually this is because the object has not yet been initialised.

In your case the nullpointer is caused by something at line 29 of your Food class, probably one of these two lines

TextViewfdi= (TextView)findViewById(R.id.textView1);
   TextViewfdn= (TextView)findViewById(R.id.textView2);

Are you sure that both the R.id.textView1 and R.id.textView1 exist? They should be specified somewhere in a layout xml file, something like this:

 <TextView
    android:id="@+id/textView1"
    ....

Post a Comment for "How To Retrieve Data From Json Array And Display In Textview?"