在Android应用程序创建线程结果强制关闭

问题描述:

我想创建一个线程来处理登录按钮被按下时执行的登录函数,以便我可以显示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

您不应该修改从任何线程的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

从非UI线程使用类似

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

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

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