0

我有一个 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 的数据方面给我一些建议。

感谢您的帮助,

4

2 回答 2

2

您可以通过调用内部登录方法来使用 AsyncTask 更改代码, 并在登录成功时doInBackground启动下一个活动: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
            }
        }
    });

}
于 2013-02-12T18:20:34.790 回答
0

简单的答案是创建一个线程并仅在该线程中调用登录,或异步任务(您可以将其定义为一个新类,然后调用执行)。像这样:

旧代码:

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();
于 2013-02-12T18:20:41.927 回答