In one of my app, I have a scenario where I need to do some background task. For doing that I am using Async Task. Also I am using custom progress dialog. Below is the layou
If I understand correctly, your TextView
of which you want to set the text can be found in the xml file progressbar.xml (i.e. R.layout.progressbar
). This TextView
can be obtained once the content view has been set (using setContentView()
). In your code you set it before this call is been and the code of mussharapp, he is calling it to early. Namely, he calls it after the setContentView(R.layout.accountsummary)
call which does not contain the TextView
. Consequently, the variable txtView
will be NULL and you will get a NullPointerException
.
What you should do is the following:
onPreExecute
, after setContentView
is called.For the code look down below:
private class InitialSetup extends AsyncTask {
ProgressDialog dialog = new ProgressDialog(getParent(),R.style.progressdialog);
// The variable is moved here, we only need it here while displaying the
// progress dialog.
TextView txtView;
@Override
protected void onPreExecute() {
dialog.show();
dialog.setContentView(R.layout.progressbar);
// Set the variable txtView here, after setContentView on the dialog
// has been called! use dialog.findViewById().
txtView = dialog.findViewById(R.id.progressMessage);
}
@Override
protected Long doInBackground(String... urls) {
// Already suggested by Paresh Mayani:
// Use the runOnUiThread method.
// See his explanation.
runOnUiThread(new Runnable() {
@Override
public void run() {
txtView.setText("Testing");
}
});
fetchDetails();
return 0;
}
@Override
protected void onPostExecute(Long result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
populateUI(getApplicationContext());
}
}