Search code examples
javaphpandroidmysqllocalhost

Connect my Android app trough an api to my server on my localhost


I have a problem. I want to connect my android app to a PHP API which runs on my localhost. But in this code it always throws the "Catch 1" and I even tried to print the exception but it didn't work. Here is the code of my MainActivity:

    package com.example.dbtest;

    import androidx.appcompat.app.AppCompatActivity;

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import org.json.JSONObject;

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.Console;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class MainActivity extends AppCompatActivity {
    private EditText etUsername;
    private EditText etPassword;

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

        etUsername = findViewById(R.id.editTextUsername);
        etPassword = findViewById(R.id.editTextPassword);
    }

    public void register(View view) {
        Log.d("MainActivity", "Button clicked");
        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        String url = "http://app.test/test.php?username="+ username +"&password="+ password;
        new MyAsyncTaskgetNews().execute(url);
    }

    public class MyAsyncTaskgetNews extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            //before works
        }

        @Override
        protected String  doInBackground(String... params) {
            Log.d("MainActivity","In Background");
            // TODO Auto-generated method stub
            try {
                String NewsData;
                //define the url we have to connect with
                URL url = new URL(params[0]);
                //make connect with url and send request
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                //waiting for 7000ms for response
                urlConnection.setConnectTimeout(7000);//set timeout to 5 seconds

                try {
                    //getting the response data
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    //convert the stream to string
                    NewsData = ConvertInputToStringNoChange(in);
                    //send to display data
                    publishProgress(NewsData);
                } finally {
                    //end connection
                    urlConnection.disconnect();
                }

            }catch (Exception ex)
            {
                Log.d("MainActivity", "Catch 1");
            }

            return null;
        }

        protected void onProgressUpdate(String... progress) {
            try {
                Log.d("MainActivity","In Progress");
                JSONObject json = new JSONObject(progress[0]);
                //display response data
                Toast.makeText(getApplicationContext(),json.getString("msg"),Toast.LENGTH_LONG).show();

            } catch (Exception ex) {
                Log.d("MainActivity","Catch 2");
            }
        }

        protected void onPostExecute(String  result2){
        }
    }

    // this method convert any stream to string
    public static String ConvertInputToStringNoChange(InputStream inputStream) {
        BufferedReader bureader=new BufferedReader( new InputStreamReader(inputStream));
        String line ;
        String linereultcal="";

        try{
            while((line=bureader.readLine())!=null) {

                linereultcal += line;

            }
            inputStream.close();


        }catch (Exception ex){}

        return linereultcal;
    }
}

My PHP API is very simple so don't go too hard on me! But I checked multiple times that the API works I can successfully add data to my database! I think the problem is in my android code. Here is the code of my PHP API:

<?php

$host = "localhost";
$user = "root";
$DBpassword = "admin123";
$database = "demo";
$connect = mysqli_connect($host,$user,$DBpassword,$database);

if(mysqli_connect_errno()) 
{
    die("Error in connection: " . mysqli_connect_errno());
    return;
}

// get the data from html request
$username = $_GET['username'];
$password = $_GET['password'];

// define the query
$query = "INSERT INTO user(username,password) values('$username','$password');";

$result = mysqli_query($connect, $query);

if(!$result) 
{
    $output = "{'msg':'Inserting failed'}";
}
else 
{
    $output = "{'msg':'Insterting succsessfull'}";
}

print($output);

mysqli_close($connect);
?>

Here is my Stacktrace as requested!

2020-06-19 11:03:21.467 3017-3663/com.example.dbtest W/System.err: java.net.ConnectException: Connection refused
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at java.net.PlainSocketImpl.socketConnect(Native Method)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at java.net.Socket.connect(Socket.java:605)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.Connection.connectSocket(Connection.java:196)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:172)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
2020-06-19 11:03:21.518 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
2020-06-19 11:03:21.519 3017-3663/com.example.dbtest W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
2020-06-19 11:03:21.521 3017-3663/com.example.dbtest W/System.err:     at com.example.dbtest.MainActivity$MyAsyncTaskgetNews.doInBackground(MainActivity.java:69)
2020-06-19 11:03:21.521 3017-3663/com.example.dbtest W/System.err:     at com.example.dbtest.MainActivity$MyAsyncTaskgetNews.doInBackground(MainActivity.java:44)
2020-06-19 11:03:21.522 3017-3663/com.example.dbtest W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:305)
2020-06-19 11:03:21.522 3017-3663/com.example.dbtest W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
2020-06-19 11:03:21.523 3017-3663/com.example.dbtest W/System.err:     at java.lang.Thread.run(Thread.java:761)

Does anyone have an idea what the problem could be? Any help is appreciated.

PS: Sorry for my bad English, it's not my mother tongue.


Solution

  • I finally figured it out.

    I had the API running on a custom virtualhost, so the emulator could not connect to my custom virtualhost. I moved my API to the "original" localhost folder and edited my url in code. My url now looks like this:

    String url = "http://10.0.2.2/test.php?username="+ username +"&password="+ password;
    

    The ip 10.0.2.2 I found out is a shortcut to your machines localhost.

    If any questions occur I try my best to help!