1

My app is crashing and the log is showing this error:

Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference on the line where I do:

ab = jobj.getString("title");

I'm a noob to Android development. Please help!

public class MainActivity extends ActionBarActivity {

JSONObject jobj = null;
ClientServerInterface clientServerInterface = new ClientServerInterface();
TextView textView;
String ab = "";

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

    textView = (TextView) findViewById(R.id.textView);
    new RetrieveData().execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings)
    {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

class RetrieveData extends AsyncTask<String,String,String>
{
    protected String doInBackground(String... arg0) {
        jobj = clientServerInterface.makeHttpRequest("http://**.***.***.**/printresult.php");
        try {
            ab = jobj.getString("title");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return ab;
    }

    protected void onPostExecute(String ab){
        textView.setText(ab);
    }
}
}

Here's the other file:

public class ClientServerInterface {

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


public ClientServerInterface(){
}
public JSONObject makeHttpRequest(String url){
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try{
        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity httpentity = httpresponse.getEntity();
        is = httpentity.getContent();
    }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;
        try{
            while((line = reader.readLine())!= null){
                sb.append(line+"\n");
            }
            is.close();
            json = sb.toString();
            try{
                jobj = new JSONObject(json);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }catch (UnsupportedEncodingException e){
        e.printStackTrace();
    }
    return jobj;
}
}

Maybe it is in my php file?

<?php
require_once('connection.php');

$qry = "SELECT * FROM eventdetails";
$result = mysql_query($qry);
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[] = $r;
}
echo json_encode($rows);
mysql_close();
?>

I'm really stumped. Please help!

4 Answers 4

3

I believe what's causing the difficulty is that your URL points to a malformed JSON string. What I get at the the URL provided is:

[{"title":"School Start","pictureURL": ...   }]

the Square bracket at the front and at the end should not appear in the string you pass to the JSONObject constructor here.

 json = sb.toString();
        try{
            jobj = new JSONObject(json);
        }catch (JSONException e){
            e.printStackTrace();
        }

You need to trim the first and last character of json since I believe the constructor is throwing an exception which you ar catching and ignoring.

Sign up to request clarification or add additional context in comments.

2 Comments

Here is what I added: json.substring(1); json.substring(0,json.length()); But I'm still getting that error. But I found something else in the log now. "org.json.JSONException: Value [JSON DATA FROM WEBPAGE] of type org.json.JSONArray cannot be converted to JSONObject"
I GOT IT THANKS TO YOU!
1

try like this

class RetrieveData extends AsyncTask<String,String,JSONObject>{
    protected JSONObject doInBackground(String... arg0) {
        JSONObject jobj = clientServerInterface.makeHttpRequest("http://54.164.136.46/printresult.php");
        return jobj;
    }
    protected void onPostExecute(JSONObject jobj){
        try {
            String ab = jobj.getString("title");
            textView.setText(ab);
        } catch (JSONException e) {
        e.printStackTrace();
        }
    }
}

3 Comments

Android Studio is giving me an error now. It's saying: Error:(63, 30) error: doInBackground(String...) in MainActivity.RetrieveData cannot override doInBackground(Params...) in AsyncTask return type JSONObject is not compatible with String where Params,Result are type-variables: Params extends Object declared in class AsyncTask Result extends Object declared in class AsyncTask
Also this one: Error:(62, 5) error: MainActivity.RetrieveData is not abstract and does not override abstract method doInBackground(String...) in AsyncTask
Oops I mistyped what you wrote. But now it's still giving me that same original error with the null pointer exception
0

this usually is the case with higher version of jdk version set as target . this happen to me when we were using jdk 1.7 as target platform to build with . when changed to jdk 1.5 it resolved the issue . Not sure but it worked.Also to mention that was not specific to android application but was a deployment package . not sure its related but the package was same java.lang.string.

3 Comments

Still getting the same null pointer... I changed it in File->Other Settings->Default Settings->Compiler->Java Compiler and tried all the versions
are you using eclipse . then which version is it juno or indigo. check that too . worked on it a very long time ago . try to change platform too if possible. also if possible after changing those try to clean workspace and build again
I'm on Android Studio. I'll try it on Eclipse
0

The error, as user1023110 pointed out, happens because the constructor is throwing an exception. In this case, I was giving the constructor a JSONArray and it giving the error that it could not be converted to JSONObject. First, I added this to the top of my ClientServerInterface class:

static JSONArray jarr = null;

Then, I added these two lines:

jarr = new JSONArray(json);
jobj = jarr.getJSONObject(0);

where I previously had this:

jobj = new JSONObject(json);

The method now returns the first JSONObject of the JSONArray.

Thanks to all your help!

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.