I am trying to create a thread to handle a login function that is executed when the login button is pushed, so that I can show a 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();
}
});
However when the thread is created, it force closes. If I change back to no threads, it works fine.
Thanks
Edit:
LogCat of crash:
Can’t create handler inside thread that has not called Looper.prepare()
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
…..
would you guys need more than this?
You shouldn’t modify the UI from any thread except the main thread
, as you do in:progressDialog.dismiss();Consider using Handler or AsyncTask instead. And I would also recommend reading this article.