Android Studio php connection

Tags: , ,



I’m trying to get information from db using php in android studio java. The php code works 100%. The problems is that when I open the app from the Android emulator the app closes itself almost instantly.

    --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.c__expensechart, PID: 2450
    java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
        at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:121)
        at org.json.JSONTokener.nextValue(JSONTokener.java:98)
        at org.json.JSONObject.<init>(JSONObject.java:165)
        at org.json.JSONObject.<init>(JSONObject.java:182)
        at com.example.c__expensechart.MainActivity$Connection.onPostExecute(MainActivity.java:89)
        at com.example.c__expensechart.MainActivity$Connection.onPostExecute(MainActivity.java:57)
        at android.os.AsyncTask.finish(AsyncTask.java:771)
        at android.os.AsyncTask.access$900(AsyncTask.java:199)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 2450 SIG: 9

This is the error message I get in run Logcat is empty The Build is also error-less From what I see there is a problem in the onPostExecute so let me show you how it looks

I have a class

class Connection extends AsyncTask<String, String, String>

in it I have two functions:

protected String doInBackground(String... params){
    String result = "";
    String host = "http://192.168.1.114/php_api/GET.php";
    try{
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(host));
        HttpResponse response = client.execute(request);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer stringBuffer = new StringBuffer("");

        String line = "";
        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
            break;
        }
        reader.close();
        result = stringBuffer.toString();
    }
    catch(Exception e){
        return new String("There exception" + e.getMessage());
    }

    return null;
}

and

protected void onPostExecute(String result){
    try {
        JSONObject jsonResult = new JSONObject(result);
        int success = jsonResult.getInt("success");
        if(success == 1){
            JSONArray measurements = jsonResult.getJSONArray("measurements");
            for(int i = 0; i < measurements.length(); i++){
                JSONObject measure = measurements.getJSONObject(i);
                int measureId = measure.getInt("id");
                double start_times = measure.getDouble("start_times");
                double end_times = measure.getDouble("end_times");
                double power = measure.getDouble("power");
                String line = measureId + ":" + start_times + ":" + end_times + ":" + power;
                setMeasureInfo(line);

            }

        }else{
            Toast.makeText(getApplicationContext(), "There aren't any measurements", Toast.LENGTH_SHORT).show();
        }
    }
    catch (JSONException e){

    }
}

Edit: About the db connection I made it so it displays me all it reads in the file just to be sure and this is what is says

{"success":1,
"measurements"[
  {"id":"1","start_times":"42405","end_times":"48","power":"65508"}
]}

My PHP code:

<?php

$host = 'localhost';
$user = 'root';
$pwd = '';
$db = 'c--db';

$conn = mysqli_connect($host, $user, $pwd, $db);

if(!$conn){
    die("ERROR in connection: " . mysqli_connect_error());
}
$response = array();

$sql_query = "SELECT * FROM `measurements`";
$result = mysqli_query($conn, $sql_query);

if(mysqli_num_rows($result) > 0){
    $response['success'] = 1;
    $measurements = array();
    while($row = mysqli_fetch_assoc($result)){
        array_push($measurements, $row);
    }
    $response['measurements'] = $measurements;
}else{
    $response['success'] = 0;
    $response['message'] =  'No data';

}
echo json_encode($response);
mysqli_close($conn);
?>

Answer

I fixed the problem. So actually I double checked the error log and found it had something to do with apache library I searched the error and found I had to add it to AndroidManifest.xml too it should look like this:

<application
    ...
    ...
    android:usesCleartextTraffic="true"
    android:requestLegacyExternalStorage="true">
    ...
    ...
    <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />
</application>


Source: stackoverflow