1

I don't need threads, I just want to increment the value of the progress bar manually by clicking a button.

Here's the XML code

<ProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

And in the Java file I have

    ProgressBar pb;

    ...

    pb = (ProgressBar)findViewById(R.id.progressBar1);
    pb.setMax(100);
    pb.setProgress(0);

Now in a method that is called when a button is clicked, I want to increment the progress by one

public void increment(View view) {

    int progress = pb.getProgress();
    pb.setProgress(progress++);

}

This causes the program to crash. How can I control the ProgressBar from the Java program like this?

slybloty
  • 6,346
  • 6
  • 49
  • 70
user1802713
  • 25
  • 1
  • 5
  • 3
    It'd be nice if you'd give your logcat errorlist or your stacktrace. – Joep_H Nov 12 '12 at 13:21
  • What is the error? Where does it crash? – slybloty Nov 12 '12 at 13:24
  • It crashes at pb.setMax(100); with a null pointer exception. – user1802713 Nov 12 '12 at 13:25
  • Have you tried initializing your `ProgressBar pb` first? Something like `ProgressBar pb = new ProgessBar()`. (I believe you can set the max value in the xml file too) – Joep_H Nov 12 '12 at 13:28
  • because it is not found in you view hierarchy. Check that you call setContentView before calling findViewById – njzk2 Nov 12 '12 at 13:29
  • Looks like this line `pb = (ProgressBar)findViewById(R.id.progressBar1);` is assigning null to your `pb`. – slybloty Nov 12 '12 at 13:29
  • Arcshade I have tried that, doesn't fix it. njzk2, how can I get the 'view' parameter for setContentView to set the view hierarchy? – user1802713 Nov 12 '12 at 13:38
  • `myActivity.setContentView(R.layout.my_layout);` You need to set this somewhere at the start of the onCreate method. – Joep_H Nov 12 '12 at 13:39
  • Okay that fixed the first problem - the ProgressBar is displaying correctly, but now I can't access it from the increment() method. I can't call pb.getProgress();. Thanks. – user1802713 Nov 12 '12 at 13:45

1 Answers1

0

2 options:

final ProgressBar pb = (ProgressBar)findViewById(R.id.progressBar1);

or

private ProgressBar pb = null; placed as global variable.

slybloty
  • 6,346
  • 6
  • 49
  • 70
  • You should add the `private`. [In Java, what's the difference between public, default, protected, and private?](http://stackoverflow.com/a/215505/935627) – slybloty Nov 12 '12 at 14:10