我正在尝试创建一个线程来处理按下登录按钮时执行的登录函数,以便我可以显示进度对话框。
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
……
你们还需要更多吗?
最佳答案
除了主线程之外,您不应该从任何线程修改UI,就像在:progressDialog.dismiss();
考虑使用Handler或AsyncTask反而。我还建议阅读 this article .
关于java - 创建线程会导致 Android 应用程序强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249613/