使用android studio和000webhost将MySQL数据库连接到Android应用程序

时间:2016-08-07 17:22:53

标签: java android mysql android-studio authentication

我正在尝试为Android应用程序构建用户数据库,我正在按照Tonikami(https://www.youtube.com/watch?v=QxffHgiJ64M&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka)制作的教程。我相信我已经复制了他的代码,但我仍然无法将数据从应用程序传递到数据库。

这是我的注册活动:

    package com.example.jerem.myapplication;

    import android.content.Intent;
    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 com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.toolbox.Volley;

    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 etName = (EditText) findViewById(R.id.etName);
            final EditText etUsername = (EditText) findViewById(R.id.etUsername);
            final EditText etPassword = (EditText) findViewById(R.id.etPassword);
            final EditText etAge = (EditText) findViewById(R.id.etAge);
            final Button buttonRegister = (Button) findViewById(R.id.buttonRegister);

            buttonRegister.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    final String name = etName.getText().toString();
                    final String username = etUsername.getText().toString();
                    final int age = Integer.parseInt(etAge.getText().toString());
                    final String password = etPassword.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("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                                }

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

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

这是我的RegisterRequest活动:

    package com.example.jerem.myapplication;

    import com.android.volley.Response;
    import com.android.volley.toolbox.StringRequest;

    import java.util.HashMap;
    import java.util.Map;


    public class RegisterRequest extends StringRequest{

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

        public RegisterRequest(String name, String username, int age, String password, Response.Listener<String> listener){

            super(Method.POST, REGISTER_REQUEST_URL, listener, null);
            params = new HashMap<>();
            params.put("name", name);
            params.put("age", age + "");
            params.put("username", username);
            params.put("password", password);

        }

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

这是我的android清单:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.example.jerem.myapplication">

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

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/Theme.AppCompat.Light">
            <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=".UserAreaActivity"></activity>
        </application>

     </manifest>

这是我运行应用程序并输入新用户时的LOGCAT图片:

LOGCAT

这是我收到的LOGCAT例外:

    08-09 10:54:55.124 2896-2896/com.example.jerem.myapplication E/MYAPP: unexpected JSON exception
                                                                   org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
                                                                      at org.json.JSON.typeMismatch(JSON.java:111)
                                                                      at org.json.JSONObject.<init>(JSONObject.java:160)
                                                                      at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                      at com.example.jerem.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:44)
                                                                      at com.example.jerem.myapplication.RegisterActivity$1$1.onResponse(RegisterActivity.java:40)
                                                                      at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                      at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                      at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                      at android.os.Handler.handleCallback(Handler.java:739)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    08-09 10:55:13.211 2896-2937/com.example.jerem.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa9f4f2a0

这是我的PHP文件&#34; login.php&#34;:

    <?php
        $con = mysqli_connect("server38.000webhost.com", "a4434902_admin", "1234abcd", "a4434902_users");

        $username = $_POST["username"];
        $password = $_POST["password"];

        $statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
        mysqli_stmt_bind_param($statement, "ss", $username, $password);
        mysqli_stmt_execute($statement);

        mysqli_stmt_store_result($statement);
        mysqli_stmt_bind_result($statement, $userID, $name, $age, $username, $password);

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

        while(mysqli_stmt_fetch($statement)){
            $response["success"] = true;  
            $response["name"] = $name;
            $response["age"] = $age;
            $response["username"] = $username;
            $response["password"] = $password;
        }

        echo json_encode($response);
    ?>

这是我的PHP文件,名为&#39; register.php&#39;:

    <?php
        $con = mysqli_connect("server38.000webhost.com", "a4434902_admin", "1234abcd", "a4434902_users");

        $name = $_POST["name"];
        $age = $_POST["age"];
        $username = $_POST["username"];
        $password = $_POST["password"];
        $statement = mysqli_prepare($con, "INSERT INTO user (name, username, age, password) VALUES (?, ?, ?, ?)");
        mysqli_stmt_bind_param($statement, "ssis", $name, $username, $age, $password);
        mysqli_stmt_execute($statement);

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

        echo json_encode($response);
    ?>

0 个答案:

没有答案