Murdok Murdok - 7 days ago 4
Android Question

Android Studio: Progress Bar without thread or multiprocessing

Hi everyone this is my first post on stackoverflow, I have a very specific question about Android Studio. I would like to implement a method that allows me to start a Progressbar-wait several seconds before it is finished-and end it.

I would like to create this method without using threads or MultiProcessing.

I'm not a real expert in java and I can't figure out why my method doesn't work/doesn't compile!

This is the code of method:

public void RunProgressBar(){
int counter = 0;
while(counter < progressBar.getMax()){
progressBar.setProgress(counter);
SystemClock.sleep(200);
counter++;
}
}


The method is used in:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.RunProgressBar();
}


In case I also added all the code of the MainActivity

package com.xedoll.green_player;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.RunProgressBar();
}

public void RunProgressBar(){
int counter = 0;
while(counter < progressBar.getMax()){
progressBar.setProgress(counter);
SystemClock.sleep(200);
counter++;
}
}
}

Answer

Just a quick comment - in Java, methods start with lowercase letters, this means that your method RunProgressBar() should be named runProgressBar(). This is a convention and following them normally makes code more readable.

The problem here is that you are trying to call RunProgressBar() on an instance of a ProgressBar. Your custom method RunProgressBar() belongs to the MainActivity class. This means that the line progressBar.RunProgressBar() should be changed to RunProgressBar(), or this.RunProgressBar().

The second issue I see is that you are implementing View.OnClickListener, but you don't @Override the method public void onClick(View v).

After sorting this the code should compile.

Comments