0

Hello im trying to retrieve some data from a website using JSON. I got some code from an tutorial but the tutorial didn't work. I thought it was becuase the url from the tutorial wasn't working, but when i tried a working url it still gives the same error. Can someone tell me what I'm doing wrong. I read everywhere that using JSON should be very simple and easy, but I really got an headache trying al the tutorials and reading al the examples.

Heres the code from the tutorial called Main.java:

public class Main extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

//the website I use lacks some security so I don't wanne put it here.
//its still under construction.       
    JSONObject json = JSONfunctions.getJSONfromURL("http://somewebsite/jsonexample.html");

    try{

        JSONArray  student = json.getJSONArray("student");

        for(int i=0;i<student.length();i++){                        
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = student.getJSONObject(i);

            map.put("id",  String.valueOf(i));
            map.put("name", "Naam: " + e.getString("name"));
            map.put("age", "Leeftijd: " +  e.getString("age"));
            mylist.add(map);            
        }       
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                    new String[] { "name", "age" }, 
                    new int[] { R.id.item_title, R.id.item_subtitle });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);  
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
            Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

        }
    });
}
}

Here is the code from the tutorial called JSONfunctions.java:

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url){
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }

  //convert response to string
    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();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }

    try{

        jArray = new JSONObject(result);            
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}
}

the json:

{ "student":[{ "id" : "1", "name" : "Piet", "age" : "10" }{ "id" : "2", "name" : "Jaap", "age" : "6" }] }

And the logcat:

03-12 11:24:09.773: E/AndroidRuntime(911): FATAL EXCEPTION: main
03-12 11:24:09.773: E/AndroidRuntime(911): java.lang.RuntimeException: Unable to start              activity ComponentInfo{me.mikey.my.games.galgjex/me.mikey.my.games.galgjex.Main}:        java.lang.NullPointerException
03-12 11:24:09.773: E/AndroidRuntime(911):  at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
03-12 11:24:09.773: E/AndroidRuntime(911):  at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.os.Looper.loop(Looper.java:137)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.app.ActivityThread.main(ActivityThread.java:4745)
03-12 11:24:09.773: E/AndroidRuntime(911):  at java.lang.reflect.Method.invokeNative(Native Method) 
03-12 11:24:09.773: E/AndroidRuntime(911):  at java.lang.reflect.Method.invoke(Method.java:511)
03-12 11:24:09.773: E/AndroidRuntime(911):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
03-12 11:24:09.773: E/AndroidRuntime(911):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-12 11:24:09.773: E/AndroidRuntime(911):  at dalvik.system.NativeStart.main(Native  Method)
03-12 11:24:09.773: E/AndroidRuntime(911): Caused by: java.lang.NullPointerException
03-12 11:24:09.773: E/AndroidRuntime(911):  at  me.mikey.my.games.galgjex.Main.onCreate(Main.java:41)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.app.Activity.performCreate(Activity.java:5008)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
03-12 11:24:09.773: E/AndroidRuntime(911):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
03-12 11:24:09.773: E/AndroidRuntime(911):  ... 11 more

Changed json to: { "student":[{ "id" : "1", "name" : "Piet", "age" : "10" },{ "id" : "2", "name" : "Jaap", "age" : "6" }] } But it still gives an NPE. Or is my json still invalit?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Zeebats
  • 480
  • 7
  • 22
  • What is line no 47 in your Main.java – Pragnani Mar 12 '13 at 11:54
  • @Pragnami Line 47 is map.put("id", String.valueOf(i)); or did u mean line 41? that is JSONArray student = json.getJSONArray("student");. – Zeebats Mar 12 '13 at 11:57
  • Well i think Your JSON is Invalid.. May be You are missing a comma.. – Sanober Malik Mar 12 '13 at 11:58
  • @user2119398 Sorry it is 41 not 47 typing mistake..post it – Pragnani Mar 12 '13 at 11:58
  • @user1566160 yes you are right, invalid json missing comma after a record, but the exception is not a JSONEXception, instead it is NPE so there might be something wrong – Pragnani Mar 12 '13 at 12:00
  • I put a comma after the record (see above) but the error is the same. – Zeebats Mar 12 '13 at 12:07
  • @user2119398 Have you debugged it or log it, are getting the response from the service..? – Pragnani Mar 12 '13 at 12:10
  • @user2119398 : put a log for `result=sb.toString();` as `Log.e("log_tag", " JSON DATA ::-- "+result);` and check what u are getting in response from webservice ? – ρяσѕρєя K Mar 12 '13 at 12:15
  • This are the logs:03-12 12:22:47.573: E/log_tag(1914): Error in http connection android.os.NetworkOnMainThreadException 03-12 12:22:47.573: E/log_tag(1914): Error converting result java.lang.NullPointerException 03-12 12:22:47.603: E/log_tag(1914): Error parsing data org.json.JSONException: End of input at character 0 of. I see the netword exeption. Something wrong with connectiong to the page? I have put permission internet in the manifest. – Zeebats Mar 12 '13 at 12:24
  • can you fetch the URL in android browser? – Nezam Mar 12 '13 at 12:28
  • Try to return a minimal data set, including an empty json array. See if it works. If it does, add more data; if it does not, simplify it further until it works, and then add data. – 18446744073709551615 Mar 12 '13 at 12:29
  • Is it necessary to put html tags on the page? There is only the json array on it now? I will try fetchurl too. – Zeebats Mar 12 '13 at 12:35
  • Tell me if you can fetch the URL in android stock browser.If you can't you just need to add Internet Permission or enable mobile data... if that solves it tell me.. i will post it as an answer inshallah – Nezam Mar 12 '13 at 12:38
  • Yes the browser on the emulator can connect to the page. and I already have set the permission internet. ( ) – Zeebats Mar 12 '13 at 12:43
  • @user2119398 check my answer...The cause for your Exception is performign network operation on UI thread and so your jsonobject is null, so you are getting NPE also – Pragnani Mar 12 '13 at 12:43

2 Answers2

0

Check the Website Address..

If your Website is correct and if you run your Application in Emulator you will Get NullpointerException.Once check it in Your Device whether you are getting JSON response. Still if your getting Error Check whether you added Permission in Manifest file. If your not added permission add the below permission in manifest file.

             <uses-permission android:name="android.permission.INTERNET"/>

And look at the below link this will help you http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

user1835052
  • 455
  • 1
  • 5
  • 11
0

Place all your code in separate thread or in the AsyncTask and also make sure that you've kept the permission

 <uses-permission android:name="android.permission.INTERNET"/>

in your manifest

Try this code to get the data from the Service

How one interface can be used for different background android tasks?

Community
  • 1
  • 1
Pragnani
  • 20,075
  • 6
  • 49
  • 74
  • I think your right. Now I read about the network exeption I read you can't use it on the main thread. I will learn how to use the asynctask now (still don't get the String,String,String part, becuase in other examples this is Void,Void,Void or Url, Cursor, Cursor.) , but thank you very much for your help. – Zeebats Mar 12 '13 at 13:27
  • @user2119398 in the Three parameters are async task result is the return type of the doInBackGround method and parameter of onPostExecute, Params is the type of Parameters in the doInBackground and progress is type of data you need to update the progress – Pragnani Mar 12 '13 at 13:30
  • @user2119398 you can mark this as answer by clicking on the right mark beside the answer – Pragnani Mar 12 '13 at 13:31