JSON object showing null pointer exception - java

I want to post data to the url and getting Null pointer exception
My JSON URL contains
{
"Details":
[
{
"Status":"NO UPDATES"
}
]
}
I'm getting the error the line:
String status = object.getString("Status").trim(); //error Line
Full code:
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
btnPost.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("null")
#Override
public void onClick(View arg0)
{
try
{
String postReceiverUrl = "http://";
Log.v(TAG, "postURL: " + postReceiverUrl);
// HttpClient
#SuppressWarnings("resource")
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
jsonobject.put("IDNo", IDNo.getText().toString());
jsonobject.put("Position", Position.getText().toString());
jsonobject.put("Data", Data.getText().toString());
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
Log.v("jsonResult",jsonResult);
JSONObject object = new JSONObject(jsonResult);
String status = object.getString("Status").trim();
Toast.makeText(getBaseContext(), "Please wait...",100).show();
if(status.toString().equals("SUCCESS"))
{
Intent i = new Intent(LoginPage.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
if(status.toString().equals("FAILED"))
{
Toast.makeText(getBaseContext(), "Wrong Credentials",100).show();
}
else
{
Toast.makeText(getBaseContext(), "Details Inserted",100).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});

Do proper parsing of the JSON as , you see yours response:-
{ "Details":[{"Status":"NO UPDATES"}]}
So Firstly try to make the object of the JSONObject than after the JSONArray , look at below example:-
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray detailsArray = jsonObject.getJSONArray("Details");
String status = dataArray.getJSONObject(0).getString("status");
Toast.makeText(getBaseContext(), "Please wait...",100+status).show();

your code should be like this
JSONObject object = new JSONObject(jsonResult);
JSONOArray details = object.getJSONArray("Details");
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String status = c.getString("Status");
}
Toast.makeText(getBaseContext(), "Please wait...",100).show();

Modift String status = object.getString("Status").trim(); to
String status = object.get("Details").getAsJsonArray()[0].getString("Status").trim();

You are using getString("Status") which may return null if key is not available in JSON. I'd suggest you to use optString("Status") it'll return blank String if key is not available.
JSONObject jsonObject = new JSONObject(stringJSON);
JSONArray jsonArray = jsonObject.optJSONArray("Details");
if(jsonArray != null){
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jObject = jsonArray.optJSONObject(i);
if(jObject != null){
String strStatus = jObject.optString("Status");
}
}
}

Try this code
JSONObject object = new JSONObject(jsonResult);
JSONArray array=object.getJsonarray("Details");
for(int i=0;i<array.length();i++)
{
JSONObject innerObject=array.getJsonObject(i);
String s= innerObject.getString("Status");
}

If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then simply check as following:
if(json_object == null) {
System.out.println("json_object is found as null");
}
else {
System.out.println("json_object is found as not null");
}

Related

How to get the value of a child node of a json array

please i am having some issues parsing a list of data form the this link(https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23) i am able to get the data from the json array(articles) but how can i get the data from the josn array(sources)
private void getWebApiData() {
String WebDataUrl = "https://gnews.io/api/v3/top-news?&token=dd21eb88599ccb3411eaad9b314cde23";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONObject("articles");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is code I am using the get the data of the articles.
To get the sources I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response2 = response.getJSONArray("articles");
JSONObject response3 = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I think I am not getting the code correctly
Here is the second option I have tried
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONObject response = response2.getJSONObject("sources");
NewsClass newsClass;
for (int i = 0; i < newsClass.length(); i++) {
JSONObject post = newsClass.optJSONObject(i);
String name = post.optString("name");
newsClass = new newsClass();
newsClass.setNews_Name(name);
artistClassList.add(newsClass);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But this only gives me empty text Fields the spaces for the data is populated but it is blank
Please any help will be greatly appreciated
I don't know how your code works. You have tried to get JSONObject as articles which is actually JSONArray. Besides this I don't find any key in your json like sources instead I have found source. To parse source try below way:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("source");
String name = sourceObject.optString("name");
String url = sourceObject.optString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
As Md. Asaduzzaman stated it is actually an JSON array ("articles" to be exact).
I have tested it on my phone and it works no prob. You will have to try and figure out how u want the JSONArray to be parsed thou.
private class AsyncTaskExample extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
stringURL = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) stringURL.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
//render string stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != is) {
is.close();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String js) {
super.onPostExecute(js);
try {
JSONObject jay = new JSONObject (js);
JSONObject source = jay.getJSONObject("articles");
String s = source.getString("title");
System.out.println(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here you will find all you need for JSON.
Best of luck to you :)
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray articles = jsonObject.getJSONArray("articles");
for(int i=0; i<articles.length(); i++){
JSONObject obj1 = (JSONObject) articles.get(i);
JSONObject source = obj1.getJSONObject("source");
Log.i(TAG, "onResponse: " + source.toString()); }
Hope that help you !

Android JSON parsing: parse a particular element

I have a mentioned bellow could you let me know how to parse only Tripname in this json
I want like
delta
Baby
bluebay
whaynle
from the json
MyJson
[{"0":"$deta","Tripname":"delta"},{"0":"Baby","Tripname":"Baby"},{"0":"bluebay","Tripname":"bluebay"},{"0":"whaynle","Tripname":"whaynle"}]
System.out.println("--RESULT--" + result);
JSONObject jObject = null;
try {
jObject = new JSONObject(result);
//JSONArray a = jObject.getJSONArray("Tripname");
String status = jObject.getString("Tripname");
//Log.v("result1", jObject.toString());
Log.v("Response", status);
}
catch (JSONException e)
{
e.printStackTrace();
}
try this:
try{
JSONArray jsonArray = new JSONArray(jsonString);
for(int i=0;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String data1 = object.getString("0");
String trip_name = object.getString("Tripname");
Log.i("TripName",trip_name);
//rest of the strings..
}
catch (JSONException e){
e.printStackTrace();
}
Do like this
JSONArray jArray= null;
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject= jArray.getJSONObject(i);
String status = jObject.getString("Tripname");
//Log.v("result1", jObject.toString());
Log.v("Response", status);
}
}
catch (JSONException e)
{
e.printStackTrace();
}

Error converting JSONArray to JSONObject

I am trying to extract and process some JSON data, but it is erroring when I try. This is my code:
protected void onPostExecute(String s) {
String err=null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
LASTNAME = user_data.getString("lastname");
PASSWORD = user_data.getString("password");
EMAIL = user_data.getString("email");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: "+e.getMessage();
}
Intent i = new Intent(ctx, MainActivity.class);
i.putExtra("lastname", LASTNAME);
i.putExtra("email", EMAIL);
i.putExtra("password", PASSWORD);
i.putExtra("err", err);
startActivity(i);
}
But this is the error:
org.json.JSONException: Value [] at user_data of type org.json.JSONArray cannot be converted to JSONObject
I think you have problem with casting Array to Object.
[..] means it is JSONArray.
{..} means it is JSONObject.
try {
JSONArray jObj = new JSONArray(json);
//This is how you get value from 1 element in JSONArray
String firstObjectValue = jObj.getString(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you looking for value need you to iterate all JSONArray
by doing some simple loop.
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
JSONArray jsonARRAY = jsonObject.getJSONArray("nameOfJSONArray");
for (int i = 0; i < jsonARRAY.length(); i++) {
JSONObject jsonOBJECT = (JSONObject) jsonARRAY.get(i);
String yourValue = jsonOBJECT.getString("valueKey");
}
} catch (JSONException e) {
e.printStackTrace();
}
It seems like your "user_data" is coming as json array instead of json object that you are trying to access.
you can use root.optJSONObject("user_data") to determine & return json object if your user_data is json object or will return null.

Unterminated object at jsonobject line 19?

Am new to android development am making simple login application using volley and getting json response from server like this:
json response:-
{"loginResult":"{\"UserLoginID\":864,\"UserID\":864,\"EmployeeCode\":\"PI4264\",\"Password\":\"XXXX\",\"IsPasswordChanged\":false,\"ModuleName\":\"XXX\",\"ModuleID\":1,\"EmployeeName\":\"XXXX \"}"}
When i try to parse this jsonobect am getting :
Unterminated object at 19 jsonexception so far what i have tried is to parse is
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
int yogs=yog.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
don't know where am making mistake can anybody teach me am i doing it in right way!!!
You should change your code to this:
String resp = response.toString().replaceAll("\\\\", "");
try {
JSONObject yog = new JSONObject(resp);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), resp, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
I executed the code and didn't get the error:
JSONObject yog = new JSONObject("{\"loginResult\":\"{\\\"UserLoginID\\\":864,\\\"UserID\\\":864,\\\"EmployeeCode\\\":\\\"PI4264\\\"," +
"\\\"Password\\\":\\\"XXXX\\\",\\\"IsPasswordChanged\\\":false,\\\"ModuleName\\\":\\\"XXX\\\",\\\"ModuleID\\\":1,\\\"EmployeeName\\\":\\\"XXXX " +
"\\\"}\"}");
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
Toast.makeText(getApplicationContext(), String.valueOf(yogs), Toast.LENGTH_SHORT).show();
You are making an un-necessary string sanitization.
Just remove replaceAll command. and use following code :
try {
JSONObject yog = new JSONObject(response);
JSONObject loginObject = new JSONObject(yog.getString("loginResult"));
int yogs=loginObject.getInt("UserID");
System.out.println(yogs);
}
catch (JSONException e) {
e.printStackTrace();
}
This should work fine after that.

how to code json array without array name?

I'm new to JSON android java eclipse. I am doing a listview with images and parsing json array. I followed this tutorial: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ . In that tutorial, their JSON array contains the array name.However, mine doesn't contain the array name. So my question is how to code JSON Array without the array name?
Below is my JSON code.
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
},
{
"event_id": "EV00000002",
"event_title": "Movie2",
}
]
Below is my JSON coding for parsing the JSON.
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Events event = new Events();
event.setevent_title(object.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
What am i suppose to do?
This problem is solved. Thus, i will be posting the correct code.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Events event = new Events();
event.setevent_title(obj.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
Here is a little example:
JSONArray array = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("key", "value");
array.put(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("key2", "value2");
array.put(obj2);
That would look like:
[
{
"key": "value"
},
{
"key2": "value2"
}
]
If you want to get information about your JSONObjects in your JSONArray just iterate over them:
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
object.get("event_id");
object.get("event_title");
}
You can use GSON librery, it's very easy to use. Just create a class (model)
public class Event{
private String event_id;
private String event_title;
...
}
and in your main activity
Event ev = new Event ("EV00000001", "Movie 1")
Gson gson = new Gson();
gSon = gson.toJson(ev);
Log.i("gson", gSon);
and you will get JSON
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
}
]
What you have is an array of JSON Objects.
What the tutorial has is a JSON Object that has a property, which has an array of JSON objects.
When you look at these, here is a simple way to differentiate the two:
[] -> Array
{} -> Object
So in your code, instead of doing
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
You might want to do:
JSONArray jarray = new JSONArray(data);

Categories

Resources