0

I've looked at the other posts on here, and I haven't found the answer to my problem. I'm practicing JSON in Android, for which I'm using the forecast.io API. Here's what the JSON looks like: https://api.forecast.io/forecast/7d5566f0ebf0fe263426f12b52d5c51c/37.8267,-122.423.

I got the code to help me get started from another post on here:

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    double LONGITUDE = location.getLongitude();
    double LATITUDE = location.getLatitude();

    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("https://api.forecast.io/forecast/7d5566f0ebf0fe263426f12b52d5c51c/" + LATITUDE + "," + LONGITUDE);
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        result = sb.toString();


    } catch (Exception e) { 
        // Oops
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }




    try {
        JSONObject j = new JSONObject(result);
        String timezone = j.getString("timezone");
        text.setText(timezone + "");

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

This line gives me an error:

JSONObject j = new JSONObject(result);

It gives a null pointer exception. The code only runs if I wrap the initializatin with if(result!=null) So I guess there's no JSON being retrieved. What could I be doing wrong?

EDIT: Here is the stacktrace

 01-21 15:28:42.857: W/System.err(31328):android.os.NetworkOnMainThreadException
01-21 15:28:42.857: W/System.err(31328):at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
01-21 15:28:42.857: W/System.err(31328):at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-21 15:28:42.857: W/System.err(31328):at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-21 15:28:42.857: W/System.err(31328):at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-21 15:28:42.857: W/System.err(31328):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-21 15:28:42.857: W/System.err(31328):at com.example.weatherapp.MainActivity.onCreate(MainActivity.java:48)
01-21 15:28:42.857: W/System.err(31328):at    android.app.Activity.performCreate(Activity.java:5231)
  • 2
    I guess you get an exception when you fetch the content via HTTP. Therefore `result` is null. The exception is silently ignored, never do that. It hides the real cause of the problem. – Henry Jan 21 '15 at 21:21
  • I was following this answer: http://stackoverflow.com/a/9606629/3677912. Is there a better way I should be fetching the JSON? – Rohit Sharma Jan 21 '15 at 21:23
  • Yes, instead of the `// Oops` do something useful, at least write the exception to System.out. – Henry Jan 21 '15 at 21:25
  • Add `e.printStackTrace();` instead of the `// Oops` And post the stack trace here so we can help – Jorge Campos Jan 21 '15 at 21:27
  • Updated. Thank you. I need to be doing everything on a background thread, I'm guessing? Doesn't seem like anyone had trouble with the answer that I got the code from. – Rohit Sharma Jan 21 '15 at 21:35
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Henry Jan 21 '15 at 21:39
  • We have liftoff. I appreciate everyone. Should I delete this since it pretty much is a duplicate? – Rohit Sharma Jan 21 '15 at 23:18

2 Answers2

2

It's because, as the exception states, you're trying to access the internet on the main thread. Android doesn't allow this since it can lag the UI. Therefore, you'll need to connect to the internet on a separate thread that isn't the UI thread. Refer to http://developer.android.com/reference/android/os/AsyncTask.html (You only really need doInBackground for internet access).

Anubhaw Arya
  • 145
  • 6
2

When you're done moving your code into a (for example) AsyncTask, remove the "s" from your URL. It should be http and not https, otherwise you will get a 404 and no data.

degill
  • 1,285
  • 2
  • 13
  • 19