java - error parsing data from mysql database

284

I am developing an android application. I'm trying to get data from a mysql database and I keep getting this error. Can't seem to figure out what is wrong. Here is my code and my logs.

Log:

02-02 17:00:40.289        89-89/system_process W/InputManagerService: Window already focused, ignoring focus gain of: [email protected]
02-02 17:00:48.338    1039-1056/com.example.busscheduledatarecorder E/My Error: Error D
02-02 17:00:48.461    1039-1056/com.example.busscheduledatarecorder E/My Error: Error D
02-02 17:01:05.339    1039-1056/com.example.busscheduledatarecorder E/response string: [ 02-02 17:01:05.762  1039:0x420 E/JSON Parser ]
    Error parsing data org.json.JSONException: End of input at character 1 of
02-02 17:01:06.228    1039-1039/com.example.busscheduledatarecorder D/AndroidRuntime: Shutting down VM
02-02 17:01:06.265    1039-1039/com.example.busscheduledatarecorder W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
02-02 17:01:06.398    1039-1039/com.example.busscheduledatarecorder E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.example.busscheduledatarecorder.MainActivity$Load_Routes.onPostExecute(MainActivity.java:407)
    at com.example.busscheduledatarecorder.MainActivity$Load_Routes.onPostExecute(MainActivity.java:375)
    at android.os.AsyncTask.finish(AsyncTask.java:602)
    at android.os.AsyncTask.access$600(AsyncTask.java:156)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4424)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)
02-02 17:01:06.534       89-473/system_process W/ActivityManager: Force finishing activity com.example.busscheduledatarecorder/.MainActivity

PHP code:

<?php
$response = array();
$response["success"] = 0;
$response["message"] = "No routes found";

// include db connect class
include('db.php');

// connecting to db
$db = new DB_CONNECT();

// get all routes from route table
$result = mysql_query("SELECT * FROM route");

// check for empty result
if ($result && mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["routes"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $route = array();
    $route["busRouteId"] = $row["busRouteId"];
    $route["routeName"] = $row["routeName"];

    // push single product into final response array
    array_push($response["routes"], $route);
}
// success
$response["success"] = 1;

}
// Echo JSON anyway!
echo json_encode($response);
die();
?>

Java Code:

public class JSONParser {

    String result = null;
    DBHelper db;
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

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();
        Log.e("My Error", "Error A " + e.toString());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.e("My Error", "Error B " + e.toString());
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("My Error", "Error C " + e.toString());
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        Log.e("My Error", "Error D ");
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            Log.e("My Error", "Error D ");
        }
        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 {
        Log.e("response string",json);
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}}

MainActivity:

public class MainActivity extends Activity {

DBHelper db;
int routeloadsuccess;

JSONArray jArray = null

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

    spinroute= (Spinner)findViewById(R.id.spinnerroute);
    pb = (ProgressBar) findViewById(R.id.progressBar);
    pb.setVisibility(View.INVISIBLE);
    db = new DBHelper(this);
}

public void shout(String voice)
{Toast.makeText(this, voice,Toast.LENGTH_LONG).show();}



public void insertNewRoutes(int id, String routename){
    //check if route exists
    boolean exists = db.checkRouteforId(id), result = false;
    if(exists)
    {
        result = db.updateRoute(id, routename);

    }
    else{ result = db.insertRoute(id, routename);}
    if(result){routeloadsuccess = 1;}

}

private class Load_Routes extends AsyncTask<String, String, JSONObject>{

    InputStream is;
    String url;
    private static final String TAG_ROUTE = "bus_route";

    public Load_Routes()
    {
         is = null;
         url = "http://busscheduledata.com/RouteMobile.php";
    }
    @Override
    protected JSONObject doInBackground(String... arg0) {

        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(url);

       return json;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        shout("Loading Routes...");
        pb.setVisibility(View.VISIBLE);
    }
  @Override
    protected void onPostExecute(JSONObject json) {
        // TODO Auto-generated method stub
      pb.setVisibility(View.INVISIBLE);
          try {
            // Getting JSON Array

              int success = json.getInt("success");
              if (success == 1) {
                  JSONArray JAStuff = json.getJSONArray("response");

                  /** CHECK THE NUMBER OF RECORDS **/
                  int intStuff = JAStuff.length();

                  if (intStuff != 0)  {

                      for (int i = 0; i < JAStuff.length(); i++) {
                          JSONObject JOStuff = JAStuff.getJSONObject(i);
                          Log.e("ALL THE STUFF", JOStuff.toString());

                          // Storing  JSON item in a Variable
                          int routeid = JOStuff.getInt("busRouteId");
                          String routename = JOStuff.getString("routeName");

                          //Set JSON Data in spinner
                          insertNewRoutes(routeid,routename );

                      }
                  }
              }




        } catch (JSONException e) {
            e.printStackTrace();
            shout("Loading failed");
        }



    }
    }//end of loading route thingy



    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    populateMenu(menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    applyMenuChoice(item);
    return(applyMenuChoice(item) ||super.onOptionsItemSelected(item));
}

private void populateMenu(Menu menu) {
    menu.add(0, SIXTEEN_ID, 0, "Get Routes");
}
private boolean applyMenuChoice(MenuItem item) {
    Intent intent;
    switch (item.getItemId())
    {
        case SIXTEEN_ID:
            db.deleteAllRoutes();
            Load_Routes lr = new Load_Routes();
            lr.execute();
            if(routeloadsuccess == 1){
            shout("Loading Complete");
            intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);}
            return(true);
        //break;

    }
    return true ;
}


}
494

Answer

Solution:

Log.e("response string",json);

This line is printing: E/response string: n

Your response is "n" which is String. In the next line you are converting it into a JsonObject which will definitely throw the exception.

jObj = new JSONObject(json);

Change the response from server from String to Json

People are also looking for solutions to the problem: php - SessionHandlerInterface write method alternatives

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.