How to set progress in Horizontal Progress Bar android - android

I want to have Horizontal progress bar that moves from 0 to 100. I added this code in layout. what should i do for moving this progress bar?
<ProgressBar
android:id="#+id/progressBar"
android:indeterminate="false"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:progress="0"
android:max="100"
style="#android:style/Widget.ProgressBar.Horizontal"
/>

Try this code :
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btn;
private ProgressBar progressBar;
TextView txt;
Integer count =1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
btn = (Button) findViewById(R.id.btn);
btn.setText("Start");
txt = (TextView) findViewById(R.id.output);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count =1;
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
new MyTask().execute(100);
});
}
class MyTask extends AsyncTask<Integer, Integer, String> {
#Override
protected String doInBackground(Integer... params) {
for (count=1 ; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
txt.setText(result);
btn.setText("Restart");
}
#Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
#Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setProgress(values[0]);
}
}
}

android:indeterminate: false
You must add the feature.
Sample
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="116dp"
android:text="Do some stuff" />
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:id="#+id/progressBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:progress="0"/>
</LinearLayout>
class MainActivity : AppCompatActivity() {
private var progressBarStatus = 0
var dummy:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the references from layout file
var btnStartProgress = this.button1
var progressBar = this.progressBar1
// when button is clicked, start the task
btnStartProgress.setOnClickListener { v ->
// task is run on a thread
Thread(Runnable {
// dummy thread mimicking some operation whose progress can be tracked
while (progressBarStatus < 100) {
// performing some dummy operation
try {
dummy = dummy+25
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
// tracking progress
progressBarStatus = dummy
// Updating the progress bar
progressBar.progress = progressBarStatus
}
}).start()
}
}
}

Related

How to add Progress Bar dynamically to the layout

I am rolling a dice and using a random function i am counting the no. of 1s,2s,3s,4s,5s,6s and printing it out .If it takes too much time then it will show a progress bar.Why my android code is not showing progress bar although i have used progress bar in my java code?
Plz figure out the mistakes.
Java Code
package dead.asynctaskprogressbar;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
editText=(EditText)findViewById(R.id.editText);
}
public class Asynctask extends AsyncTask<Integer,Integer,String>{
ProgressBar bar;
#Override
protected void onPreExecute() {
super.onPreExecute();
bar=new ProgressBar(MainActivity.this,null,android.R.attr.progressBarStyleHorizontal);
bar.setVisibility(View.VISIBLE);
bar.setMax(Integer.parseInt(editText.getText().toString().trim()));
}
#Override
protected String doInBackground(Integer... integers) {
Random random=new Random();
int ones=0,twos=0,threes=0,fours=0,fives=0,sixes=0,a;
double currentProgress=0;
double previousprogress=0;
for (int i=0;i<integers[0];i++){
currentProgress=(double)i/integers[0];
if (currentProgress-previousprogress>=0.02){
previousprogress=currentProgress;
publishProgress(i);
}
a= random.nextInt(6)+1;
switch (a){
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
default:
sixes++;
}
}
String results="Ones :"+ones +"\n"+"Twos :"+twos +"\n"+"Threes :"+threes +"\n"+"Fours :"+fours +"\n"+"Fives :"+fives +"\n"+"Sixes :"+sixes +"\n";
return results;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
bar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
public void Dice(View view){
int not=Integer.parseInt(editText.getText().toString().trim());
new Asynctask().execute(not);
}
}
Xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="dead.asynctaskprogressbar.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:hint="Dice"
android:inputType="textPersonName"
android:padding="10dp" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="Dice"
android:text="Roll Dice" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="20dp" />
</LinearLayout>
Why my android code is not showing progress bar
You have created ProgressBar dynamically but You didn't add that ProgressBar inside your layout that's why its not displaying
You need to add that ProgressBar in your layout
Try below code it will work fine
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
ProgressBar bar;
LinearLayout rootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar=new ProgressBar(MainActivity.this,null,android.R.attr.progressBarStyleHorizontal);
rootView=findViewById(R.id.rootView);
rootView.addView(bar);
bar.setVisibility(View.GONE);
}
public class Asynctask extends AsyncTask<Integer,Integer,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(View.VISIBLE);
bar.setMax(Integer.parseInt(editText.getText().toString().trim()));
}
#Override
protected String doInBackground(Integer... integers) {
Random random=new Random();
int ones=0,twos=0,threes=0,fours=0,fives=0,sixes=0,a;
double currentProgress=0;
double previousprogress=0;
for (int i=0;i<integers[0];i++){
currentProgress=(double)i/integers[0];
if (currentProgress-previousprogress>=0.02){
previousprogress=currentProgress;
publishProgress(i);
}
a= random.nextInt(6)+1;
switch (a){
case 1:
ones++;
break;
case 2:
twos++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
default:
sixes++;
}
}
String results="Ones :"+ones +"\n"+"Twos :"+twos +"\n"+"Threes :"+threes +"\n"+"Fours :"+fours +"\n"+"Fives :"+fives +"\n"+"Sixes :"+sixes +"\n";
return results;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
bar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
public void Dice(View view){
int not=Integer.parseInt(editText.getText().toString().trim());
new Asynctask().execute(not);
}
}

Animating android progress bar

I've created ProgressBar in my view, and I would like it to animate when it's value is updated. I'm runnig the code on API 23. How to animate progressBar when It's value is updated?
Here is my activity:
package com.brylkowski.cleaner.cleaner.Errands;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;
import com.brylkowski.cleaner.cleaner.R;
public class UploadErrandActivity extends AppCompatActivity {
public static final String PROGRESS = "progress";
UploadRequestTask task;
private ProgressBar progressBar;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_errand);
progressBar = (ProgressBar) findViewById(R.id.upload_progress);
progressBar.setMax(6);
task = new UploadRequestTask();
handler = new Handler() {
public void handleMessage(android.os.Message msg) {
progressBar.incrementProgressBy(1);
}
};
task.execute();
}
public class UploadRequestTask extends AsyncTask<Void, Void, Boolean> {
UploadRequestTask() {
}
#Override
protected Boolean doInBackground(Void... params) {
for (int i = 1; i <=6; i++){
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt(PROGRESS, i);
msg.setData(bundle);
handler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
}
and my view:
<?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: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"
android:orientation="vertical"
android:gravity="center"
tools:context="com.brylkowski.cleaner.cleaner.Errands.UploadErrandActivity">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:indeterminate="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/upload_progress"
android:layout_gravity="bottom"
android:longClickable="false"/>
</LinearLayout>
Check this for how to make ProgressBar animation. The only modification you need is instead of applying the animation once when view is initialized, you will need to call
ProgressBarAnimation anim = new ProgressBarAnimation(progressBar, progressBar.getProgress(), to);
anim.setDuration(1000);
progressBar.startAnimation(anim); // play animation immediately
every time you want to update value. Here is documentation for view animation.

how to show progress bar(circle) in an activity having a listview before loading the listview with data

I have a ListView in my second activity.OnItemClick of it I called a webservice and trying to fetch data. And after that I am moving to third activity which also have a ListView having description of previous activities ListView item.
I want to display a progress dialog before populating this ListView.
I don't understand how to do it on ListView? Does anybody know how to do it?
My Code-
ThirdActivity.java
package com.google.iprotect;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;
import com.google.iprotect.layout.TitleBarLayout;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class ThirdActivity extends ListActivity implements OnItemClickListener{
JSONArray jArray1,jArray2;
String one,two,three,tablename;
String color,r;
JSONObject responseJSON;
TitleBarLayout titlebarLayout;
final ArrayList<Tables> arraylist = new ArrayList<Tables>();
TextView tableName;
ColorStateList colorStateList1;
String email1,password1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
ListView lv=getListView();
lv.setOnItemClickListener(this);
tablename=getIntent().getExtras().getString("Table Name");
email1 = getIntent().getExtras().getString("email");
password1 =getIntent().getExtras().getString("password");
titlebarLayout = new TitleBarLayout(ThirdActivity.this);
titlebarLayout.setLeftButtonText("go Back");
titlebarLayout.setRightButtonText("Logout");
titlebarLayout.setTitle(tablename);
titlebarLayout.setLeftButtonSize(70,40);
titlebarLayout.setRightButtonSize(70,40);
//titlebarLayout.setLeftButtonLeftDrawable(R.drawable.refresh);
//titlebarLayout.setRightButtonLeftDrawable(R.drawable.buttonrefresh);
//titlebarLayout.setLeftButtonBackgroundColor(Color.rgb(255,255,255));
//titlebarLayout.setRightButtonBackgroundColor(Color.rgb(34,49,64));
//titlebarLayout.setLeftButtonTextColor(Color.rgb(255,255,255));
//titlebarLayout.setRightButtonTextColor(Color.rgb(255,255,0));
XmlResourceParser parser1 =getResources().getXml(R.color.colorstatelist);
try {
colorStateList1 = ColorStateList.createFromXml(getResources(), parser1);
titlebarLayout.setRightButtonTextColor(colorStateList1);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.left_button) {
Intent intent = new Intent(ThirdActivity.this,SecondActivity.class);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
startActivity(intent);
finish();
} else if (v.getId() == R.id.right_button) {
Intent intent = new Intent(ThirdActivity.this,
MainActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
ThirdActivity.this.startActivity(intent);
}
}
};
titlebarLayout.setLeftButtonOnClickListener(listener);
titlebarLayout.setRightButtonOnClickListener(listener);
updateTableList();
}
private void updateTableList() {
// TODO Auto-generated method stub
//final ProgressDialog pd1=ProgressDialog.show(this, "Calling Webservice", "Waiting...", true, false);
final ProgressBar pbHeaderProgress = (ProgressBar) findViewById(R.id.pbHeaderProgress);
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pbHeaderProgress.setVisibility(View.VISIBLE);
}
protected Void doInBackground(Void... params) {
r = invokeWebService1(tablename);
//pd1.dismiss();
try {
responseJSON = new JSONObject(r);
//json reading
jArray1 = responseJSON.getJSONArray("FirstThree");//get JSONArray jArray1 from JSONObject with name FirstThree
jArray2 = responseJSON.getJSONArray("Color");//get JSONArray jArray2 from JSONOobject with name Color
JSONObject json_data1 = null;
JSONObject json_data2 = null;
for (int i = 0; i < jArray1.length(); i++) {
json_data1 = jArray1.getJSONObject(i);//get JSONObject json_data1 from JSONArray at index i;
one = json_data1.getString("One");//get value from JSONObject json_data1 with key "One"
two = json_data1.getString("Two");
three = json_data1.getString("Three");
json_data2 = jArray2.getJSONObject(i);
color = json_data2.getString("color");//get value from JSONObject json_data2 with key "color"
Tables tables = new Tables();
//set value to Tables Class
tables.column1 = one;
tables.column2 = two;
tables.column3 = three;
tables.tableName=tablename;
tables.color=color;
//add Tables object into ArrayList<Tables>
arraylist.add(tables);
Log.i("ONE", json_data1.getString("One"));
Log.i("TWO", json_data1.getString("Two"));
Log.i("THREE", json_data1.getString("Three"));
Log.i("color",""+ json_data2.getString("color"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
pbHeaderProgress.setVisibility(View.GONE);
//Custom Adapter for ListView
TableDetailAdapter adaptor = new TableDetailAdapter(ThirdActivity.this,
R.layout.table_data_list_item, arraylist);
setListAdapter(adaptor);
}
}.execute();
}
protected String invokeWebService1(String tablename2) {
// TODO Auto-generated method stub
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
// Pass the parameters if needed
Map<String, String> params = new HashMap<String, String>();
params.put("action", "getTableRecords");
params.put("tablename", tablename2);
params.put("email", email1);
params.put("password", password1);
// Get JSON response from server the "" are where the method name
// would normally go if needed example
response = webService.WebGet("auth", params);
} catch (Exception e) {
Log.d("Error: ", e.getMessage());
}
return response;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
Log.v("", "Click ListItem Number "+position);
Intent intent = new Intent(ThirdActivity.this,FourthActivity.class);
intent.putExtra("Json", responseJSON.toString());//sending json Object as a string to next activity
intent.putExtra("Table Name", tablename);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
intent.putExtra("Item No", position);
startActivity(intent);
}
}
thirdactivity.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/linlaHeaderProgress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ThirdActivity" >
<include
android:id="#+id/titlebar"
layout="#layout/titlebar_layout" />
<ProgressBar
android:id="#+id/pbHeaderProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="2" >
</ProgressBar>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="260dp"
android:layout_weight="5.04">
</ListView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="#dimen/titlebar_height"
android:layout_alignParentBottom="true"
android:background="#color/footer_bg_color"
android:gravity="bottom"
android:orientation="horizontal" >
<include
android:id="#+id/footer"
android:layout_height="#dimen/titlebar_height"
android:layout_gravity="bottom|center_horizontal"
layout="#layout/footer_layout" />
</LinearLayout>
</LinearLayout>
There are several methods of showing a progress bar (circle) while loading an activity. In your case, one with a ListView in it.
IN ACTIONBAR
If you are using an ActionBar, you can call the ProgressBar like this (this could go in your onCreate()
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
And after you are done displaying the list, to hide it.
setProgressBarIndeterminateVisibility(false);
IN THE LAYOUT (The XML)
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="#+id/pbHeaderProgress"
style="#style/Spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:cacheColorHint="#android:color/transparent"
android:divider="#00000000"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:persistentDrawingCache="scrolling"
android:smoothScrollbar="false" >
</ListView>
</LinearLayout>
And in your activity (Java)
I use an AsyncTask to fetch data for my lists. SO, in the AsyncTask's onPreExecute() I use something like this:
// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
#Override
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
and in the onPostExecute(), after setting the adapter to the ListView:
#Override
protected void onPostExecute(Void result) {
// SET THE ADAPTER TO THE LISTVIEW
lv.setAdapter(adapter);
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
EDIT: This is how it looks in my app while loading one of several ListViews
You can do this easier.
Source: http://www.tutorialspoint.com/android/android_loading_spinner.htm
It helped me.
Layout:
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
After defining it in xml, you have to get its reference in java file
through ProgressBar class. Its syntax is given below:
private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);
After that you can make its disappear , and bring it back when needed
through setVisibility Method. Its syntax is given below:
spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
I used this one for list view loading may helpful.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp" >
<LinearLayout
android:id="#+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="1dip"
android:visibility="gone" />
</RelativeLayout>
and my MainActivity class is,
public class MainActivity extends Activity {
ListView listView;
LinearLayout layout;
List<String> stringValues;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
stringValues = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stringValues);
listView.setAdapter(adapter);
new Task().execute();
}
class Task extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
listView.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean result) {
layout.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Boolean doInBackground(String... params) {
stringValues.add("String 1");
stringValues.add("String 2");
stringValues.add("String 3");
stringValues.add("String 4");
stringValues.add("String 5");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
this activity display progress for 3sec then it will display listview, instead of adding data statically to stringValues list you can get data from server in doInBackground() and display it.
Please use the sample at tutorialspoint.com. The whole implementation only needs a few lines of code without changing your xml file. Hope this helps.
STEP 1: Import library
import android.app.ProgressDialog;
STEP 2: Declare ProgressDialog global variable
ProgressDialog loading = null;
STEP 3: Start new ProgressDialog and use the following properties (please be informed that this sample only covers the basic circle loading bar without the real time progress status).
loading = new ProgressDialog(v.getContext());
loading.setCancelable(true);
loading.setMessage(Constant.Message.AuthenticatingUser);
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
STEP 4: If you are using AsyncTasks, you can start showing the dialog in onPreExecute method. Otherwise, just place the code in the beginning of your button onClick event.
loading.show();
STEP 5: If you are using AsyncTasks, you can close the progress dialog by placing the code in onPostExecute method. Otherwise, just place the code before closing your button onClick event.
loading.dismiss();
Tested it with my Nexus 5 android v4.0.3. Good luck!
Are you extending ListActivity?
If so, put a circular progress dialog with the following line in your xml
<ProgressBar
android:id="#android:id/empty"
...other stuff...
/>
Now, the progress indicator will show up till you have all your listview information, and set the Adapter. At which point, it will go back to the listview, and the progress bar will go away.
ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);
Create an xml file any name (say progressBar.xml) in drawable
and add <color name="silverGrey">#C0C0C0</color> in color.xml.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="720" >
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="6"
android:useLevel="false" >
<size
android:height="200dip"
android:width="300dip" />
<gradient
android:angle="0"
android:endColor="#color/silverGrey"
android:startColor="#android:color/transparent"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Now in your xml file where you have your listView add this code:
<ListView
android:id="#+id/list_form_statusMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<ProgressBar
android:id="#+id/progressBar"
style="#style/CustomAlertDialogStyle"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:indeterminateDrawable="#drawable/circularprogress"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
In AsyncTask in the method:
#Override
protected void onPreExecute()
{
progressbar_view.setVisibility(View.VISIBLE);
// your code
}
And in onPostExecute:
#Override
protected void onPostExecute(String s)
{
progressbar_view.setVisibility(View.GONE);
//your code
}
You can add the ProgressBar to listview footer:
private ListView listview;
private ProgressBar progressBar;
...
progressBar = (ProgressBar) LayoutInflater.from(this).inflate(R.layout.progress_bar, null);
listview.addFooterView(progressBar);
layout/progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/load_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
when the data is loaded to the adapter view call:
listview.removeFooterView(progressBar);
I suggest you when working with listview or recyclerview to use SwipeRefreshLayout. Like this
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/card_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
Only wrap your view and this will create an animation of refresh when loading data or by swipping down the screen as we can do in many apps.
Here's the documentation of how to use it:
https://developer.android.com/training/swipe/add-swipe-interface.html
https://developer.android.com/training/swipe/respond-refresh-request.html
Happy coding !
Use this within button onClick option or your needs.
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
Process Bar:
Dependency:
implementation 'com.github.castorflex.smoothprogressbar:library:1.0.0'
XML:
<fr.castorflex.android.smoothprogressbar.SmoothProgressBar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/myProcessbar"
android:layout_width="match_parent"
android:layout_height="10dp"
android:indeterminate="true" />
In Res->color
<color name="pocket_color_1">#ff1635</color>
<integer-array name="pocket_background_colors">
<item>#color/pocket_color_1</item>
</integer-array>
<color name="pocket_color_stop">#00ff00</color>
<integer-array name="pocket_background_stop">
<item>#color/pocket_color_stop</item>
</integer-array>
In Main:
public class MainActivity extends AppCompatActivity{
SmoothProgressBar smoothProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smoothProgressBar=findViewById(R.id.myProcessbar);
showProcessBar();
stopAnimation(); // call when required to stop process
}
public void showProcessBar(){
smoothProgressBar.setVisibility(View.VISIBLE);
smoothProgressBar.setIndeterminateDrawable(new SmoothProgressDrawable.Builder(getApplicationContext())
.interpolator(new AccelerateInterpolator())
.progressiveStart(true)
.progressiveStopSpeed(1000)
.build());
smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
SmoothProgressBarUtils.generateDrawableWithColors(
getResources().getIntArray(R.array.pocket_background_colors),
((SmoothProgressDrawable) smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
}
public void stopAnimation(){
smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
SmoothProgressBarUtils.generateDrawableWithColors(
getResources().getIntArray(R.array.pocket_background_stop),
((SmoothProgressDrawable) smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
smoothProgressBar.progressiveStop();
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
smoothProgressBar.animate().alpha(0.0f).setDuration(6000).translationY(1000);
smoothProgressBar.setVisibility(View.GONE);
}
},1000);
}
}
I am using this:
loading = ProgressDialog.show(example.this,"",null, true, true);

Button duplication in android when setting new text

I am working with the android support library, to be able to use fragments from Froyo, and the Sherlock extension, to show an ActionBar.
I have a fragment which shows three textViews and a button, and I want to be able to change the button text dinamically, depending on the content of the Intent. The problem is that when I call button.setText(String text), a second button appears. However, I've called button.getId() when clicking on each of them, and the Id is the same. I don't have a clue of why this is happening, so I'd appreciate some help.
The app is run on a Samsung Galaxy S, with Android 2.3.3. I can't upload a screen capture because I don't have enough reputation yet :(
This is the code:
FRAGMENT
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragment;
import com.parse.ParseUser;
import com.tiempoderodar.egdf.EGDF_App;
import com.tiempoderodar.egdf.R;
import com.tiempoderodar.egdf.security.Constants;
/**
* #author Daniel Leal López
*
*/
public class ChapterDetailsFragment extends SherlockFragment{
private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("ChapterDetailsFragment", "Created");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ParseUser user = EGDF_App.getUser();
b = (Button) getSherlockActivity().findViewById(R.id.buttonWatchChapter);
if (user != null){
String chapterNumber = "";
Bundle extras = getSherlockActivity().getIntent().getExtras();
String s = extras.getString(Constants.CHAPTER_NUMBER_PARSE);
if((s != null)&&(!s.equals(""))){
// tvNumber.setText(s);
chapterNumber = "Chapter_" + s;
Log.i("Properties", s);
}
String seen = user.getString(chapterNumber);
if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_SEEN))){
b.setText("Second text: "+getString(R.string.watch_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to watch");
}
else if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_NOT_SEEN))){
b.setText("Second text: " + getString(R.string.buy_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to buy");
}else{
Log.w("DEV ERROR", "Chapter text not obtained");
}
}else{
Log.w("DEV ERROR", "ParseUser is null in EGDF_App!!!");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chapter_details, container, false);
return view;
}
public void setText(String item) {
getSherlockActivity().getSupportActionBar().setTitle(item);
}
public void setButtonText(String text){
b.setText(text);
}
}
Activity
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ChapterDetailsActivity extends SherlockFragmentActivity {
private Bundle extras;
MediaPlayer mMediaPlayer;
private String chapterNumber;
private boolean isChapterSeen;
// private int duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_details);
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
ChapterDetailsFragment details = new ChapterDetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
Log.d("BUTTON PARENT VIEW", b.getParent().getClass().getName());
Log.d("BUTTON ID", String.valueOf(b.getId()));
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
String buyChapter = getString(R.string.buy_chapter_button_text);
}
#Override
protected void onPause() {
Log.i("Activity lifecycle", "On pause called");
super.onPause();
}
#Override
protected void onStop() {
Log.i("Activity lifecycle", "On stop called");
super.onStop();
}
#Override
protected void onDestroy() {
Log.i("Activity lifecycle", "On destroy called");
super.onDestroy();
EGDF_App.releaseMediaPlayer();
}
#Override
protected void onResume() {
Log.i("Activity lifecycle", "On resume called");
super.onResume();
}
#Override
protected void onStart() {
Log.i("Activity lifecycle", "On start called");
super.onStart();
}
}
Activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/chapterDetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.tiempoderodar.egdf.content.ChapterDetailsFragment" />
</LinearLayout>
Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewChapterNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSeason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSinopsis"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterCredits"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<Button
android:id="#+id/buttonWatchChapter"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/watch_chapter_button_text"
android:layout_gravity="center"
android:onClick="watchChapter"/>
</LinearLayout>
Thanks!
I think I might have found the problem. I was calling
b = (Button) getSherlockActivity().findViewById(R.id.button);
but it should be
b = (Button) getView().findViewById(R.id.button);
With that change it works correctly

Android imageView Switching Problem

i have imageview and i have to display different image in
that with time interval, but when i change the ImageResource
the last image is displayed
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test);
try {
Thread.sleep(2000) ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);
}
Kindly Suggest the Right way to do that
Thanks in Advance
Perhaps this thread is what you are looking for:
how to change images with timer
Whenever you want to update the user interface without performing any action or event, handlers should be used.
This is the sample code
Main.java
package com.balaji.handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;
public class Main extends Activity {
private ImageView txtStatus;
int i=0;
int imgid[]={R.drawable.icon,R.drawable.back,R.drawable.slider,R.drawable.forward};
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Main.this.updateUI();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
private void updateUI(){
//int currentInt = Integer.parseInt((String) txtStatus.getText()) + 10;
if(i<imgid.length){
mRedrawHandler.sleep(1000);
txtStatus.setBackgroundResource(imgid[i]);
i++;
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
this.txtStatus = (ImageView)this.findViewById(R.id.txtStatus);
updateUI();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
</ImageView>
</RelativeLayout>

Categories

Resources