Android doInBackground任务没有运行...但是执行前运行

时间:2017-08-07 08:04:04

标签: php android mysql

我正在运行一个与mysql连接的Android应用程序,我使用php文件登录并注册用户,我已经向数据库添加了数据,我正在尝试使用这些详细信息登录。

我有一个名为Background worker的不同类来执行asynctask。 doInBackground任务不会运行,但预执行任务在应用程序中运行。

这些是php中的登录和注册文件,存储在本地主机...

<?php
require "conn.php";
$user_name = "user_name";
$user_pass = "password";
$mysql_query = "select * from users where Email like '$user_name' and Password like '$user_pass'";
$result = mysqli_query($conn, $mysql_query);
if(mysqli_num_rows($result) > 0){
    echo "login success";
}
else {
    echo "login not success";
}
?>

Register.php

<?php
require "conn.php";
$name = "name";
$user_name = "user_name";
$user_pass = "password";
$cpass = "cpass";
$mysql_query = "insert into users (Name,Email,Password,ConfirmPass) values ('$name','$user_name','$user_pass','$cpass')";
if($conn->query($mysql_query) === TRUE){
    echo "You have successfully registered!";
}
else {
    echo "Register failed";
}
$conn->close();
?>

这是我在android中的Login.java页面:

package com.example.user.smartkitchen;

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

public class Login extends AppCompatActivity {

    public Button login,loginResetPass,RegisterLinkButton;
    EditText UserNameTxt, PasswordTxt;
    //private FirebaseAuth auth;
    public static final String Email = "Email";
    public ImageButton exit;
    //private ProgressBar progressBar;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /*auth = FirebaseAuth.getInstance();

        if (auth.getCurrentUser() != null) {
            startActivity(new Intent(Login.this, MainActivity.class));
            finish();
        }
        */
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        UserNameTxt = (EditText) findViewById(R.id.UserNameTxt);
        PasswordTxt = (EditText) findViewById(R.id.PasswordTxt);
        //progressBar = (ProgressBar) findViewById(R.id.progressBar);
        login = (Button) findViewById(R.id.login);

        RegisterLinkButton = (Button) findViewById(R.id.RegisterLinkButton);
        RegisterLinkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, Register.class));
            }
        });


    }

    public void onLogin(View view) {
        String username = UserNameTxt.getText().toString();
        String password = PasswordTxt.getText().toString();
        String type = "login";
        BackgroundWorker backgroundWorker = new BackgroundWorker(this);
        backgroundWorker.execute(type,username,password);
    }

       /* loginResetPass = (Button) findViewById(R.id.loginResetPass);



        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();




        loginResetPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, forgotPassword.class));
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String email = UserNameTxt.getText().toString();
                final String password = PasswordTxt.getText().toString();
                String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (email.matches(emailPattern))
                {
                    Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                //progressBar.setVisibility(View.VISIBLE);

                //authenticate user
                auth.signInWithEmailAndPassword(email, password)
                        .addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                //progressBar.setVisibility(View.GONE);
                                if (!task.isSuccessful()) {
                                    // there was an error
                                    if (password.length() < 6) {
                                        PasswordTxt.setError(getString(R.string.minimum_password));
                                    } else {
                                        Toast.makeText(Login.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                                    }
                                } else {
                                    Intent intent = new Intent(Login.this, Home.class);
                                    intent.putExtra("Email", email);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        });
            }
        });

    }

    public void onExitTapped(View view) {

        exit = (ImageButton) findViewById(R.id.exit);
        finish();
    }
*/

}

这是我的后台工作者班:

package com.example.user.smartkitchen;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by User on 8/6/2017.
 */

public class BackgroundWorker extends AsyncTask<String,Void,String> {

    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_URL = "http://192.168.1.7/login.php";
        String register_URL = "http://192.168.1.7/register.php";
        if(type.equals("login")){
            try {
                String user_name = params[1];
                String password = params[2];
                URL url = new URL(login_URL);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8")+"&"+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String result="";
                String line="";
                while ((line = bufferedReader.readLine())!=null){
                    result +=line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if(type.equals("register")){
            try {
                String name = params[1];
                String user_name = params[2];
                String password = params[3];
                String cpass = params[4];
                URL url = new URL(register_URL);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data1 = URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(name, "UTF-8")+"&" +
                URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8")+"&" +
                URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8")+"&"
                        +URLEncoder.encode("cpass", "UTF-8")+"="+URLEncoder.encode(cpass, "UTF-8");
                bufferedWriter.write(post_data1);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String result="";
                String line="";
                while ((line = bufferedReader.readLine())!=null){
                    result +=line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

}

我获得了标题集的警告对话框,但是没有出现成功消息,php页面没有运行?有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您正在http中使用POST,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tabs">
  <li class="tab" draggable="true"><span>1</span></li>
  <li class="tab" draggable="true"><span>2</span></li>
  <li class="tab" draggable="true"><span>3</span></li>
  <li class="tab" draggable="true"><span>4</span></li>
  <li class="tab" draggable="true"><span>5</span></li>
</ul>