1

I am trying to get a data from URL using some tutorials in connecting to mysql using php.

However, I get a nullpointerexception when I run the code.

Database_demo.java

 package com.database_demo;

 import java.io.BufferedReader;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.List;

 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.NameValuePair;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;

 import android.app.ListActivity;
 import android.net.ParseException;
 import android.os.Bundle;
 import android.widget.ArrayAdapter;
 import android.widget.Toast;

 public class Database_demo extends ListActivity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    List<String> r = new ArrayList<String>();

    try{

    //http post
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://uragon-dev.com/synergy/webservices.php?action=displayAll");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }
    catch(Exception e){
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
   }

    //Convert response to string  
    try
    {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));

      sb = new StringBuilder();

      String line = null;

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

      is.close();

      result = sb.toString();
    }
    catch(Exception e)
    {
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }
    //END Convert response to string   
    try{
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++)
            {
               json_data = jArray.getJSONObject(i);
               r.add(json_data.getString("users"));
           }
           setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
        }
        catch(JSONException e1){
            Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
        } catch (ParseException e1) {
            Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
    }

}
 }

The error in the logcat points to this line.

 try{
            JSONArray jArray = new JSONArray(result);

Here is the data to fetched on the url http://uragon-dev.com/synergy/webservices.php?action=displayAll

{"users":[{"username":"jokerxvier","firstname":"jason","lastname":"javier"},{"username":"migz","firstname":"miguel","lastname":"rivera"}],"success":1}

What could be the problem that is causing this? Also I would like to know how can I pass data to the url and not just fetching data from it. Android newbie here. Thanks!

Jeongbebs
  • 4,100
  • 7
  • 34
  • 60

3 Answers3

0

Looks like you are trying to attempt a network operation on the main thread. Have a look at this post on how to handle this: https://stackoverflow.com/a/6343299/2045570

Read the docs

EDIT:

The reason you are getting a JSON error is because you are catching your first exception: HERE

    try{

    //http post
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://uragon-dev.com/synergy/webservices.php?action=displayAll");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }
    catch(Exception e){
        Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();

   }

So here:

JSONArray jArray = new JSONArray(result);

result will always be null. This is your first problem you need to solve. You can't access the network from your main thread.

To see your error message add this line : e.printStackTrace(); to your catch block and it will print a android.os.NetworkOnMainThreadException in your logcat output.

Community
  • 1
  • 1
nedaRM
  • 1,837
  • 1
  • 14
  • 28
  • I get these errros in the logcat `at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) at org.json.JSONTokener.nextValue(JSONTokener.java:94) at org.json.JSONArray.(JSONArray.java:87) at org.json.JSONArray.(JSONArray.java:103) ` is the json part wrong? – Jeongbebs Sep 25 '13 at 03:16
  • @MiguelRivera That's exactly what I said it would be. Please read this answer here: http://stackoverflow.com/a/6343299/2045570 – nedaRM Sep 25 '13 at 03:37
  • so i'm to create a new method like the one given in the link? – Jeongbebs Sep 25 '13 at 03:42
  • Network on main thread is definitely a issue but that exception added on Android 3.0 or API level 11, so if you run you app on older Android version you will not get networkonMainThread error. – minhaz Sep 25 '13 at 03:45
  • i'm really a newbie here so any help would be very appreciated. – Jeongbebs Sep 25 '13 at 03:50
0

you said the error is on the JSONArray jArray = new JSONArray(result);. If this is the case, could you try checking the value of result? Maybe use Log to display it on the Logcat.

If the error is NetworkOnMainThread, you will need to check the answer from @user2045570

Hope this helps, Good luck

Reid

reidzeibel
  • 1,622
  • 1
  • 19
  • 24
0

You have couple of issue. JSON you are trying to read is not an array that's an object. So code should be

JSONObject result = new JSONObject(result);
JSONArray users = result.getJSONArray("users");

And, please do not open network connection on main thread.

minhaz
  • 4,233
  • 3
  • 33
  • 49
  • I followed your answer and I get these messages on the logcat. http://shrib.com/logerror The logcat points to this error. ` HttpResponse response = httpclient.execute(httppost); ` – Jeongbebs Sep 25 '13 at 03:33