在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()
致命异常处理程序创建
..... 你们会需要比这更多吗?
答
您不应该修改从任何线程的UI,除了主线程
,当你在做的:
progressDialog.dismiss();
考虑使用Handler或AsyncTask代替。我也建议阅读this article。
答
从非UI线程使用类似
runOnUiThread(new Runnable() {
// Your UI modifications here
});
或
yourUIControl.post(new Runnable() {
// something like
yourUIControl.setText("new text");
});
+0
+1为答案的第二部分。 –
给我们崩溃的堆栈跟踪,我们不是魔术师。 :) –
哦,对不起,现在加入! – Dan