如何从XAMPP数据库获取Android Studio

时间:2017-03-07 13:01:54

标签: java php android

我正在创建一个包含登录和注册页面的Android应用。有人登录后,他们可以执行应用程序提供的不同测试。如何将他们的结果与他们的用户ID一起存储在XAMPP数据库中?我提供了login.php,LoginActivity.java,User.java和EditProfile.java代码。我提供了一个示例,其中有人可能想要编辑他们的个人资料,当他们想要保存更改时,应该使用他们的用户ID进行保存。我正在努力奋斗。非常感谢任何帮助,谢谢

的login.php

<?php
    $error = NULL;

    include_once('connection.php');
        if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
        $username = $_POST['txtUsername'];
        $password = $_POST['txtPassword'];

        $query = "SELECT * FROM user WHERE username = '$username' AND password = '$password'";

        $result = mysqli_query($conn, $query);

        if($username == $error || $password == $error) {
            echo "Login Failed <br>";
        }
        else if($result->num_rows > 0){
            if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
                echo "success";
                exit;
            }
            echo "Login Successful";
        }
        else{
            echo "Login Failed <br>";
        }
    }
?>


<html>
<head>
    <title>Login</title>
</head>
<body>
<h1>Login </h1>
<form action="<?PHP $_PHP_SELF ?>" method="post">
    Username <input type="text" name="txtUsername" value="" /> <br/>
    Password <input type="password" name="txtPassword" value=""/><br/>
    <input type="submit" name="btnSubmit" value="Login"/> </form>
</body>
</html>

LoginActivity.java

package com.delta.object.newandroidproject;

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

import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;

import java.util.HashMap;

public class LoginActivity extends AppCompatActivity implements       AsyncResponse, View.OnClickListener {

    EditText etUsername, etPassword;
    Button loginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.login_toolbar);
        setSupportActionBar(mToolbar);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        loginBtn = (Button) findViewById(R.id.email_login_button);
        loginBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        HashMap postData = new HashMap();
        postData.put("mobile", "android");
        postData.put("txtUsername", etUsername.getText().toString());
        postData.put("txtPassword", etPassword.getText().toString());

        PostResponseAsyncTask task = new PostResponseAsyncTask(this, postData);
        task.execute("http://10.0.3.2/androidproject/login.php");

    }

    @Override
    public void processFinish(String result) {
        if (result.equals("success")) {
            Intent i = new Intent(this, TestActivity.class);
            startActivity(i);
        }
        else{
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }

    }

    public void registerClick(View view) {
        Intent i = new Intent(LoginActivity.this, SignUpActivity.class);
        startActivity(i);
    }
}

user.php的

package com.delta.object.newandroidproject;

import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("user_id")
    public int user_id;

    @SerializedName("name")
    public String name;

    @SerializedName("gender")
    public String gender;

    @SerializedName("username")
    public String username;

    @SerializedName("password")
    public String password;
 }

EditProfile.java

package com.delta.object.newandroidproject;

import android.content.Intent;

import java.util.ArrayList;
import java.util.HashMap;


public class EditProfile extends AppCompatActivity {

    EditText etName, etPassword, etUsername;
    Button submitBtn;
    RadioGroup rg;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_profile);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.edit_profile_toolbar);
        setSupportActionBar(mToolbar);
    }

    public void editProfileSave(View view) {
        Intent i = new Intent(EditProfile.this, TestActivity.class);
        startActivity(i);
    }

    public void cancelClick(View view) {
        Intent i = new Intent(EditProfile.this, TestActivity.class);
        startActivity(i);
    }
}

1 个答案:

答案 0 :(得分:0)

我想在此分享一些关于如何在项目中解决问题的经验

首先,为了让我从数据库中获取用户ID,我将使用JSON解析来自login.php的userID值。

这是login.php的样子,阅读代码的注释

 login.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['email']) && isset($_POST['password'])) {

    // receiving the post params
    $email = $_POST['email'];
    $password = $_POST['password'];

    // get the user by email and password
    $user = $db->getUserByEmailAndPassword($email, $password);

    if ($user != false) {
        // user is found
        //so reading all the database record 

        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"]; //here is the user ID,will fetch along
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";

        echo json_encode($response); //encode this to JSON,so later on can be use in Android code
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters email or password is missing!";
    echo json_encode($response);
}
?>

现在,您可以在processFinsh()

中获取UserID
@Override
        public void processFinish(JSONArray jarray) {
            // TODO Auto-generated method stub
            try{
            JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {
                    // user successfully logged in


                    // Get your user ID here and other details
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    //Here you can set your userId to the global value,so you can use it in your EditProfile.java
                   User userId = (User)getApplicationContext();
                    userId.setUserId(uid);

                    // Launch main activity
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();

                 }
                catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

在您的User.java中,创建一个getter和setter来存储您的用户ID

        private String userId;

        public String getUserId(){
            return userId;
        }

        public void setUserId(String user_id){
            this.userId = user_id;
        }

我不知道您要在哪里使用您的用户ID,但无论何时您想使用它,您都可以这样打电话

//Get your userId
    User userId = (User)getApplicationContext();
    String userId=   userId.getUserId(); 
    Log.d("userId",userId) // log to the android monitor to see whether is the value you want or not

为了让您有一些基本的概念来使用json编码,您可以查看以下链接

How to connect Android with PHP, MySQL for Basic CRUD

Android Login and Registration with PHP, MySQL and SQLite