我正在尝试创建一个线程来处理按下登录按钮时执行的登录功能,这样我就可以显示progressDialog。
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:
无法在未调用Looper.prepare()的线程内创建处理程序
致命异常:Thread-10
java.lang.NullPointerException
.....
你们需要更多吗?
答案 0 :(得分:4)
您不应该修改除主线程之外的任何线程的UI,如下所示: progressDialog.dismiss();
请考虑使用Handler或AsyncTask。我还建议阅读this article。
答案 1 :(得分:2)
从非UI线程使用类似
的内容runOnUiThread(new Runnable() {
// Your UI modifications here
});
或
yourUIControl.post(new Runnable() {
// something like
yourUIControl.setText("new text");
});