Reputation: 379
I have two class. class A is activity where my progress bar will be use. and class B is no-activity where my progress bar will be update. but when i calling progress bar from non-activity class B . i got null pointer exception.
class A:-
ProgressBar progressBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);}
class B:-
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
((Activity) cnt).runOnUiThread(new Runnable() {
public void run() {
XMPPClient xc = new XMPPClient();
xc.progressBar = new ProgressBar(cnt);
xc.progressBar.setProgress(progressStatus);
// Toast.makeText(cnt, "ok", Toast.LENGTH_SHORT).show();
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
when i added this line :- xc.progressBar = new ProgressBar(cnt);
then i did not get nullpointerexception. But now my progress bar is **not updating.**
please any one help me.
Upvotes: 1
Views: 1577
Reputation: 759
in ClassA :-
ProgressBar progressBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
////Then Use the Reference on Progressbar
ClassB classb = new ClassB(this, progressBar);
}
Then in ClassB :-
public class ClassB{
private Context cnt;
private ProgressBar progressBar;
public ClassB(Context context, ProgressBar pBar){
cnt = context;
progressBar = pBar;
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
((Activity) cnt).runOnUiThread(new Runnable() {
public void run() {
XMPPClient xc = new XMPPClient();
xc.progressBar = new ProgressBar(cnt);
xc.progressBar.setProgress(progressStatus);
// Toast.makeText(cnt, "ok", Toast.LENGTH_SHORT).show();
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
}
Upvotes: 0
Reputation: 22064
ProgressBar progressBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
ClassB classb = new ClassB(this, progressBar);
}
public class ClassB{
private Context cnt;
private ProgressBar progressBar;
public ClassB(Context context, ProgressBar pBar){
cnt = context;
progressBar = pBar;
}
}
Now you can use progressBar instead of creating a new one like you did in previous code! Just a quick overview...
Upvotes: 4