2011-11-23 118 views
0

我想創建一個線程來處理登錄按鈕被按下時執行的登錄函數,以便我可以顯示progressDialog。在Android應用程序創建線程結果強制關閉

btnLogin.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      // Check Login 


      ProgressDialog.show(Activity.this, "", "Loading..."); 
      new Thread(new Runnable(){ 
       public void run(){ 
        try{ 
         int duration; 
         Toast toast; 
         Context context; 
         String username = etUsername.getText().toString(); 
         String password = etPassword.getText().toString(); 

         JSONArray jsonArray=null; 
         password=ServerConnection.encryptPassword(password); 
         //Log.i("login hash",password); 
         jsonArray=ServerConnection.login(username, password); 

         if(jsonArray!=null) //login successful 
         { 
          context=getApplicationContext(); 
          duration=Toast.LENGTH_SHORT; 
          toast=Toast.makeText(context, "Login Successful!", duration); 
          toast.show();//Shows the little pop up right at the bottom of the screen 
          Intent i = new Intent(getApplicationContext(), MapWithFriends.class); 
          startActivity(i); 
         } 
         else 
         { 
          context=getApplicationContext(); 
          duration=Toast.LENGTH_SHORT; 
          toast=Toast.makeText(context, "Login Fail", duration); 
          toast.show();//Shows the little pop up right at the bottom of the screen 
          //lblResult.setText("Login failed. Username and/or password doesn't match."); 
         } 
        }catch(Exception e) 
        { 
         Log.e("tag", e.getMessage()); 
        } 
        progressDialog.dismiss(); 
       } 

      }).start(); 


     } 
    }); 

但是,當線程被創建時,它強制關閉。如果我改回沒有線程,它工作正常。

感謝

編輯:
logcat的崩潰:螺紋10
顯示java.lang.NullPointerException:
不能內螺紋已不叫Looper.prepare()
致命異常處理程序創建
..... 你們會需要比這更多嗎?

+0

給我們崩潰的堆棧跟蹤,我們不是魔術師。 :) –

+0

哦,對不起,現在加入! – Dan

回答

4

您不應該修改從任何線程的UI,除了主線程 ,當你在做的: progressDialog.dismiss();

考慮使用HandlerAsyncTask代替。我也建議閱讀this article

+0

其實['dismiss'](http://developer.android.com/reference/android/app/Dialog.html#dismiss%28%29)可以安全地從任何線程運行。但你是對的,這個問題可能在於所有的「Toast」代碼 – Craigy

+0

@Craigy--我沒有意識到這一點。非常感謝你! – MByD

+0

@Craigy,我嘗試評論吐司,仍然強行關閉。謝謝你,雖然 – Dan

2

從非UI線程使用類似

runOnUiThread(new Runnable() { 
    // Your UI modifications here 
}); 

yourUIControl.post(new Runnable() { 
    // something like 
    yourUIControl.setText("new text"); 
}); 
+0

+1爲答案的第二部分。 –