duancheng7743 2017-01-10 11:05
浏览 88

Android注册表单未发布到MySQL - localhost

I am new to android and trying to learn develop a simple registration form. I followed an youtube tutorial and the codes for the same are available in github.
I am using php-mysql installed locally on my machine. Hence for the path to url - both register request as well as login request, I am using the following urls:

http://192.168.0.101/register.php
http://192.168.0.101/login.php

When I run these files in my browser locally using:

http://127.0.0.1/register.php
http://127.0.0.1/login.php

it doesn't return any error.

The connection in the register and login php files are made as follows:

$con = mysqli_connect("localhost", "root", "ABCABC", "agnya");

The app upon providing username and password should open a third page or when I register using the registration page, should update the db and return the login page.

The problem is:

The app runs on VM locally without any errors, however upon entering the details and clicking the login or register buttons, I see no action or no error messages. I have tried changing the url in various combinations as follows:

127.0.0.1, 127.0.0.1:3306, 192.168.0.101,192.168.0.101:3306, localhost, 10.0.2.2, 10.0.2.3

and in the php files instead of localhost i have used all these and in various combinations of these.

I have been struggling with a solution for this for the last 3 days, but to no avail. Do i have to use a jsonparser- I saw an option like that somewhere.

I configured a table in Mysql hosted on the cloud, and used the cloud credentials, still not working. Any thoughts?

Application Manifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="INTERNET"></uses-permission>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".registerActivity" />
    <activity android:name=".userDetailsActivity"></activity>
</application>

RegisterActivity.java

   package inagnya.axiomanalytics.www.agnya;


import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;

import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.android.volley.RequestQueue;

import org.json.JSONException;
import org.json.JSONObject;

public class registerActivity extends AppCompatActivity {

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

        final EditText etNameReg = (EditText) findViewById(R.id.etNameReg);
        final EditText etUsernameReg = (EditText) findViewById(R.id.etUsernameLog);
        final EditText etPasswordReg = (EditText) findViewById(R.id.etPasswordLog);
        final EditText etAgeReg = (EditText) findViewById(R.id.etAgeWel);
        final Button btnRegister = (Button) findViewById(R.id.btnRegister);


        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = etNameReg.getText().toString();
                final String username = etUsernameReg.getText().toString();
                final String password = etPasswordReg.getText().toString();
                final int age = Integer.parseInt(etAgeReg.getText().toString());

                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(registerActivity.this, LoginActivity.class);
                                registerActivity.this.startActivity(intent);
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(registerActivity.this);
                                builder.setMessage("Registration Failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                RegisterRequest registerRequest = new RegisterRequest(name,username,password,age,responseListener);
                RequestQueue queue = Volley.newRequestQueue(registerActivity.this);
                queue.add(registerRequest);
            }
        });

    }


    }

RegisterRequest.java

package inagnya.axiomanalytics.www.agnya;

import java.util.HashMap;
import java.util.Map;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

/**
 * Created by mageshpoondi on 08/01/17.
 */

public class RegisterRequest extends StringRequest{

    private static final String REGISTER_REQUEST_URL = "http://192.168.0.101/register.php";
    private Map<String, String> params;

    public RegisterRequest(String name, String username, String password, int age, Response.Listener<String> listener) {
        super(Method.POST, REGISTER_REQUEST_URL,listener,null);
        params = new HashMap<>();
        params.put("name", name);
        params.put("username", username);
        params.put("password", password);
        params.put("age", age + "");
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
    }

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_register"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="inagnya.axiomanalytics.www.agnya.registerActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="11dp"
        android:layout_marginStart="11dp"
        android:id="@+id/etNameReg"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Name" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_below="@+id/etNameReg"
        android:id="@+id/etUsernameLog"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignLeft="@+id/etNameReg"
        android:layout_alignStart="@+id/etNameReg"
        android:hint="Username" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etPasswordLog"
        android:layout_below="@+id/etUsernameLog"
        android:layout_alignLeft="@+id/etUsernameLog"
        android:layout_alignStart="@+id/etUsernameLog"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Password" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:layout_below="@+id/etPasswordLog"
        android:id="@+id/etAgeWel"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignLeft="@+id/etPasswordLog"
        android:layout_alignStart="@+id/etPasswordLog"
        android:hint="Age" />

    <Button
        android:text="Register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etAgeWel"
        android:layout_alignLeft="@+id/etAgeWel"
        android:layout_alignStart="@+id/etAgeWel"
        android:layout_marginTop="21dp"
        android:id="@+id/btnRegister"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

ifconfig output

en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    ether a4:5e:60:c1:9d:6b 
    inet6 fe80::a65e:60ff:fec1:9d6b%en0 prefixlen 64 scopeid 0x4 
    inet 192.168.0.101 netmask 0xffffff00 broadcast 192.168.0.255
    nd6 options=1<PERFORMNUD>
    media: autoselect
    status: active
  • 写回答

1条回答 默认 最新

  • duanlu2935 2017-01-10 11:37
    关注

    Certainly Its an example to show how to achieve(It is an example to show and does not contains exact answer asked by user).Try Networking Lib.("Volley") for calls. I example for Login and Registration.

    //Layout of Activity
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="2dp"
    tools:context="com.test.test.ScreenOne">
    
    
    <EditText
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:id="@+id/etUsername"
        android:layout_marginTop="150dp"
        android:hint="username"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    
    <EditText
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:id="@+id/etPassword"
        android:hint="password"
        android:layout_below="@+id/etUsername"
        android:layout_centerHorizontal="true" />
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/bLogin"
        android:layout_below="@+id/etPassword"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:id="@+id/bSave"
        android:layout_below="@+id/bLogin"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="42dp" />
    </RelativeLayout> 
    

    Activity has 2 buttons and 2 EditText, Login button login via server and Save button saves your data in server:

    package com.test.test;
    
    import android.app.ProgressDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.Window;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import com.android.volley.AuthFailureError;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class ScreenOne extends AppCompatActivity {
    
    private static final String URL_LOGIN = "http://IP_ADDRESS/login.php";
    private static final String URL_SAVE = "http://IP_ADDRESS/save.php";
    private EditText username;
    private EditText password;
    private Button login;
    Button save;
    String name;
    String pass;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_one);
    
        username = (EditText) findViewById(R.id.etUsername);
        password = (EditText) findViewById(R.id.etPassword);
    
        (login = (Button) findViewById(R.id.bLogin)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request();
            }
        });
    
        (save = (Button) findViewById(R.id.bSave)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveRequest();
            }
        });
    }
    
    private void saveRequest() {
        name = username.getText().toString().trim();
        pass = password.getText().toString().trim();
        final ProgressDialog mDialog = new ProgressDialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setMessage("Loading...");
        mDialog.show();
    
        StringRequest request = new StringRequest(Request.Method.POST, URL_SAVE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        mDialog.dismiss();
                        Toast.makeText(ScreenOne.this, response, Toast.LENGTH_LONG).show();
                        username.setText("");
                        password.setText("");
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mDialog.dismiss();
                        Toast.makeText(ScreenOne.this, "Something went wrong", Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> key = new HashMap<>();
                key.put("username", name);
                key.put("password", pass);
                return key;
            }
        };
    
        NetworkCalls.getInstance().addToRequestQueue(request);
    }
    
    private synchronized void request() {
        name = username.getText().toString().trim();
        pass = password.getText().toString().trim();
        final ProgressDialog mDialog = new ProgressDialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialog.setMessage("Loading...");
        mDialog.show();
    
        StringRequest request = new StringRequest(Request.Method.POST, URL_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        mDialog.dismiss();
                        Toast.makeText(ScreenOne.this, response, Toast.LENGTH_LONG).show();
                        username.setText("");
                        password.setText("");
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mDialog.dismiss();
                        Toast.makeText(ScreenOne.this, "Something went wrong", Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> key = new HashMap<>();
                key.put("username", name);
                key.put("password", pass);
                return key;
            }
        };
    
        NetworkCalls.getInstance().addToRequestQueue(request);
     }
    }
    

    Singleton class for Volley request:

    import android.content.Context;
    
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.Volley;
    
    /**
     * Created by W4R10CK on 12-09-2016.
     */
    public class NetworkCalls {
        private RequestQueue requestQueue;
        private static Context context;
    
        private static NetworkCalls ourInstance = new NetworkCalls();
    
        public static NetworkCalls getInstance() {
            return ourInstance;
        }
    
        private NetworkCalls() {
        }
    
        public RequestQueue getRequestQueue(){
            requestQueue = Volley.newRequestQueue(context.getApplicationContext());
            return requestQueue;
        }
    
        public <T> void addToRequestQueue(Request<T> request){
            getRequestQueue().add(request);
        }
    }
    

    API to call server:

     //conn.php for connection (file one)
    <?php
    $host = "localhost";
    $user = "root";
    $pass = "";
    $db_name = "hello";
    
    $con = new mysqli($host,$user,$pass,$db_name);
    
    if($con -> connect_error){
    echo "Connection error";
    }   
    
    
    //save.php(file two)
    <?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    require_once('conn.php');
    
    $sql = "INSERT INTO user (username, password) VALUES ('$username','$password')";
    
    if($con -> query($sql) === TRUE) {
    echo "User added";
    }
    //$con -> close();
    ?>
    ?>
    
    //login.php(file three)
    <?php
    require_once('conn.php');
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $sql = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";
    
    $result = mysqli_query($con,$sql);
    
    if(mysqli_fetch_array($result) == NULL){
    echo "Invalid Cred.";
    }else{
    echo "Success";
    }
    
    $con->close();
    ?>
    

    Lastly create one DB named hello and table in localhost user with 2 fields username, password.

    Try to learn more on this link here

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。