1

I am trying to parse a JSON object, but am running into a nullpointer error, and a Value Cannot of type java.lang.String cannot be converted to JSONObject error. My code is below. I'd appreciate any help.

06-30 14:48:18.151: E/JSON Parser(10231): Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONObject
06-30 14:48:18.156: E/AndroidRuntime(10231): FATAL EXCEPTION: main
06-30 14:48:18.156: E/AndroidRuntime(10231): Process: rafa.weatherapp, PID: 10231
06-30 14:48:18.156: E/AndroidRuntime(10231): java.lang.NullPointerException
06-30 14:48:18.156: E/AndroidRuntime(10231):    at rafa.weatherapp.MainActivity$AsyncTaskParseJson.onPostExecute(MainActivity.java:72)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at rafa.weatherapp.MainActivity$AsyncTaskParseJson.onPostExecute(MainActivity.java:1)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at android.os.AsyncTask.finish(AsyncTask.java:632)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at android.os.Handler.dispatchMessage(Handler.java:102)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at android.os.Looper.loop(Looper.java:146)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at android.app.ActivityThread.main(ActivityThread.java:5602)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at java.lang.reflect.Method.invokeNative(Native Method)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at java.lang.reflect.Method.invoke(Method.java:515)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
06-30 14:48:18.156: E/AndroidRuntime(10231):    at dalvik.system.NativeStart.main(Native Method)

and here is my MainActivity

    package rafa.weatherapp;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

    TextView textview = null;
    JSONObject currentTemperature = null;

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

        textview = (TextView) findViewById(R.id.textview);
        // we will using AsyncTask during parsing 
        new AsyncTaskParseJson().execute();
    }

    // you can make this class as another java file so it will be separated from your main activity.
    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here
       String yourJsonStringUrl = "https://api.forecast.io/forecast/5530508d3568e57848d53bf10cfade1f/37.8267,-122.42";

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JSONParser jParser = new JSONParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

                JSONObject weatherData = new JSONObject();


                currentTemperature = weatherData.getJSONObject("currently");
                currentTemperature.getString("temperature").toString();

                textview = (TextView) findViewById(R.id.textview);
                textview.setText((CharSequence) currentTemperature);
                Toast.makeText(MainActivity.this, "Text set", Toast.LENGTH_LONG);




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

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {
            currentTemperature.toString();
             textview.setText((CharSequence) (currentTemperature));
        }
    }
}
5
  • Just because you cast a JSONObject to a CharSequence, doesn't make it a CharSequence. Commented Jun 30, 2014 at 18:54
  • 2
    Does it really say Value Cannot of type java.lang.String cannot be converted to JSONObject? Commented Jun 30, 2014 at 18:55
  • @SotiriosDelimanolis It was the solution suggested by eclipse when I was getting an error before casting it. Commented Jun 30, 2014 at 18:58
  • Eclipse is short-sighted. It sees that your types are wrong and is trying to help you. Commented Jun 30, 2014 at 18:59
  • side note: you must be getting a JSON exception, otherwise you would be getting another exception with these two lines textview.setText((CharSequence) currentTemperature); Toast.makeText(MainActivity.this, "Text set", Toast.LENGTH_LONG); Can't update UI on background thread. Use one of the other methods. Commented Jun 30, 2014 at 19:01

4 Answers 4

2

I see few problems:

  • First of all you are getting a null pointer because your return null from doInBackground()
  • You are trying to display a toast in doInBackground, thats not allowed in the background thread
  • You should initialize your textView in onCreate method.
  • You are trying to get data from weatherData which you never initialized with json.

public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
    String yourJsonStringUrl = "https://api.forecast.io/forecast/5530508d3568e57848d53bf10cfade1f/37.8267,-122.42";
    @Override
    protected String doInBackground(String... url) {
      String temperature = "";
        try {

            // instantiate our json parser
            JSONParser jParser = new JSONParser();
            // get json string from url
            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
            JSONObject currentData = json.getJSONObject("currently");
            temperature = currentTemperature.getString("temperature");    

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

        return temperature;
    }

    @Override
    protected void onPostExecute(String currentTemp) {
         textview.setText((CharSequence) (currentTemp));
    }
}

As I read the error again:

Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONObject

It seems like jParser.getJSONFromUrl() does not return a JSONObject but a string instead, in this case you should pass the string to the JSONObject constructor:

 String jsonString = jParser.getJSONFromUrl(yourJsonStringUrl);
 JSONObject json = new JSONObject(jsonString);

But you wrote this function , only you know what it returns.

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

7 Comments

With your suggestion I get the same parsing error, but no nullpointer error. Any clue why that might be?
have logged the JSON, you should show me which line is throwing the the parsing error. I would make sure I get the actual json and can print it to the console before attempting to display it on a textview
@ralphie9224 I expanded on my answer
In my JSONParser class I do return a JSONObject
Again...which line is giving u error, are u able to log the json
|
1

Storage the currentTemperature JSONObject.getString("temperature").toString into a proper string type, then send that argument on the textview you want to show.

When you call

currentTemperature.getString("temperature").toString();

you are not converting the currentTemperature into a String, you are just calling the method and not assigning it anywhere

Also, you should create a model for that JSON Object, for example

public class CurrentTime{
String temperature;
String humidity;
}

And so on, then storage all the values of the JSON into an object of this class and you are good to go to do anything with it, create the setters & getters and it is cleaner code

2 Comments

I turn it into // instantiate our json parser JSONParser jParser = new JSONParser // get json string from JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl); JSONObject currentTemperature = json.getJSONObject("currently"); temperature = currentTemperature.getString("temperature"); but it still gives me a null pointer error
Did you changed the arguments received on the onPostExecute of your asynctask? @Override protected void onPostExecute(String currentTemp) { textview.setText((CharSequence) (currentTemp)); }
1

Actually you are getting the json data in variable "json" using following code :

 JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);

but after this you have not used this variable anywhere, instead of it you are using "wheatherData" variable which is having no data. please check it once.

Comments

0

You need to save the string in some variable, replace this line:

currentTemperature.getString("temperature").toString();

With:

String myRealTemperature = currentTemperature.getString("temperature");

And use myRealTemperature to set the Textview.

1 Comment

I have it set as that now, but i'm still getting the error // instantiate our json parser JSONParser jParser = new JSONParser(); // get json string from url JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl); JSONObject currentTemperature = json.getJSONObject("currently"); temperature = currentTemperature.getString("temperature");

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.