将数据从Android发送到php webservice以验证登录

时间:2013-02-12 18:04:23

标签: android json web-services android-asynctask

我有一个login.php脚本,它将验证在android中输入的用户名和密码。代码在

之下
<?php

    include('dbconnect.php'); 

    $data=file_get_contents('php://input');
    $json = json_decode($data);
    $tablename = "users";

    //username and password sent from android
    $username=$json->{'username'};
    $password=$json->{'password'};

    //protecting mysql injection
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);
    $password = md5($password);

    $sql = "SELECT id FROM $tablename WHERE u_username='$username' and password='$password'"; 

    //Querying the database
    $result=mysql_query($sql);

    //If found, number of rows must be 1
    if((mysql_num_rows($result))==1){

    //creating session
    session_register("$username");
    session_register("$password");

    print "success";
    }else{
    print "Incorrect details";
    }
?>

我还有一个android类,用户将从中输入用户名和密码。代码如下。

  public class LoginActivity extends Activity {


   public static final String loginURI="http://.../login.php";

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



    buttonSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            String userID = "";
            userID=login(editTextUsername.getText().toString(), editTextPassword.getText().toString());

            if (editTextPassword.getText().toString() != null & editTextUsername.getText().toString() != null){
                //Used to move to the Cases Activity
                Intent casesActivity = new Intent(getApplicationContext(), CasesActivity.class);
                startActivity(casesActivity);
                casesActivity.putExtra("username", userID);

            }
            else{
                //Display Toaster for error
                Toast.makeText(getApplicationContext(),"this is an error message", Toast.LENGTH_LONG).show();
            }
        }
    });


private String login(String username, String password){

    JSONObject jsonObject = new JSONObject();

    String success = "";

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(loginURI);
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,10000);
    HttpConnectionParams.setSoTimeout(httpParams,10000);

   try {

        jsonObject.put("username", username);
        Log.i("username", jsonObject.toString());
        jsonObject.put("password", password);
        Log.i("password", jsonObject.toString());

        StringEntity stringEntity = new StringEntity(jsonObject.toString());
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            success = EntityUtils.toString(httpResponse.getEntity());
            Log.i("success", success);
        }

    }catch (IOException e){
        Log.e("Login_Issue", e.toString());
    }catch (JSONException e) {
        e.printStackTrace();  
    }


    return success;
  }

}

我收到以下错误:ERROR / AndroidRuntime(29611):FATAL EXCEPTION:main android.os.NetworkOnMainThreadException。 我知道我需要另一个线程,我正在考虑使用AsyncTask,但我不知道将它放在这个类的哪个位置。

你能否给我一些使用JSON从android发送和接收数据的建议。

感谢您的帮助,

2 个答案:

答案 0 :(得分:2)

您可以通过调用doInBackground中的登录方法使用AsyncTask更改代码,并在登录成功时在onPostExecute上启动下一个活动:

private class LoginOperation extends AsyncTask<String, Void, String> {

String str_username=;
String str_password=;

     public LoginOperation(String str_username,String str_password){
      this.str_password=  str_password;
      this.str_username=  str_username;
     }
     @Override
      protected void onPreExecute() {

       // show progress bar here
      }
      @Override
      protected String doInBackground(String... params) {
           // call login method here
         String userID=login(str_username,str_password);
         return userID;
      }      

      @Override
      protected void onPostExecute(String result) {    
         // start next Activity here
           if(result !=null){
                Intent casesActivity = new Intent(getApplicationContext(),
                                                CasesActivity.class);
                casesActivity.putExtra("username", result);
                Your_Activiy.this.startActivity(casesActivity);

               }
      }

并按下按钮启动LoginOperation AsyncTask:

buttonSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (editTextPassword.getText().toString() != null 
                         & editTextUsername.getText().toString() != null){
                // start AsyncTask here
                 new LoginOperation(editTextUsername.getText().toString(),
                        editTextPassword.getText().toString()).execute("");
            }
            else{
              // your code here
            }
        }
    });

}

答案 1 :(得分:0)

简单的答案是创建一个线程,只调用该线程中的登录或Async任务(您可以将其定义为新类,只需调用execute)。像这样:

旧代码:

userID=login(editTextUsername.getText().toString(), editTextPassword.getText().toString());

新代码:

 Runnable runnable = new Runnable() {
      void run() {
         login(editTextUsername.getText().toString(), editTextPassword.getText().toString());
      }
 (new Thread(runnable)).start();