My loading circle works fine but has a white box behind it as seen here. I have spent a few hours searching for solutions and all of the SO posts I've found suggest an implementation very similar to the one I've used. I also tried applying a custom theme to the dialog and setting transparency but this did nothing. I'm not sure what the white rectangle actually is since changing the properties of the ProgressBar itself only seems to affect the square in the center containing the image.
I have the following layout defined for my progress bar which runs during my AsyncTask.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/transparent" >
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"/>
</FrameLayout>
Below is my method for the dialog which uses the layout shown above.
public static ProgressDialog createProgressDialog(Context mContext) {
ProgressDialog dialog = new ProgressDialog(mContext);
try {
dialog.show();
} catch (WindowManager.BadTokenException e) {
}
dialog.setCancelable(false);
dialog.setContentView(R.layout.progressdialog);
return dialog;
}
public class FetchAcroTask extends AsyncTask<String, Void, String[]> {
Dialog progressDialog = null;
#Override
protected void onPreExecute() {
// Display loading circle
if (progressDialog == null) {
progressDialog = createProgressDialog(AcroActivity.this);
progressDialog.show();
} else {
progressDialog.show();
}
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
return GET(params[0]);
}
#Override
protected void onPostExecute(String[] resultStrs) {
if (resultStrs == null) {
acroAdapter.add("No results were found");
} else {
acroAdapter.addAll(resultStrs);
}
// Dismiss loading circle
progressDialog.dismiss();
}
}
}
Thanks in advance.
I've found the solution thanks to the comment left by Kostas.
I transferred my ProgressBar declaration to my layout file for the activity and simply hide it when my AsyncTask is complete.
In my activity's layout file:
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
Within the async task:
#Override
protected void onPostExecute(String[] resultStrs) {
if (resultStrs == null) {
acroAdapter.add("No results were found");
} else {
acroAdapter.addAll(resultStrs);
}
// Dismiss loading circle
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.INVISIBLE);
}
Thank you.
Related
I am using this code, everything are working fine, but progressbar is not showing. I want to block my ui during the method implementation and want to show progressbar. I want to get behaviour like progressDialog.
Here is my method
public void effct(int effectNo) {
final int finalEffectNO = effectNo;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressLayout.setVisibility(View.VISIBLE);
progressLayoutLinear.setVisibility(View.VISIBLE);
Thread thread = new Thread(){
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
imageViewFragment.applyEffect(finalEffectNO);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressLayout.setVisibility(View.GONE);
progressLayoutLinear.setVisibility(View.GONE);
}
});
}
};
thread.start();
}
My xml code for progressLayout
<LinearLayout
android:id="#+id/progressBarLinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:padding="12dp"
android:visibility="gone"
android:orientation="horizontal">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:textSize="18sp"/>
</LinearLayout>
For above your requirement you must use ProgressDialog for same, here is an example
Example
Try using an AsyncTask instead of Thread, something like this :
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressLayoutLinear.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(final Void ... params ) {
runOnUiThread(new Runnable() {
#Override
public void run() {
imageViewFragment.applyEffect(finalEffectNO);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
});
return null;
}
#Override
protected void onPostExecute( final Void result ) {
progressLayoutLinear.setVisibility(View.GONE);
}
}.execute();
Hope this helps
There’s a few ways to solve your problem - check this video for more information. The most basic approach might be an AsyncTask, which could look like this:
public class DummyAsyncTask extends AsyncTask<Void, Void, Void> {
private final Window window;
private final ProgressBar progressBar;
public DummyAsyncTask(Window window, ProgressBar progressBar) {
this.window = window;
this.progressBar = progressBar;
}
#Override protected void onPreExecute() {
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.VISIBLE);
}
#Override protected Void doInBackground(Void... voids) {
// Do the heavy lifting.
}
#Override protected void onPostExecute(Void aVoid) {
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.GONE);
}
}
You execute it by running new DummyAsyncTask(/* params */).execute();.
Do note that AsyncTask does not adhere to the lifecycle and holding a reference to a Context aware instance is just asking for trouble. A safer alternative might be using LiveData:
public void effect(int effectNo) {
// Show progress and disable user interaction here.
final ListData<Content> data = model.applyEffect(effectNo);
data.observe(this, (Observer<Content>) c -> {
// Apply results, hide progress & enable user interaction.
});
}
Given the above, you should be careful how you handle showing & hiding progress, so you don’t accidentally disable user interaction forever.
I loading some data from a database and I'd like to display a circle animation during this, because it's take time. The circle appears but only after loadContent() which load data.
The code:
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
ProgressBar p = (ProgressBar) findViewById(R.id.imgProgress);
p.setEnabled(true);
if (settings.getBoolean("my_first_time", true)) {
// the app is being launched for first time, do something
Log.d("Launched:", "first time");
loadContent();
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
p.setEnabled(false);
In XML:
<ProgressBar
android:id="#+id/imgProgress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content" />
Why not just do this ?
public class SomeTask extends AsyncTask<Void, String, Void>{
ProgressDialog dialogue;
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialogue.dismiss();
//If Using some adapter; someadapteradapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
dialogue = new ProgressDialog(ProgressBar.this);
dialogue.setTitle("Loading items..");
dialogue.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//Your task!!
return null;
}
}
What can be more simple than this..:)
I don't know what is loadContent method but I'd suggest you to do an AsyncTask (if it's not the case). You will be able to show/hide your ProgressBar as follows:
// loadContent method
public class loadContent extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// set your progress bar to visible
((ProgressBar) findViewById(R.id.imgProgress)).setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
// do some stuff: load datas from sql, load images.. whatever
// and return a string value for onPostExecute (string = "Loaded"
return string;
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Loaded") {
// the loading is finish, display your datas
// set your progress bar to gone
((ProgressBar) findViewById(R.id.imgProgress)).setVisibility(View.GONE);
}
}
}
Here and here, you will see a good example of an AsyncTask method. Then, you just have to add the visibility attribute to your view as:
<ProgressBar
android:id="#+id/imgProgress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
android:indeterminate="true"
android:visibility="gone" />
Hope this helps.
For a few days a have some problem.
I need to show simple ProgressBar (not dialog) while doing some stuff in main thread...
I thought its a very simple question, but i cant do this, help me please.
First i tried simple setVisibility(View.VISIBLE) before and setVisibility(View.GONE) after.
But this is doing in the same thread, and ProgressBar freezed while my function working.
Now i have this code, but i have some error, and i dont know whats wrong..
my simple layout :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
i have a base activity :
public class BaseActivity extends Activity {
public ProgressBar loading;
public class ProgressBarShow extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... unused) {
return(null);
}
protected void onProgressUpdate() {
}
protected void onPreExecute() {
loading.setVisibility(View.VISIBLE);
}
protected void onPostExecute() {
}
}
}
and finally my working activity , which extends BaseActivity
public class SearchActivity extends BaseActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loading = (ProgressBar) findViewById(R.id.loading);
new ProgressBarShow().execute();
//doing long stuff
//new ProgressBarHide().execute(); there isnt, but sense the same
}
}
I have many activities, which need progress bar, thats why i have created BaseActivity,
to not to dublicate code.
I need to do long work (stuff function) in main thread, because i want to freeze main window and not to allow user do anything (click button etc..), just show working ProgressBar.
Whats wrong in my example? Or give me some advice how can i do this better
class ProgressTask extends AsyncTask<Integer, Integer, Void>{
ProgressBar progress;
Context context;
public ProgressTask(ProgressBar progress, Context context) {
this.progress = progress;
this.context = context;
}
#Override
protected void onPreExecute() {
// initialize the progress bar
// set maximum progress to 100.
progress.setMax(100);
}
#Override
protected Void doInBackground(Integer... params) {
// get the initial starting value
int start=params[0];
// increment the progress
for(int i=start;i<=100;i+=5){
try {
boolean cancelled=isCancelled();
//if async task is not cancelled, update the progress
if(!cancelled){
publishProgress(i);
SystemClock.sleep(1000);
}
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
return null;
}
//Has direct connection to UI Main thread
//Called everytime publishProgress(int) is called in doInBackground
#Override
protected void onProgressUpdate(Integer... values) {
progress.setProgress(values[0]);
Toast.makeText(context, "test"+values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void result) {
// async task finished
Log.v("Progress", "Finished");
}
#Override
protected void onCancelled() {
progress.setMax(0);
}
}
Use AsyncTask http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html Put your ProgressBar in it, while all work is doing in main thread
Firs of all thanks for reading this.
I'm having trouble updating the progress from my custom ProgressBar through an AsyncTask inner class. I'm using 9patch for the background and progress drawables. It just don't update. It stays there all filled like it was in the maxed value, I'm using the onProgressUpdate() to call the invalidate() and update the UI thread.
Here's what it looks like now, it goes visible and just stays there all filled up: http://imageshack.us/photo/my-images/651/mobicashprogressbar.png/
The progressbar should only be
visible after the user concludes the
form.
There's another inner AsyncTask handling the send SMS button that connects with an Web Service.
HERES THE CODE:
public void setTimerProgress(int progress){
progressBar.setProgress(progress);
}
public void updateProgress(){
progressBar.invalidate();
}
public void showProgress(){
progressBar.setVisibility(View.VISIBLE);
}
//Classe auxiliar para controle da progress bar
private class TimerProgress extends AsyncTask<Void, Void, Void>{
private int start;
private final int OTP_TIMEOUT = 900000;
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgress();
start = (int) System.currentTimeMillis();
}
#Override
protected Void doInBackground(Void... param) {
int timer = (int) System.currentTimeMillis() - start;
while (timer <= OTP_TIMEOUT){
setTimerProgress(timer);
timer = (int) System.currentTimeMillis() - start;
publishProgress();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
updateProgress();
}
}
HERE'S XML:
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:layout_gravity="center_horizontal"
android:visibility="invisible"
android:id="#+id/progress_bar_timer"
android:max="900000"
android:progress="3000"
android:progressDrawable="#drawable/progress_bar"
android:background="#drawable/progress_background"
android:layout_width="fill_parent"
android:layout_height="25dip"
android:layout_marginRight="73sp"
android:layout_marginLeft="70sp">
</ProgressBar>
HERE'S ONE PLACE WHERE I CALL IT
#Override
public void onClick(View v) {
if (v.getId() == R.id.refresh_otp) {
saveParametersForOTP();
if (edtIniPin.getText().length() == pinLengthInt) {
try {
disableEditText(edtIniPin);
disableEditText(edtValue);
edtOTP.setText(Facade.getInstance().nextOTP(Facade.getInstance().getPin(), Facade.getInstance().getValue()));
//Inicia o timer da progressbar
new TimerProgress().execute();
Help? :D
UPDATE:
For test purpuses I've set the OTP_TIMEOUT to 50000, made the following changes to the code and removed the 9patch drawables properties so it would use the native drawables for the bar. It works, however, when I use the images to customize the bar it appears the same old problem is happening. It is static, all filled up like before.
private final int OTP_TIMEOUT = 50000;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("PROGRESS", "Chegou no PreExecute!");
showProgress();
ENABLE_REFRESH = false;
start = (int) System.currentTimeMillis();
}
#Override
protected Void doInBackground(Void... param) {
int timer = (int) System.currentTimeMillis() - start;
while (timer <= OTP_TIMEOUT){
Log.i("PROGRESS", "Chegou no while!");
setTimerProgress((int)timer);
timer = (int) System.currentTimeMillis() - start;
publishProgress();
if (timer >= OTP_TIMEOUT) {
ENABLE_REFRESH = true;
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
Log.i("PROGRESS", "Chegou no Progress Update!");
updateProgress();
}
You need to add a layer-list resource and configure your ProgressBar to use it.
Here an example that I use. Note that in progress_bar.xml progress_bar_progress and progress_bar_background are nine-patch images.
progress_bar.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#android:id/background" android:drawable="#drawable/progress_bar_background" />
<item android:id="#android:id/progress" >
<clip android:drawable="#drawable/progress_bar_progress" />
</item>
</layer-list>list>
layout snippet:
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="30dp"
android:max="100"
android:progress="50"
android:progressDrawable="#drawable/progress_bar"
android:indeterminateOnly="false" />
In my application i'm downloading a video file. I want to show the progress bar for the download.
How is it possible through AsyncTask Concept?
Thanks,
Niki
Use the onProgressUpdate method of AsyncTask.
If you know the size of the file you can set the max value in onPreExecute:
protected void onPreExecute() {
ProgressDialog myDialog = new ProgressDialog(context);
myDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myDialog.setMax(maxValue);
myDialog.show();
}
EDIT: added myDialog.show();
There are several methods to update the progress, either by incrementing by an amount or by setting the progress to a specific value:
#Override
protected void onProgressUpdate(Integer... progress) {
myDialog.incrementProgressBy(progress[0]);
// or
// myDialog.setProgress(progress[0]);
}
Then in the onDoInBackground():
#Override
protected void doInBackGround() {
// your code
publishProgress(1);
}
EDIT example with progressbar in layout:
In your layout file, add a progressbar like this
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:visibility="gone"
/>
And in your asynctask:
protected void onPreExecute() {
ProgressBar myProgress = findViewById(R.id.progressbar);
myProgress.setMax(maxValue);
myProgress.setVisibility(View.VISIBLE);
}
protected void onProgressUpdate(Integer... progress) {
myProgress.setProgress(progress[0]);
}
First you have to calculate downloading timi, and then implement progress bar as per time limit. here i enclosed the sample program of progress bar
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
And this is the code for calculating the Time length for downloading file
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {
// getHeaderFields() returns a Map with key=(String) header
// name, value = List of String values for that header field.
// just use the first value here.
String sLength = (String) values.get(0);
if (sLength != null) {
//parse the length into an integer...
}