Wednesday 2 December 2020

Android URL Connection error: Database connection error using XAMPP

I'm currently building a project that need to manage a history transaction database.

I follow the instruction of this website in order to connect my database to the project:

How To Connect An Android App To A MySQL Database

After that, I try to build my project with this code in Fragment_History, however, this error occured:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mind.loginregisterapps, PID: 6912
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.JSONArray.<init>(JSONArray.java:94)
    at org.json.JSONArray.<init>(JSONArray.java:110)
    at com.mind.loginregisterapps.Fragment_History.loadIntoListView(Fragment_History.java:83)
    at com.mind.loginregisterapps.Fragment_History.access$000(Fragment_History.java:24)
    at com.mind.loginregisterapps.Fragment_History$1DownloadJSON.onPostExecute(Fragment_History.java:55)
    at com.mind.loginregisterapps.Fragment_History$1DownloadJSON.onPostExecute(Fragment_History.java:42)
    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 checked the code, and realised that the null value being passed down due to failed to connect URL in downloadJSON.

Therefore, I added res/xml/network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

and edited Manifest:

<application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"
</application>

But then, this error occur when using HTTPUrlConnection, and I'm stumbled:

Failed to connect to localhost/127.0.0.1:80

I attempted to change localhost to 127.0.0.1 in downloadJSON and network_security_config.xml, and the error turned into:

Failed to connect to /127.0.0.1:80

How can I fix this issue? Please let me know.

Thank you so much!

Here is the code for:

Fragment_History.java

public class Fragment_History extends Fragment {

ListView listView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_history, container, false);

    listView = (ListView)view.findViewById(R.id.list_history);
    downloadJSON("http://localhost/hist_login.php");

    return view;
}

private void downloadJSON(final String urlWebService) {

    class DownloadJSON extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
            try {
                loadIntoListView(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }
        }
    }
    DownloadJSON getJSON = new DownloadJSON();
    getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);
    ArrayList<History> list = new ArrayList<History>();
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.getJSONObject(i);
        list.add(new History(obj.getString("h_rName"),obj.getDouble("h_amount")));
    }
    HistoryAdapter adapter = new HistoryAdapter(list, getActivity());
    listView.setAdapter(adapter);
}

}

hist_login.php:

<?php
$db = "test";
$user = "root";
$pass = "";
$host = "localhost";

// Create connection
$con=mysqli_connect($host,$user,$pass,$db);
 
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
 
// Select all of our stocks from table 'history'
$sql = "SELECT * FROM history";
 
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
    // We have results, create an array to hold the results
        // and an array to hold the data
    $resultArray = array();
    $tempArray = array();
 
    // Loop through each result
    while($row = $result->fetch_object())
    {
        // Add each result into the results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }
 
    // Encode the array to JSON and output the results
    echo json_encode($resultArray);
} else
{
    echo "Not connected...";
}
 
// Close connections
mysqli_close($con);
?>


from Android URL Connection error: Database connection error using XAMPP

No comments:

Post a Comment