2017-08-07 51 views
-1

我正在运行一个Android应用程序连接与MySQL,我使用PHP文件登录和注册用户,我已经添加到数据库的数据,我是试图使用这些细节进行登录。Android doInBackground任务没有运行...但预执行运行

我有一个名为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._-][email protected][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页面不运行?有人可以帮助吗?

+0

你可以把一些日志和调试指针来检查时,代码被切换到后台方法会发生什么。它是否甚至没有进入第一线或停止在别的地方? –

+0

如果警报栏显示它意味着onPostExecute()正在工作,也doInBackground()。因为你有调用alertDialog.show(); onPostExecute()中的 –

回答

0

您在使用HTTP POST,

so in php you should use : 

if(isset($_POST['user_name'])) 
{ 
$user_name=$_POST['user_name']; 
$password=$_POST['password']; 
} 

Hope it works 
相关问题