0

I am trying to parse a json entry from the url. Below is the code segment.

TextView txtViewParsedValue;
private JSONObject jsonObject;
private static String url = "https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1"; 
String strParsedValue = null;  
TextView txtViewParsedValue;
private JSONObject jsonObject;
private static String url = "https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1"; 
String strParsedValue = null;           

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

    txtViewParsedValue = (TextView) findViewById(R.id.textview1);

    try {
        parseJSON();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void parseJSON() throws JSONException
{       
    JSONParser jParser = new JSONParser();
    jsonObject = jParser.getJSONFromUrl(url);

    JSONObject object = jsonObject.getJSONObject("student");

    JSONArray subArray = object.getJS ONArray("student");

    for(int i=0; i<subArray.length(); i++)
    {
        strParsedValue+="\n"+subArray.getJSONObject(i).getString("id").toString();
    }

    txtViewParsedValue.setText(strParsedValue);
}

I want to extract all id's of student and print them in textview. Its giving null pointer exception. Searched several posts relatng to this and tried them, but didn work, any guidance would be of great help!

2 Answers 2

3

student is JsonArray instead of JsonObject but you are trying to get it as JsonObject. change your parsing code as :

JSONArray subArray =jsonObject.getJSONArray("student");//<<< get student JSONArray
for(int i=0; i<subArray.length(); i++)
  {
   strParsedValue+=
        "\n"+subArray.getJSONObject(i).getString("id").toString();
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, it displays in the textview sometimes and remains blank sometimes on consecutive runs, my internet connections is good, any idea for this behavior??
@bharath : use AsyncTask for getting data from Server which avoid freezing of UI when getting data from server
Thanks for the reply, any pointers for sample Async task to access the json data from server??
0

Dont use JSONObject object = jsonObject.getJSONObject("student"); because according to your JSON student is an array.

Change it to

JSONArray subArray = jsonObject.getJSONArray("student");

Comments

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.