0

I have a very basic register script in Android but Android wont connect to my localhost phpmyadmin database (XAMPP).

I was told it could be my XAMPP settings, or I'm using the wrong URL, or I need a timeout chunk in my script. I've been through a lot of debugging methods, but the only result i got was

/Create User: com.android.volley.NoConnectionError: java.io.EOFException.

And now even that error is gone. I don't get any errors, and my script does nothing.

Here is my CreateUser script;

public class CreateUser extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_user);
        this.setTitle("Create User");
        final EditText username1 = findViewById(R.id.Createusername);
        final EditText password1 = findViewById(R.id.CreatePassword);
        final Switch isAdmin = findViewById(R.id.isadmin);
        final Button createuser = findViewById(R.id.createuserbtn);
        if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
            isAdmin.setVisibility(View.GONE);
        }
        createuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String username = username1.getText().toString();
                final String password = password1.getText().toString();
                if (isAdmin.getShowText()) {
                    Global.isadmin = "1";
                }else{
                    Global.isadmin ="0";
                }
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");
                            if (success){
                                Intent intent = new Intent(CreateUser.this, MainActivity.class);
                                CreateUser.this.startActivity(intent);
                            }else{
                                AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry",null)
                                        .create()
                                        .show();


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                int socketTimeout = 250000;//30 seconds - change to what you want
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                RegisterRequest registerRequest = new RegisterRequest(username,password,Global.isadmin,responseListener);
                registerRequest.setRetryPolicy(policy);
                RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
                queue.add(registerRequest);
            }
        });
    }

Here is my RegisterRequest class;

public class RegisterRequest extends StringRequest {

    private static final String REGISTER_REQUEST_URL = "http://10.0.2.2:3306/phptesting/Register.php"; //the address was localhost, then my ipaddress, and now its this code i was told to put in
    private Map<String, String> params;
    public RegisterRequest(String username, String password, String isAdmin, Response.Listener<String> listener){
        super(Method.POST, REGISTER_REQUEST_URL,listener,null);
        params = new HashMap<String, String>();
        params.put("username",username);
        params.put("password",password);
        params.put("isAdmin", isAdmin);
    }

    public Map<String, String> getparams() {
        return params;
    }
}

and if you need it, here is my PHP script located in htdocs in XAMPP.

<?php
    $db_host = 'localhost:3306';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'test';

    $con = mysqli_connect($db_host,'user',$db_pass,$db_name);
    if($con){
        echo "connection successful";
    }else{
        echo "connection failed";
    }

    $age = $_POST["isAdmin"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
    if(!$statement) { printf("Prepare failed: %s\n", mysqli_error($con)); }
    if(!$statement) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
    mysqli_stmt_bind_param($statement, "sss",$username,$password,$isAdmin);
    mysqli_stmt_execute($statement);
    if(mysqli_error($statement)) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }

    $response = array();
    $response["success"] = true;  

    echo json_encode($response);
    ?>

I appreciate all help, and I'd love it if someone were to walk with me on trying to create this simple login and register app.

Shashanth
  • 4,995
  • 7
  • 41
  • 51
  • 1
    Do your Manifest allow internet connections? – statosdotcom Nov 05 '18 at 02:07
  • @statosdotcom yes, –  Nov 05 '18 at 02:24
  • is your php file working correctly? and local host address is ok ? – PushpikaWan Nov 05 '18 at 02:28
  • @Lucefer yes. Php (in url) works, but i get some warnings and such. "connection successful Notice: Undefined index: isAdmin in C:\xampp\htdocs\testing\Register.php on line 14 Notice: Undefined index: username in C:\xampp\htdocs\testing\Register.php on line 15 Notice: Undefined index: password in C:\xampp\htdocs\testing\Register.php on line 16 Warning: mysqli_error() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\testing\Register.php on line 22 {"success":true}" –  Nov 05 '18 at 02:35
  • 1
    those notices will likely create some html output , which will not be JSON decodable android side. Fix them. – YvesLeBorg Nov 05 '18 at 02:48
  • @YvesLeBorg well, how would i go about logging HTML errors? –  Nov 05 '18 at 02:57

2 Answers2

1

You're getting errors due to the wrong URL you're using in your code.

private static final String REGISTER_REQUEST_URL = "http://10.0.2.2:3306/phptesting/Register.php"; 

I'm not sure whether you're aware of it or not. Port number 3306 is reserved for MySQL database engine. Where, Apache server works on port number 80 or any other port if you've configured to use other port number.

Now you need to change that URL to something like below (just remove :3306).

private static final String REGISTER_REQUEST_URL = "http://10.0.2.2/phptesting/Register.php"; 

Keep in mind that this URL (10.0.2.2) works only on Android emulators not on real devices. So, I suggest you to use the system (LAN) IP address which works fine on both emulator as well as real devices.

How to check IP address?

First connect your system and phone (or emulator) to the same WiFi network or mobile hotspot.

And open command prompt, type ipconfig which returns an output like below

C:\Users\user_name>ipconfig

Windows IP Configuration


Wireless LAN adapter Wireless Network Connection 2:

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

Wireless LAN adapter Wireless Network Connection:

Connection-specific DNS Suffix  . :
Link-local IPv6 Address . . . . . : ******
IPv4 Address. . . . . . . . . . . : 192.168.1.141
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : ******
                                   192.168.*.*

Ethernet adapter Local Area Connection:

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{******}:

Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

C:\Users\user_name>

Now check for

Wireless LAN adapter Wireless Network Connection:

Connection-specific DNS Suffix  . :
Link-local IPv6 Address . . . . . : ******
IPv4 Address. . . . . . . . . . . : 192.168.1.141
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : ******
                                   192.168.1.1

Copy IPv4 address 192.168.1.141 and prepare a URL like this

private static final String REGISTER_REQUEST_URL = "http://192.168.1.141/phptesting/Register.php";

The IP address differs from system to system. And also keep in mind that to get an IP address you should connect your system to WiFi (or LAN) network.

I you've configured Apache port address to something else, the URL look like this

private static final String REGISTER_REQUEST_URL = "http://192.168.1.141:80/phptesting/Register.php";

In which the port number is 80

Shashanth
  • 4,995
  • 7
  • 41
  • 51
  • 1
    Dude, i think you're honestly onto something. No one ever told me to use Apache's port, and not MySQL's before. I'll test this immediately –  Nov 05 '18 at 04:25
  • False alarm. It didnt work. I used the Apache port, and my ip address and got an error. "Unexpected response code 404 for" then it lists the URL. –  Nov 05 '18 at 04:31
  • If Apache port address is `80`, you can omit 80. If it is 8080 use `8080`. What's your port address? You need to use your system IP address not used in my answer. Make sure that the URL is accessible though-out LAN (and it works fine) using Postman client. `404` means you're using a wrong URL or the service doesn't exist which you're trying to use. – Shashanth Nov 05 '18 at 04:37
  • xampp gives me 2 apache ports to use. 80, and 443. i used 80. I am using my ip address (its not hard to find a person ip address, but thats for that tutorial). And as for the postman, i thought if i run everything on the machine, itd pick it up. But postman sounds like a hosting service, and i wanted to run everything locally first. –  Nov 05 '18 at 04:47
  • 1) Make sure that the PHP files are under `C:\xampp\htdocs\phptesting\` 2) Skip `80` in URL by default it points to Apache 3) Postman is not hosting service it's a REST API testing tool my friend. Which helps us to test the API to make sure it works fine. – Shashanth Nov 05 '18 at 04:55
  • yes, my file is in the right area. localhost/phptesting/Register.php pull ups fine in browser. As for the port, do you wish for me to use the other port, 443? or get rid of it entirely? And, ill give this postman site a try once i figure out how to work it –  Nov 05 '18 at 05:24
  • yea, i got no idea how to even use postman. could you walk me through a couple steps to get it to do what you want this thing to do? cuz the hell if i know what this thing is –  Nov 05 '18 at 05:36
  • You don't need to use `443` port address. Just remove `:80` from URL and give a try. If you want to try the same URL with Postman, then download & install Postman from [here](https://www.getpostman.com/). And there are numerous of tutorials on Postman client usage. I found [this](http://toolsqa.com/postman-tutorial/) top result in Google search. – Shashanth Nov 05 '18 at 05:59
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183105/discussion-between-alec-harvey-and-shashanth). –  Nov 05 '18 at 06:09
0

This Android: Volley NoConnectionError will help for u. Most probably your ip address and port is not correct. You can check it by entering ip address and port in mobile (emulator) browser then check whether it is correctly loaded. If not find correct ip address and port for your application.

There can be emulator and your xampp server not in same network. You can check that also trying to browse ip address and port in your mobile address.

PushpikaWan
  • 2,437
  • 3
  • 14
  • 23
  • I already looked into that, hence why my url isnt my address or localhost. Read the comment line beside the URL. Also, you got interested in this "entering ip address and port in mobile (emulator) browser then check whether it is correctly loaded" how would i go about that? i can set my emulator to run on the same ip address as my computer? isnt that what the URL is supposed to do? –  Nov 05 '18 at 02:38
  • no Your emulator is up from another port. basically go browser in emulator. then enter "http://10.0.2.2:3306/phptesting/Register.php" . Then check whether you get same output as you run it in your machine browser – PushpikaWan Nov 05 '18 at 02:41
  • you can check your rela ip address by in Linux: ifconfig [wlan0] in Windows use: ipconfig – PushpikaWan Nov 05 '18 at 02:44
  • when i typed in the exact url of my php file into the emulator's browser, the browser immediately started to download something, but then stopped. Im guessing it found the PHP file alright. –  Nov 05 '18 at 02:55
  • In your noram machine browser also doing same thing ? – PushpikaWan Nov 05 '18 at 03:06
  • try theses https://stackoverflow.com/questions/40943/how-to-automatically-start-a-download-in-php solutions – PushpikaWan Nov 05 '18 at 03:07
  • its not supposed to download anything. When i open it in my computer, it runs the php script and what i see is the output. –  Nov 05 '18 at 03:08
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183101/discussion-between-alec-harvey-and-lucefer). –  Nov 05 '18 at 04:25