2013-11-22 134 views
0

我試圖讓應用程序,需要在應用程序中的用戶名和密碼,併發送他們使用http請求到MySQL數據庫,檢查數據庫後,如果用戶存在,我看到一個文本顯示在應用程序「正確的用戶名和密碼」的文本視圖中,如果它不存在,我看到一個文本顯示「不正確的用戶名或密碼」 我看不到正確或不正確我沒有看到任何東西后點擊按鈕登錄在一個AsyncTask中的HTTP請求Android

Logindb類

public class Logindb extends Activity { 
    Button login; 
    EditText u, p; 
    TextView res; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.logindb); 

     login = (Button) findViewById(R.id.login); 
     u = (EditText) findViewById(R.id.u); 
     p = (EditText) findViewById(R.id.p); 
     res = (TextView) findViewById(R.id.res); 
     login.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       new MyAsyncTask().execute(u.getText().toString(), p.getText() 
         .toString()); 
      } 
     }); 
    } 

    private class MyAsyncTask extends AsyncTask<String, Integer, Double> { 
     @Override 
     protected Double doInBackground(String... params) { 
      postData(params[0], params[1]); 
      return null; 
     } 

     protected void onPostExecute(Double result) { 
      Toast.makeText(getApplicationContext(), "command sent", 
        Toast.LENGTH_LONG).show(); 
     } 

     protected void onProgressUpdate(Integer... progress) {} 

     public void postData(String a, String b) { 
      ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
      postParameters.add(new BasicNameValuePair("username", a)); 
      postParameters.add(new BasicNameValuePair("password", b)); 

      String response = null; 
      try { 
       response = CustomHttpClient.executeHttpPost(
         "http://192.168.1.11/new/check.php", postParameters); 
       String result = response.toString(); 
       result = result.replaceAll("\\s+", ""); 
       if (!result.equals("0")) { 
        res.setText("A Correct Username and Password"); 
       } 
       else 
        res.setText("Incorrect Username or Password"); 
      } catch (Exception e) { 
       res.setText(e.toString()); 
      } 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.logindb, menu); 
     return true; 
    } 
} 

PHP文件check.php

 <?php 
    $un=$_POST['username']; 
    $pw=$_POST['password']; 
    //connect to the db 

    $host="localhost"; // Host name 
    $user="root"; // Mysql username 
    $pswd="123"; // Mysql password 
    $db="pet_home"; // Database name 
    $tbl_name="users"; // Table name 

    $conn = mysql_connect($host, $user, $pswd); 
    mysql_select_db($db, $conn); 
    //run the query to search for the username and password the match 
     $query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'"; 

$result = mysql_query($query) or die("Unable to verify user because : ".mysql_error()); 
//this is where the actual verification happens 
if(mysql_num_rows($result) > 0) 
echo mysql_result($result,0); // for correct login response 
else 
echo 0; // for incorrect login response 
?> 

logindb.xml `

 <EditText 
    android:id="@+id/u" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="56dp" 
    android:ems="10" /> 

     <EditText 
    android:id="@+id/p" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/u" 
    android:layout_below="@+id/u" 
    android:layout_marginTop="22dp" 
    android:ems="10" 
    android:inputType="textPassword" /> 

    <Button 
    android:id="@+id/login" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/p" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="67dp" 
    android:text="Login" /> 

    <TextView 
    android:id="@+id/res" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/login" 
    android:layout_below="@+id/p" 
    android:layout_marginTop="27dp" 
    android:text="OK" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:textColor="@android:color/black" /> 

    </RelativeLayout>` 

回答

1

我很驚訝這個工作根本不會崩潰,你試圖從doInBackground訪問UI(通過調用postData中的res.setText),這是不可能的。您應該在doInBackground中返回一個布爾值,並據此在onPostExecute中相應地更改TextView。

使用這個作爲類定義:

private class MyAsyncTask extends AsyncTask<String, Integer, Boolean> 

然後在公共布爾 POSTDATA的端部(字符串一個,串B):

return result.equals("0") 

和在doInBackground:

boolean success = postData(params[0],params[1]); 
return success; 

and finally

protected void onPostExecute(Boolean result){ 
    // change the text for your TextViews here according to the Boolean result 
    if (result){ 
     res.setText("A Correct Username and Password"); 
    }else{ 
     res.setText("Incorrect Username or Password"); 
    } 
    Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show(); 
} 
2

,因爲你在doInBackground修改您的TextView它不工作。你所有的視覺修改已在您的onPostExecute 被稱爲所以在這裏,你需要做的是從postData返回字符串結果,並在onPostExecute移動下面的代碼:

if (!result.equals("0")) { 
    // Intent in = new Intent(Logindb.this, Welcome.class); 
    // LoadPreferences(); 
    res.setText("A Correct Username and Password"); 
    //startActivity(in); 
    } 
    else 
    res.setText("Incorrect Username or Password"); 
1

當您進行任何類型的網絡操作時,您必須使用thread/asynctask來完成此操作。另一方面,當您必須訪問或修改任何UI元素時,您必須在MainThread(UIThread)中執行此操作。 現在你在做的是從不是UIThread的線程內調用res.setText()。 AsyncTask由幾個方法組成,其中一些方法在UIThread中運行,如onPostExecute,onProgressUpdate ..但doInBackground不在UIThread中運行,這就是爲什麼你面臨這個問題。

爲了解決您的問題,您現在可以按照其他的答案,因爲他們建議實際應該如何處理這個問題。在這種情況下,您必須調整您的代碼才能像這樣工作。

另外還有一種方法可以解決您的問題,但可悲的是它消除了使用asynctask的必要性,因爲您沒有使用AsyncTask的任何優勢,您可以使用Thread來代替。

當您對postData(params [0],params [1])中的任何UI元素進行任何修改時,請使用runOnUiThread。

像這樣:

runOnUiThread(new Runnable() { 

        public void run() { 
         // TODO Auto-generated method stub 
         // do what you have to do 
        res.setText("A Correct Username and Password"); 
        } 
      }); 

嘗試這種方式它應該工作。