INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

(OP)
I designed app to make order for pizza food restaurant
I show userid,menu id ,address,longtiude,latitude then press on button make order
Error show after I press button and found in async task doin background
It give me fatal exception error
An error occurred while executing doInBackground()
and it show to me two lines have proplem
AddNewOrder.doInBackground(Summary.java:113)
AddNewOrder.doInBackground(Summary.java:77)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean org.json.JSONObject.getBoolean(java.lang.String)' on a null object reference
package com.pizza_final_project_app.pizza_final_project;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Summary extends Activity {
SharedPreferences preferences;
private ProgressDialog pDialog;
//JSONParser jsonParser = new JSONParser();
boolean errorFound;
TextView textaddress;
TextView textlongtiude;
TextView textlatitude;
TextView text2;
TextView textuser;
Button btnorder;
private static final String TAG_SUCCESS = "success";
private static final String TAG = Summary.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary);
text2=(TextView)findViewById(R.id.textView3);
textaddress=(TextView)findViewById(R.id.textaddress);
textuser=(TextView)findViewById(R.id.textView4);
textlongtiude=(TextView)findViewById(R.id.textlongtiude);
textlatitude=(TextView)findViewById(R.id.textlatitude);
Intent i = getIntent();
String id = i.getStringExtra("Data4");
String address = i.getStringExtra("Data8");
String longtiude = i.getStringExtra("Data9");
String latitude = i.getStringExtra("Data10");
text2.setText(id);
textaddress.setText(address);
textlongtiude.setText(longtiude);
textlatitude.setText(latitude);
preferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

String email=preferences.getString("email","");
textuser.setText(email);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
btnorder=(Button)findViewById(R.id.button2);
btnorder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
addOrder(textuser.getText().toString().trim(), text2.getText().toString().trim(),
textaddress.getText().toString().trim(), textlongtiude.getText().toString().trim(),
textlatitude.getText().toString().trim());

}
});


}
//line 77
class AddNewOrder extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Summary.this);
pDialog.setMessage("Making Order...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

protected String doInBackground(String... args) {
final JSONParser jsonParser = new JSONParser();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userID", args[0]));
params.add(new BasicNameValuePair("menuID", args[1]));
params.add(new BasicNameValuePair("address", args[2]));
params.add(new BasicNameValuePair("longitude", args[3]));
params.add(new BasicNameValuePair("latitude", args[4]));


JSONObject jObj = jsonParser.makeHttpRequest(AppConfig.URL_Order,
"POST", params);

try {
//Line 113
boolean error = jObj.getBoolean("error");
if (!error) {

errorFound=false;
} else {
errorFound=true;

}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
if (!errorFound){
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();


Intent intent = new Intent(
Summary.this,
FinalResult.class);
startActivity(intent);
finish();
}
else{
Toast.makeText(getApplicationContext(), "An Error occoured!", Toast.LENGTH_LONG).show();

}
}
}

}
*/
private void addOrder(final String userID, final String menuID, final String address,
final String longitude, final String latitude) {

new AddNewOrder().execute(userID, menuID, address, longitude, latitude);

}

}



Class AppConfig
package com.pizza_final_project_app.pizza_final_project;

public class AppConfig {

public static String URL_Order = "http://amit-learning.com/myPizza/Api_v2.php?functi...";

json parser
package com.pizza_final_project_app.pizza_final_project;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

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

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

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

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.d("data",url);
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
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();
Log.d("json","data is "+json);

} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}


RE: Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

Why do you include a whole lot of code for us to have to wade through that has nothing to do with the problem?
Just show the code where the problem occurs.

If you are using the Android SDK environment, have you set Breakpoints in your code and then single-stepped through to where the problem occurs?
If not, then do so.

And if so, have you examined the parameter/variable contents just before the problem?
If not, do so.
If so, what is the problem?

Quote:

Attempt to invoke virtual method ... on a null object reference
It sounds as though one of your parameter/variable contents is NULL when that is not allowed.
If so, use the Debug tools to find out which one and then find out why that is occurring.
* Is the JSON value you are getting NULL? if so, why?
* Can you pre-test and then change a NULL to a string "" ?

Good Luck,
JRB-Bldr



RE: Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

(OP)
This is my url i using
http://amit-learning.com/myPizza/Api_v2.php?functi...
this line is give error
boolean error = jObj.getBoolean("error");
it give me null pointer reference exception
in jObj(json object) variable
so that what i do now

RE: Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

I will have to study your code in greater detail before giving an answer.

BUT until then, have you plugged your URL into a browser to see what the response is?
I always do that to be certain that my URL is put together correctly.
If it is correct and the web service is working properly, the browser should return the JSON data on-screen

If one of those is not correct, then you will not get your JSON data for your app code to work with.

Good Luck,
JRB-Bldr

RE: Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

(OP)
This meaning browser URL must return data
if not return data
meaning browser URL have problem not related to source code i write
if i true answer for me

RE: Null Pointer Exception In Method Boolean.Org.Json.Jsonobject Do in background async task

If the web service is not returning values in reply to your URL request, then your JSON object will be empty and your code will likely show an ERROR unless you test for this issue condition.

By using your Browser you can manually test to find out if the web service is responding to the URL that you are sending to it.
* If it is responding correctly with data, the Browser will show the data.
YES -

Quote:

This meaning browser URL must return data
* If it is Not responding with data, then either your URL is bad or the web service is not working correctly.

Quote:

meaning browser URL have problem not related to source code i write
If that were the case then the code you wrote would need to be modified to handle the web service error.

Lets make sure by manually testing that the URL and the web service are both working correctly before we get into how the app code is encountering a problem.
Maybe the MAIN problem is 'outside' of the app code.

Good Luck,
JRB-Bldr


Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close