连接我的mysql数据库和Android应用程序

时间:2016-03-27 19:55:59

标签: php android mysql

我正在关注在youtube上由tonakami TV制作Android登录注册的教程。我遇到了一个问题,即Android应用程序无法通过LOCALHOST XAMPP更新或连接到数据库。

该应用程序运行良好,直到我将注册表信息发送到数据库。一旦我尝试更新我的数据库(注册后),里面就没有新的数据......

ServerRequests.java

public class ServerRequests {

    ProgressDialog progressDialog;
    public static final int CONNECTION_TIMEOUT = 100 * 15;
    public static final String SERVER_ADDRESS = "http://10.0.2.2:8080/";

    public ServerRequests(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Processing");
        progressDialog.setMessage("Please wait...");
    }

    public void storeUserDataInBackground(User user, GetUserCallback userCallback) {
        progressDialog.show();
        new StoreUserDataAsyncTask(user, userCallback).execute();
    }

    public void fetchUserDataInBackground(User user, GetUserCallback callBack) {
        progressDialog.show();
        new fetchUserDataAsyncTask(user, callBack).execute();
    }

    public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void> {

        User user;
        GetUserCallback userCallback;

        public StoreUserDataAsyncTask(User user, GetUserCallback callBack) {
            this.user = user;
            this.userCallback = callBack;
        }

        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("name", user.name));
            dataToSend.add(new BasicNameValuePair("username", user.username));
            dataToSend.add(new BasicNameValuePair("email", user.email));
            dataToSend.add(new BasicNameValuePair("password", user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");

            try{
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                client.execute(post);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            progressDialog.dismiss();
            userCallback.done(null);
            super.onPostExecute(aVoid);
        }
    }

    public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
        User user;
        GetUserCallback userCallback;

        public fetchUserDataAsyncTask(User user, GetUserCallback userCallback) {
            this.user = user;
            this.userCallback = userCallback;
        }

        @Override
        protected User doInBackground(Void... params) {
            ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("username", user.username));
            dataToSend.add(new BasicNameValuePair("password", user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

            User returnedUser = null;

            try{
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                HttpResponse httpResponse = client.execute(post);

                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                JSONObject jObject = new JSONObject(result);

                if(jObject.length() == 0){
                    returnedUser = null;
                } else {
                    String name = jObject.getString("name");
                    String email = jObject.getString("email");

                    returnedUser = new User(name, user.username, email, user.password);

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

            return returnedUser;
        }

        @Override
        protected void onPostExecute(User returnedUser) {
            progressDialog.dismiss();
            userCallback.done(returnedUser);
            super.onPostExecute(returnedUser);
        }
    }
}

Register.php

<?php
    $con=mysqli_connect("10.0.2.2:8080","root","","test");

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

    $statement = mysqli_prepare($con, "INSERT INTO user (name, username, email, password) VALUES (?, ?, ?, ?) ");
    mysqli_stmt_bind_parm($statement, "siss", $id, $name, $username, $email, $password);
    mysqli_stmt_execute($statement);

    mysqli_stmt_close($statement);
    mysqli_close($con);
?>

数据库:

Database

我正在使用android studio模拟器。如果您需要任何进一步的信息或代码,请告诉我们。 Ty为你提供帮助。

1 个答案:

答案 0 :(得分:0)

记下绑定到用户名的数据类型,我不确定您是否将您的用户名用作整数。

见下文我已将其更改为使用&#34; s&#34;

绑定字符串

参考PHP手册,了解如何绑定不同的数据类型。 here

   $mysqli = new mysqli("10.0.2.2", "root", "", "test");
    /**
     * Don't use any port as mysql uses port 3306
     * thats why i have removed 8080, this is used to access phpmyadmin but not mysql that why we are including it from the frontend
     * but not when accessing it from terminal or as in our case on php
     */
    /* check connection */
    if ($mysqli->connect_errno) {
        echo json_encode("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    /* check if server is alive */
    if ($mysqli->ping()) {
        //now lets pass the post to the function register with the POST params
        if (!empty($_POST)) {
            //since we have intialised the class from above
            $query = "INSERT INTO user (name, username, email, password) VALUES (?, ?, ?, ?) ";
            $stmt = $mysqli->prepare($query);
            $stmt->bind_param('s', $_POST['name']);
            $stmt->bind_param('s', $_POST['username']);
            $stmt->bind_param('s', $_POST['email']);
            $stmt->bind_param('s', $_POST['password']);
            $result = $stmt->execute();
            if ($result) {
                echo json_encode('user created successful');
            } else {
                echo json_encode($mysqli->error);
            }
        } else {
            echo json_encode('POST is empty');
        }
    } else {
        echo json_encode("Error: %s\n", $mysqli->error);
    }