简体   繁体   中英

Null pointer exception json parsing url android

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!

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();
 }

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

Change it to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM