Creating a progress bar for android - java

Hi I am new to threading in general and I am trying to set up a progress bar that increments itself every half-second up to 100 using the sleep method. I have been having trouble using a lot of the syntax I have found on line and when I launch this program it does not display a progress bar but instead displays a spinning loading icon. This is what I have:
public class main extends ActionBarActivity {
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(1);
startPb();
}
});
}
private void startPb(){
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setIndeterminate(false);
pb.setProgress(0);
new Thread(new Runnable(){
public void run(){
for (int i = 0; i <= 100; i++)
try {
Thread.sleep(500);
pb.setProgress(i);
System.out.println(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
pb.post(new Runnable() {
public void run() {
pb.incrementProgressBy(1);
}
});
}
}).start();
}
I have a feeling I am not implementing the progress bar properly in the above code.
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Counter"
android:id="#+id/counter"
tools:ignore="InvalidId">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="startButton"
android:id="#+id/startbutton"
android:layout_centerHorizontal="true" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#+id/startbutton"
android:layout_centerHorizontal="true" />
</RelativeLayout>

A spinning progress bar is an indeterminate progress bar. To use an actual progress bar you will want to call:
pb.setIndeterminate(false);
The progress bar style was also an issue. Here is a good reference explaining progress bar style types.
What's the meaning of android:progressBarStyle attribute in ProgressBar?

Related

Countdown progress bar in Android Studio

I'm trying to make a countdown timer in form of a progress bar, and that's what i tried so far: but it don't work at all.
Layout XML File:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context=".thetest">
<ProgressBar
android:id="#+id/progressBarToday"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="79dp"
android:layout_height="101dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:max="30"
android:progress="29"
android:progressDrawable="#drawable/circular_progress_bar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Java:
public class thetest extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thetest);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBarToday);
Animation an = new RotateAnimation(0.0f, 90.0f, 250f, 273f);
an.setFillAfter(true);
pb.startAnimation(an);
}
}
And finally the drawable style file(not sure if it might help but yeah):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#android:id/progress">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="7.0"
android:useLevel="true">
<gradient
android:startColor="#fb0000"
android:endColor="#00FF00"
android:centerColor="#fbf400"
android:type="sweep" />
</shape>
</item>
</layer-list>
I found the solution:
Xml:
<ProgressBar
android:id="#+id/progressbar"
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Java code:
public class thetest extends AppCompatActivity {
ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thetest);
mProgressBar=findViewById(R.id.progressbar);
mProgressBar.setProgress(i);
mCountDownTimer=new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
i++;
mProgressBar.setProgress((int)i*100/(30000/1000));
}
#Override
public void onFinish() {
//Do what you want
i++;
mProgressBar.setProgress(100);
}
};
mCountDownTimer.start();
}
}
Rather than using animation to get a countdown timer, you can programmatically set the countdown time length as maximum progress of ProgressBar, and use a Handler object scheduled to run every second, to update the current progress of the ProgressBar as shown below:
final ProgressBar pb = findViewById(R.id.progressBarToday);
// for eg: if countdown is to go for 30 seconds
pb.setMax(30);
// the progress in our progressbar decreases with the decrement
// in the remaining time for countdown to be over
pb.setProgress(30);
// keep track of current progress
final int[] currentProgress = {30};
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
currentProgress[0] -= 1;
pb.setProgress(currentProgress[0]);
if(currentProgress[0] != 0){
new Handler().postDelayed(this, 1000);
}else
Toast.makeText(requireContext(), "Count Down is OVER!!", Toast.LENGTH_LONG).show();
}
}, 1000);

How to have a One Common ProgressBar in Android Project

I'm currently trying to sort out a way to have a single Common ProgressBar to everywhere(Activity/Fragment) I need in my Android Project. The methods I tried did not promise me good results. Please help me to find a better solution. An example with code for android java is more than welcome.
This is my Custom ProgressBar
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fl_common_probar"
android:elevation="40dp"
android:visibility="gone"
android:layout_centerInParent="true">
<View
android:id="#+id/background_dim_pro"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.5"
android:background="#color/textTitleW"
android:elevation="50dp"/>
<RelativeLayout
android:id="#+id/relative_container_pro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:elevation="60dp">
<ImageView
android:id="#+id/image_test"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:src="#drawable/logo_loading" />
<ProgressBar
android:id="#+id/progress_bar_circle_pro"
style="?android:attr/progressBarStyle"
android:layout_width="132dp"
android:layout_height="132dp"
android:indeterminateDrawable="#drawable/circular_progress_bar"
android:indeterminateDuration="#android:integer/config_longAnimTime" />
</RelativeLayout>
Please try with below approach.
1.) Create a layout xml file (dialog_progress.xml) with the below content.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl_progress"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
2.) Create AppUtil Java class and create a static method as below.
public class AppUtil {
// progress bar handling
public static Dialog showProgress(Activity activity) {
Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(0));
dialog.setContentView(R.layout.dialog_progress);
ProgressBar progressBar = dialog.findViewById(R.id.progressBar);
progressBar.getIndeterminateDrawable().setColorFilter(activity.getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
dialog.setCancelable(false);
dialog.show();
return dialog;
}
}
3.) When you need to show a ProgressBar in an Activity/Fragment do as below.
Dialog dialog = AppUtil.showProgress(MainActivity.this);
When you need to dissmiss the progressBar
dialog.dismiss();
That's it. Try and let me know your feedback.
Thank you.
Create a Java class Seperately for Progress Dialog
public class ProgressDialog {
private Dialog dialog;
private ProgressBar progressBar;
public ProgressDialog(Context context) {
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progress_layout);
dialog.setCancelable(false);
if (dialog.getWindow() != null) {
dialog.getWindow()
.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
progressBar = dialog.findViewById(R.id.progressBar);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.getIndeterminateDrawable().setColorFilter(randomColor(), PorterDuff.Mode.MULTIPLY);
new Handler().postDelayed(this, 300);
}
}, 0);
}
public void showDialog() {
if (dialog != null && !dialog.isShowing())
dialog.show();
}
public void hideDialog() {
if (dialog != null && dialog.isShowing())
dialog.cancel();
}}
//Now you can use it in anywhere in you activity/fragment
Activity:
public class ShowProgressBar extends AppCompatActivity{
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_web_pages);
progressDialog= new ProgressDialog (ShowProgressBar.this);
}
//Use these methods in your code where you want to show the progress dialog or hide the dialog.
// showing animated dialog
public void showDialog(){
progressDialog.showDialog();
}
// hide animated dialog
public void hideDialog(){
progressDialog.hideDialog();
}

Android Progress Bar not working

I have made a progress bar in Android but it is not at all working. What am I doing wrong? I have just started to learn android. Below is my code.
MainActivity.java-
public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
int mporgress=0;
EditText time;
private Handler mHandler = new Handler();
private static final int PROGRESS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Startbuttononclick(View view){
Button startbutton=(Button) findViewById(R.id.button);
startbutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mporgress = Integer.parseInt(time.getText().toString());
progressBar.setProgress(mporgress);
new Thread(new Runnable() {
public void run() {
while (mporgress < 100) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(mporgress);
mporgress = doWork();
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
});
}
}
}).start();
}
});
}
public void doprogress(View view) {
}
public int doWork(){
mporgress++;
return mporgress;
}
}
Activity_main.xml-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android.progressbar.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the time:"
android:inputType="number"
android:id="#+id/editText" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="500dp"
android:layout_height="200dp"
android:id="#+id/progressBar4"
android:layout_gravity="center"
android:scrollbarSize="500dp" />
<Button
android:text="START"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_gravity="center"
android:onClick="Startbuttononclick" />
</LinearLayout>
Check out this image below-
- https://i.stack.imgur.com/2TBIb.png
Note- Enter the time in this image is an EditText with a hint and not a TextView.
It is appearing but not working.
I have done these changes so far.-
https://i.stack.imgur.com/UujpB.png
But still the progress bar is still continuously rotating.
Seems you forgot to initialize EditText -time and ProgressBar. Init it inside onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar =(ProgressBar) findViewById(R.id.progressBar4);
time = (EditText) findViewById(R.id.editText); //here
}
Also inside button click the bar:
progressBar = new ProgressBar(this);
mporgress = Integer.parseInt(time.getText().toString());
................
.............

android weird error at the beginning

package com.example.medapp;
public class MainActivity extends Activity {
public final static String apts = "com.example.medapp.editapts";
static final int PICK_DATE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View view) {
// Do something in response to button
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
int date = dp.getYear() + dp.getMonth() + dp.getDayOfMonth();
//load DATABASE
//start showing the list
final ListView listview = (ListView) findViewById(R.id.listView1);
String[] values = new String[] { "apt1", "apt2", "apt3",
"apt4", "apt5", "apt6", "apt7", "apt8" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(view.getContext(),editapts.class);
intent.putExtra(apts,item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
startActivity(intent);
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Hi there
I have some weird problem about my code
it says
Multiple markers at this line
- button1 cannot be resolved
- overrides
android.app.Activity.onCreate
on code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
which was totally fine before (button1 is the trigger which do the acts)
the error part was provided when the file created
any tip please? android noob here :s
Thank you :)
I already did clean and rebuild everything and still not working :(
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<DatePicker
android:id="#+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="19dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/datePicker1"
android:layout_below="#+id/button1"
android:layout_marginTop="20dp" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/datePicker1"
android:layout_alignParentTop="true"
android:layout_marginTop="34dp"
android:text="Appointments" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/datePicker1"
android:layout_alignBottom="#+id/datePicker1"
android:layout_alignRight="#+id/listView1"
android:layout_marginRight="36dp"
android:onClick="open"
android:text="Open" />
</RelativeLayout>
Remove
android:onClick="open"
from your Xml . And try this into your OnCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// do whatever you are doing in open method
}
}
}
Basically your code and this edit is same , but certainly something wrong going on. Hope it helps.

Property animation of a moving button android

I need a button that will keep moving from left to right and whenever i click on it, it will do something. I came to know that I need to use Property Animation to do so. But I'm quite lost about it.
here is my main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="39dp"
android:layout_marginTop="106dp"
android:text="Button" />
how do I edit my .java file to animate it from left to right using property animation?
Have a look on this Tutorial Android Animations.
The easiest way to animate a layout is, to do something like this :
your_layout.animate().translationX(your_layout.getWidth()).setDuration(500).setInterpolator(new AccelerateDecelerateInterpolator());
I would do it the following way:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//new GetUrl().execute(20);
// Test XML Files
//testXMLFiles();
final Button speakButton = (Button)findViewById(R.id.play);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
// TODO: DO something!
}
});
final ObjectAnimator horizontalAnimator = ObjectAnimator.ofInt(new ButtonAnimatorHelper(speakButton), "marginLeft", 0, 600);
horizontalAnimator.setDuration(2000);
horizontalAnimator.setRepeatCount(ValueAnimator.INFINITE);
horizontalAnimator.setRepeatMode(ValueAnimator.REVERSE);
horizontalAnimator.setInterpolator(new LinearInterpolator());
horizontalAnimator.start();
}
/**
* Helper class for button animation
*/
private static class ButtonAnimatorHelper {
final Button mButton;
/**
* Default constructor
* #param speakButton
*/
public ButtonAnimatorHelper(final Button button) {
mButton = button;
}
public void setMarginLeft(final int margin) {
final ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mButton.getLayoutParams();
params.leftMargin = margin;
mButton.setLayoutParams(params);
}
}
}
For better understanding of property animation, I would suggest this session from Google I/O 2013 and of course, the tutorial here.

Categories

Resources