I am a new programmer. I have seen lots of tutorials but can\'t understand what is wrong. I am trying to create a ProgressBar from an Async Task. However it always crashes m
Intervals.getApp().progressBar.setProgress(values[0]);
There are two possibilities for the NullPointerException
in this line of code:
getApp()
returns null
progressBar
is null
In order to determine which is the cause, you need to split this into two separate lines:
Intervals intervals = Intervales.getApp();
intervals.progressBar.setProgress(values[0]);
Now set a breakpoint at the first line, step over it, and determine if intervals
is null
or not.
progressBar is a local variable while you are referring to the same-named variable of a different class-object (in your case, the app object). you have probably mixed them up.
I think it's better if you pass the progress bar as an argument to the AsyncTask
:
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.Progressbar);
progressBar.setProgress(0);
// Play Methods
final ImageButton Play = (ImageButton) findViewById(R.id.Play);
Play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AsyncTaskBar task = new AsyncTaskBar();
task.setProgressBar(progressBar);
task.execute();
}
And then on your AsyncTask
declare the setProgressBar
method:
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
ProgressBar bar;
public void setProgressBar(ProgressBar bar) {
this.bar = bar;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (this.bar != null) {
bar.setProgress(values[0]);
}
}
You could do the same with the TextView
you're trying to set.
In any case, since you mentioned you're new at this you may want to take a look at the Broadcast/Receiver pattern. Here's how it goes:
BroadcastReceiver
, instantiate one in your activity and register/unregister it accordingly.Sounds a bit overwhelming? It is at first, but here are the benefits: