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

时间:2017-01-10 11:05:20

标签: php android registration

我是android的新手,并试图学习开发一个简单的注册表单。我按照youtube教程进行了操作,github中提供了相同的代码 我在我的机器上使用本地安装的php-mysql。因此,对于url的路径 - 注册请求和登录请求,我使用以下URL:

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

当我在本地浏览器中使用以下命令运行这些文件时:

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

它不会返回任何错误。

寄存器和登录php文件中的连接如下:

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

提供用户名和密码的应用程序应该打开第三页,或者当我使用注册页面注册时,应该更新数据库并返回登录页面。

问题是:

应用程序在本地运行VM而没有任何错误,但是在输入详细信息并单击登录或注册按钮后,我看不到任何操作或没有错误消息。我尝试按以下方式更改网址:

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

并且在php文件而不是localhost中我已经使用了所有这些以及它们的各种组合。

过去3天我一直在努力解决这个问题,但无济于事。我是否必须使用jsonparser - 我在某处看到了类似的选项。

我在云上托管的Mysql中配置了一个表,并使用了云凭据,仍然无法正常工作。有什么想法吗?

应用程序清单

<?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输出

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 个答案:

答案 0 :(得分:0)

当然它是一个展示如何实现的例子(这是一个展示的例子,并不包含用户提出的确切答案)。试试网络图书馆(&#34; Volley&#34;)进行通话。我登录和注册的例子。

//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有2个按钮和2个EditText,登录按钮通过服务器登录,Save按钮将数据保存在服务器中:

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);
 }
}

Volley请求的Singleton类:

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:

 //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();
?>

最后在localhost 用户中创建一个名为 hello 的数据库,其中包含2个字段用户名密码。< / p>

尝试在此链接here

上了解详情
相关问题