Wednesday 25 December 2019

how to use doInBackground in android for show error msg



Hello i am using AsyncTask for webservice calling. Its working fine when i enter correct username and password, when i enter wrong then its how msg wrong username and password but in my code in doInBackground area its throw expction or application crass
private class LoginTask extends AsyncTask {



    private final ProgressDialog dialog = new ProgressDialog(login.this); 

protected void onPreExecute() {


this.dialog.setMessage("Logging in...");
this.dialog.show();
}


protected Void doInBackground(final Void... unused) {
String auth=calllogin(Username,Passowrd);
cls_constant.userid=auth;
if(auth.equals("0"))
{


TextView errorTextview=(TextView)findViewById(R.id.tv_error);
errorTextview.setText("Username & Password incorrect.");
}
else {

Intent intnt=new Intent(getBaseContext(), aftersignin.class);
startActivity(intnt);
}
return null; // don't interact with the ui!

}


protected void onPostExecute(Void result)
{

if (this.dialog.isShowing())
{
this.dialog.dismiss();
}



}


i want ot show error mgs like this but i dont know whats i m doing wrong
or how to use onPostExecute for show msg
thanks


Answer



You cant update TextView on a different thread (since Asyn does job in a new thread) since it belongs to UI thread. So fix your doInBackground as below:




protected Void doInBackground(final Void... unused) { 
String auth=calllogin(Username,Passowrd);
cls_constant.userid=auth;
if(auth.equals("0"))
{
YourActivityClass.this.runOnUiThread(new Runnable() {
@Override
public void run() {
TextView errorTextview=(TextView)findViewById(R.id.tv_error);

errorTextview.setText("Username & Password incorrect.");
}
});
}
else {

Intent intnt=new Intent(getBaseContext(), aftersignin.class);
startActivity(intnt);
}
return null; // don't interact with the ui!

}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...