-3

I am still a beginner in android web service, now I have a problem for data parsing json from url.

here my code: JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        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, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
 }
}    

here my MainActivity.java

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import learn2crack.jsonparsing.library.JSONParser;
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "https://api.themoviedb.org/3/genre/list?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
//JSON Node Names
private static final String TAG_GENRES = "genres";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";

JSONArray genres = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Creating new JSON Parser
    JSONParser jParser = new JSONParser();
    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        // Getting JSON Array
        genres = json.getJSONArray(TAG_GENRES);
        JSONObject c = genres.getJSONObject(0);
        // Storing  JSON item in a Variable
        String id = c.getString(TAG_ID);
        String name = c.getString(TAG_NAME);

        //Importing TextView
        final TextView uid = (TextView)findViewById(R.id.uid);
        final TextView name1 = (TextView)findViewById(R.id.name);

        //Set JSON Data in TextView
        uid.setText(id);
        name1.setText(name);

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

but I get an error in the logcat, as below

01-22 10:36:09.701: E/JSON Parser(379): Error parsing data org.json.JSONException: Value <h1>Not of type java.lang.String cannot be converted to JSONObject
01-22 10:36:09.721: E/AndroidRuntime(379): FATAL EXCEPTION: main
01-22 10:36:09.721: E/AndroidRuntime(379): java.lang.RuntimeException: Unable to start activity ComponentInfo{learn2crack.jsonparsing/learn2crack.jsonparsing.MainActivity}: java.lang.NullPointerException
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.os.Looper.loop(Looper.java:130)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-22 10:36:09.721: E/AndroidRuntime(379):  at java.lang.reflect.Method.invokeNative(Native Method)
01-22 10:36:09.721: E/AndroidRuntime(379):  at java.lang.reflect.Method.invoke(Method.java:507)
01-22 10:36:09.721: E/AndroidRuntime(379):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-22 10:36:09.721: E/AndroidRuntime(379):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-22 10:36:09.721: E/AndroidRuntime(379):  at dalvik.system.NativeStart.main(Native Method)
01-22 10:36:09.721: E/AndroidRuntime(379): Caused by: java.lang.NullPointerException
01-22 10:36:09.721: E/AndroidRuntime(379):  at learn2crack.jsonparsing.MainActivity.onCreate(MainActivity.java:29)
01-22 10:36:09.721: E/AndroidRuntime(379):  at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-22 10:36:09.721: E/AndroidRuntime(379):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

here my json data

{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":105,"name":"Disaster"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":82,"name":"Eastern"},{"id":2916,"name":"Erotic"},{"id":10751,"name":"Family"},{"id":10750,"name":"Fan Film"},{"id":14,"name":"Fantasy"},{"id":10753,"name":"Film Noir"},{"id":10769,"name":"Foreign"},{"id":36,"name":"History"},{"id":10595,"name":"Holiday"},{"id":27,"name":"Horror"},{"id":10756,"name":"Indie"},{"id":10402,"name":"Music"},{"id":22,"name":"Musical"},{"id":9648,"name":"Mystery"},{"id":10754,"name":"Neo-noir"},{"id":1115,"name":"Road Movie"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10755,"name":"Short"},{"id":9805,"name":"Sport"},{"id":10758,"name":"Sporting Event"},{"id":10757,"name":"Sports Film"},{"id":10748,"name":"Suspense"},{"id":10770,"name":"TV movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

I am still confused to the above solution, anyone can help?

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
user3197499
  • 17
  • 1
  • 7
  • 2
    which is your 29th line in Main Activity? – rupesh Jan 22 '14 at 04:13
  • Put it into the Thread First. – Kishan Dhamat Jan 22 '14 at 04:15
  • @user3197499 I'm thoroughly discouraged from answering your question because so many answers have a down vote. This box is also too small to discuss all your problems: Are you sure your JSONObject `json` is not null? Are you sure you mean to have a long network request on your main thread? Android doesn't like that. PS - "thanks brother". – Ken Jan 22 '14 at 07:45
  • @user3197499 It looks like you tried here too: http://stackoverflow.com/questions/21273950/json-parsing-android – Ken Jan 22 '14 at 07:50
  • @user3197499 Please read this. http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol – Ken Jan 22 '14 at 07:52

4 Answers4

2
 HttpGet httpPost = new HttpGet(url);
Digvesh Patel
  • 6,503
  • 1
  • 20
  • 34
1

The JSON you claim you're parsing isn't what you're parsing.

You catch the exception from jObj = new JSONObject(json); and log it; it's telling you there's a <h1> at the start of the string you're trying to parse. You then return jObj which is still null, so your app exits with a NullPointerException when you try to use it.

This is caused by the fact that you're doing a POST to the server:

HttpPost httpPost = new HttpPost(url);

which if you were to print out the results you'd find is returning:

<h1>Not Found</h1>

You need to be doing a GET

HttpGet httpGet = new HttpGet(url);

It's always a good idea to verify your inputs when trying to debug something.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • Up voted your post before the OP down votes out of ignorance. (And because it's thoroughly correct.) – Ken Jan 22 '14 at 07:47
  • @SK9 I go away for a couple hours and apparently miss out on all the fun / drama? – Brian Roach Jan 22 '14 at 08:03
  • @Brian Roach do you have solution source code to parsing a json data for this url http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0. I try but no response on emulator. – user3197499 Jan 24 '14 at 10:16
0

It seems that you are placing a long running process, i.e. network communication on the main thread. You are not allowed to do so. You can use AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html 

In addition, here's a nice video that explains JSON Parsing using AsyncTask.

http://www.youtube.com/watch?v=qcotbMLjlA4 

Just for testing you can add the following in your Main Activity but it is consider bad practice.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
android_dev_
  • 412
  • 2
  • 6
0

Your JSON object is returning 'null' that is why you are getting nullpointer exception.You have to use "GET" instead of "POST".Try this code

public JSONObject getJSONFromUrl(String jurl) {
    // Making HTTP request


    String marketUrl =jurl;             
    URL url;                
    try {
            url = new URL(marketUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-length", "0");
            conn.setAllowUserInteraction(false);
            // Starts the query
            conn.connect();
            int status = conn.getResponseCode();
            StringBuilder sb = new StringBuilder();
            switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                String responseData = sb.toString();      
                jObj = new JSONObject(responseData);
    } 
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jObj;
 }
}    
Bibin
  • 100
  • 4