登录未验证

时间:2015-04-09 00:16:32

标签: php android mysql

我正在尝试使用社会安全号和密码作为登录参数创建登录页面。我正在使用外部数据库(MySQL)。我从PHP文件获得响应,但是我在检查响应以转到活动时遇到了问题。

这是我的登录类:

package com.ajibola.demola;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;  
import org.apache.http.client.HttpClient;   
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {

private EditText ninum , pass;
private String strniNum,strPass;
private Button login;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;


GetIPAddress getIPaddress = new GetIPAddress();

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




    ninum = (EditText)findViewById(R.id.edtninum);

    pass = (EditText)findViewById(R.id.edtpass);

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

    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            strniNum = ninum.getText().toString();
            strPass = pass.getText().toString();
            if(strniNum.length() == 0 || strPass.length() == 0){
                showToast("Please fill in a National Id and a password");
            }else{
                dialog = ProgressDialog.show(Login.this, "", "Validating user...", true);
                 new Thread(new Runnable() {
                     public void run() {
                         login();                          
                     }
                 }).start(); 
            }
        }


    });


}


private void login() {
    // TODO Auto-generated method stub
    try{            

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost(getIPaddress.getIP()+"check.php"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>(2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
        nameValuePairs.add(new BasicNameValuePair("social_security", ninum.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
        nameValuePairs.add(new BasicNameValuePair("password", pass.getText().toString().trim())); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        response=httpclient.execute(httppost);
        // edited by James from coderzheaven.. from here....
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String responsee = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response); 

        runOnUiThread(new Runnable() {
            public void run() {
                 Toast.makeText(Login.this, "Response from PHP : " + responsee, Toast.LENGTH_SHORT).show();

                 if(responsee.trim().equalsIgnoreCase("lecturer")){
                     runOnUiThread(new Runnable() {
                         public void run() {
                             Toast.makeText(Login.this, "success", Toast.LENGTH_SHORT).show();


                         }
                     });
                     Intent in=new Intent(Login.this, MainActivity.class);
                     startActivity(in);
                     //startActivity(new Intent(Login.this, MainActivity.class));

         //tv.setText();hjg,jhg
                 //Intent in=new Intent(Login.this, MainActivity.class);
                 //startActivity(in);
                dialog.dismiss();   }

                    else{
                        Toast.makeText(Login.this, "failed", Toast.LENGTH_SHORT).show();
                    }
            }
        });




    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }

     /*if(responsee.equals("lecturer")){

          Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();

         Intent in = new Intent(Login.this, Register.class);
         startActivity(in);
     }*/

    }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}

public void signUp(View v){
    Intent in = new Intent(Login.this,Register.class);
    startActivity(in);

}

public void showToast(String msg){
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}

}

这是PHP登录文件

    <?php

 $con = mysql_connect("localhost", "root", "");
if(!$con)
  {
   die('Could not connect: ' .mysql_error());
  }
mysql_select_db("demola", $con);

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

 $query = "select * from users where social_security ='" .$social_security. "'     AND password ='".$password."'";
 $query_exec = mysql_query($query) or die(mysql_error());

 // if and else
 $rows = mysql_num_rows($query_exec);

 if ($rows == 1) {
 echo "lecturer"; 
}
else{
echo "No user was found";

} 

mysql_close($con);

?>

1 个答案:

答案 0 :(得分:1)

你需要在后台通过async执行此代码,然后onPostexecute你可以启动一个新的Activity: 这是一个粗略的例子

public class AsyncTaskTestActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // This starts the AsyncTask
    new MyTask().execute("my string paramater passed in this can be your login credentials");
}

类别:

private class MyTask extends AsyncTask < String,
Integer,
String > {

    // This is run in a background thread
    @Override
    protected String doInBackground(String...passed_in_string) {
        // get the string from params, which is an array (your login stuff)
        //replace your nameValuePairs with this array instead
        String myString = passed_in_string[0];


        httpclient = new DefaultHttpClient();
        httppost = new HttpPost(getIPaddress.getIP() + "check.php"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList < NameValuePair > (2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
        nameValuePairs.add(new BasicNameValuePair("social_security", ninum.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
        nameValuePairs.add(new BasicNameValuePair("password", pass.getText().toString().trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        response = httpclient.execute(httppost);
        // edited by James from coderzheaven.. from here....
        ResponseHandler < String > responseHandler = new BasicResponseHandler();
        final String responsee = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response);

        //then this string is passed to onPostExecute;
        return passed_in_string;

    }


    // This runs in UI when background thread finishes
    @Override
    protected void onPostExecute(String responsee) {
        super.onPostExecute(responsee);
        //login
        if (responsee.trim().equalsIgnoreCase("lecturer")) {
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(Login.this, "success", Toast.LENGTH_SHORT).show();


                }
            });
            Intent in = new Intent(Login.this, MainActivity.class);
            startActivity( in );
        }
    }
}