php - Android中通过PHP和Mysql登录

标签 php android mysql

我正在开发一个需要用户登录才能进行下一个进程的 Android 应用程序。在我的应用程序中,它匹配 username 和 password 。通过 PHP,它检查需求并给出成功或失败作为 toast 。但它不会在成功后转到下一个 Activity ,因为 onPostExecute 中的字符串变量没有从 PHP 脚本中获得任何值(成功或失败)。 请为我提供上述问题的解决方案。

我的 Java 代码是:

public class login extends AppCompatActivity implements View.OnClickListener{

    public static final String USER_NAME = "USER_NAME";

    public static final String PASSWORD = "PASSWORD";

    private static final String LOGIN_URL = "http://knitstudents.dx.am/login11.php";

    private EditText editTextUserName;
    private EditText editTextPassword;
    Button buttonRegister;
    private Button buttonLogin;

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

        editTextUserName = (EditText) findViewById(R.id.editTextUserName);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonLogin = (Button) findViewById(R.id.login);

        buttonLogin.setOnClickListener(this);
        buttonRegister= (Button) findViewById(R.id.buttonRegister);
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myintent2 = new Intent(login.this,register.class);
                startActivity(myintent2);
            }
        });
    }


    private void userlogin(){
        String username = editTextUserName.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        userLogin(username,password);
    }

    private void userLogin(final String username, final String password){
        class UserLoginClass extends AsyncTask<String,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(login.this,"Please Wait",null,true,true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if(s.equalsIgnoreCase("success")){
                    Intent intent = new Intent(login.this,Welcome.class);
                    intent.putExtra(USER_NAME,username);
                    startActivity(intent);
                }else{
                    Toast.makeText(login.this,s,Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected String doInBackground(String... params) {
                HashMap<String,String> data = new HashMap<>();
                data.put("username",params[0]);
                data.put("password",params[1]);

                RegisterUserClass ruc = new RegisterUserClass();

                String result = ruc.sendPostRequest(LOGIN_URL,data);

                return result;
            }
        }
        UserLoginClass ulc = new UserLoginClass();
        ulc.execute(username,password);
    }

    @Override
    public void onClick(View v) {
        if(v == buttonLogin){
            userlogin();
        }
    }
}

login11.php 是--

<?php


require "index111.php";

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

$sql = "select * from users_information where username='$username' and password='$password'";

$res = mysqli_query($conn,$sql);

$check = mysqli_fetch_array($res);

if(isset($check)){
echo 'success';
}else{
echo 'failure';
}

mysqli_close($conn);

?>

RegisterUserClass (sendPostRequest 和 getPostDataString):

    public class RegisterUserClass {

    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                response = br.readLine();
            }
            else {
                response="Error Registering";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

最佳答案

检查您的 API。数据获取可能存在一些问题。你的代码是正确的会有其他问题。

关于php - Android中通过PHP和Mysql登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793928/

相关文章:

mysql - 搜索替换字符(无 TSQL)

MySQL根据一个id从多个表中选择数据

php - 检查用户是否在页面上

php遍历数组中的对象数组

java - Android Studio 中基本音乐播放器中的音频问题

php函数从随机数返回相同的结果

php - 数据库 - 查询以检索其他表中不存在的行

javascript - 如何将候选人 ID 数组发送到候选人表的不同行?

android - 如何在android中设置ListView选中的item alternet文本颜色

android - 在 ViewPager 中更改 ImageView Drawable