ProgressBar is not functioning in android activity - android

I am using progressbar in simple login application.But the progress bar is not showing .Sometimes when i change the position of the progressbar is shows before the calling progressbar.show();
here is My XML code
<ProgressBar
android:id="#+id/progressBar"
android:indeterminateDrawable="#drawable/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible"
>
</ProgressBar>
In onCreate() method:
progressBar= (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
In button oncliklistener
btn_login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
uid=usrusr.getText().toString().trim();
upass=pswd.getText().toString().trim();
try {
progressBar.setVisibility(View.VISIBLE);
checkLogin(uid,upass);
progressBar.setVisibility(View.GONE);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
I have tried many other solutions from stackoverflow but none of them worked
Thanks:/

Try the below code.
private ProgressDialog progDailog;
private Button btn_login;
private EditText uid, upass;
private String uid1, upass1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progDailog = new ProgressDialog(this);
progDailog.setTitle("Login");
progDailog.setMessage("Please wait...");
progDailog.setCancelable(false);
btn_login = findViewById(R.id.btn_login);
uid = findViewById(R.id.uid);
upass = findViewById(R.id.upass);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uid1 = uid.getText().toString().trim();
upass1 = upass.getText().toString().trim();
progDailog.show();
checkLogin(uid1, upass1);
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progDailog.dismiss();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
}
});
}
Here 3000 is milliseconds which means 3 seconds, you can change it according to your requirement.
Your XML will be like.
<?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">
<EditText
android:id="#+id/uid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="uid" />
<EditText
android:id="#+id/upass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="upass" />
<Button
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn_login" />
</LinearLayout>
Please try this and let me know if you require any other changes.

Have you considered that your "data processing" code is running on the UI thread, blocking any visible changes. I would suggest trying putting
runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
});
If your progressBar still not showing and nothing helps

Try added code to show the progressBar before calling the api and dismiss the progressBar on response of the request.
Ex.
void checkLogin(String name, String psd){
progressBar.setVisibility(View.VISIBLE);
//start the api call
}
void onApiCallresponse(){
runOnUiThread(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
//code for what you want to do after login
}
});
}

You can show your progress for 3 second like this :
progressBar.setVisibility(View.VISIBLE);
progressBar.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
}
}, 3000) ;
checkLogin(uid,upass);
But it is better to show your progress when you start to check login and invoke api and hide it when you receive a result.

Related

ProgressBar gets dismissed while loading data from FirebaseStorage

I am trying to get a list of images from a folder that I created in my FirebaseStorage bucket. There are total of 20 images and while the app gets all the images, I want to show a ProgressBar. Problem is I don't even see the progressbar before it gets dismissed. I believe this is something related to asynchronous calls that FirebaseStorage uses and I tried to solve it by using AsyncTask but no luck.
private void getBigFlagsFromFirebase() {
bigFlagsList = new ArrayList<>();
progressBar.setVisibility(View.VISIBLE);
if (Utils.isInternetConnectionAvailable(this)) {
FirebaseStorage storage = FirebaseStorage.getInstance("gs://big-quiz-adrien.appspot.com/");
StorageReference storageReference = storage.getReference().child("level1_data/big_flags");
storageReference.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(final ListResult listResult) {
final AtomicInteger filesCount = new AtomicInteger(listResult.getItems().size());
for (final StorageReference file : listResult.getItems()) {
file.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
bigFlagsList.add(uri);
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
Toast.makeText(QuestionActivity.this, "Size: " + bigFlagsList.size(), Toast.LENGTH_SHORT).show(); //this gives me 20
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
Toast.makeText(QuestionActivity.this, "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(QuestionActivity.this, "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Please check your internet connection and try again later.", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Size: " + bigFlagsList.size(), Toast.LENGTH_SHORT).show(); //this gives me 0
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="#f7f7f7"
tools:context=".QuestionsActivity">
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/ads">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/themeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/less_border_radius"
android:backgroundTint="#00B050"
android:gravity="center_horizontal"
android:padding="15dp"
android:text="#string/level_1"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/flagQuestionsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:listitem="#layout/country_questions_item" />
</LinearLayout>
</ScrollView>
<TextView
android:id="#+id/ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#fff"
android:gravity="center_horizontal"
android:padding="15dp"
android:text="Ads Banner"
android:textSize="18sp" />
</RelativeLayout>
So your code seems to be doing the following:
Showing the progress bar.
Adding a success and failure listener for loading your data.
Dismissing the progress bar.
Loading the data is asynchronous, so until the loading succeeds or fails, you want the progress bar to stay displayed, but you're immediately dismissing it after registering the listener. So progressBar.setVisibility(View.GONE) should be inside the onSuccessListener and onFailureListener instead.
[Edit]
The reason your progress bar is dismissed after the first image is loaded is because you aren't waiting for all the images to load. For each result, you're registering a listener, but you dismiss the progress bar right afterwards. You should wait for all the file.getDownloadUri() calls to complete (either by succeeding or failing).
// I'm not sure if these listeners run concurrently and on which threads, so to be safe I'm using an AtomicInteger, feel free to change it to an int if it's thread safe.
final AtomicInteger filesCount = new AtomicInteger(listResult.getItems().size());
for (StorageReference file : listResult.getItems()) {
file.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Do something with the Uri
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
}
}
});
}
You need to do that with FrameLayout as it help you have the progressbar behind the recyclerview so once your image got loaded, the recyclerview will hide
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/flagQuestionsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:listitem="#layout/country_questions_item" />
</FrameLayout>
remove progressBar.setVisibility(View.GONE); line from bottom of funcion, and place when you got success/fail callback:
private void getFilesFromFirebase() {
progressBar.setVisibility(View.VISIBLE);
FirebaseStorage storage = FirebaseStorage.getInstance("gs://big-quiz-adrien.appspot.com/");
StorageReference storageReference = storage.getReference().child("level1_data/small_flags");
storageReference.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(final ListResult listResult) {
progressBar.setVisibility(View.GONE);
for (StorageReference file : listResult.getItems()) {
file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
smallFlagsList.add(uri);
Toast.makeText(QuestionsActivity.this, "Size: " + smallFlagsList.size(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
}
});
}
and also you should maintain the sequence of view based on which view will render on top and which are behind.
Last view will be on top of all view, if no view contain elevation.

Progressbar won't appear on ImageView

I wonder if I'm doing anything wrong. My code is pretty straight forward and would like an example of how you guys made it work if you have a progress bar to load an image in any of your apps, thanks! I'm using volley's imageloader and the progress bar never ever appears
holder.mProgressBar.setVisibility(View.VISIBLE);
if (video.thumbnail != null) {
mImageLoader.get(video.thumbnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.mProgressBar.setVisibility(View.GONE);
holder.mScreenShot.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
holder.mProgressBar.setVisibility(View.GONE);
}
});
}
My XML
<RelativeLayout
android:id="#+id/image_load"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:background="#android:color/darker_gray"
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="#dimen/album_cover_height"
android:clickable="true"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:scaleType="fitXY" />
<ProgressBar
android:visibility="gone"
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Definitely a timing issue. I replicated your scenario as best as I could.
public class MainActivity extends AppCompatActivity {
ImageView image;
ProgressBar pb;
public String url;
public ImageLoader imageLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
pb = (ProgressBar) findViewById(R.id.pb);
RequestQueue queue = Volley.newRequestQueue(this);
url = "http://www.hrwiki.org/w/images/thumb/d/d5/currentbad.png/180px-currentbad.png";
imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
show();
new testTask().execute(imageLoader);
}
public void show() {
image.setVisibility(View.INVISIBLE);
pb.setVisibility(View.VISIBLE);
}
public void hide() {
image.setVisibility(View.VISIBLE);
pb.setVisibility(View.INVISIBLE);
}
private class testTask extends AsyncTask<ImageLoader, Void, Void> {
#Override
protected Void doInBackground(ImageLoader... params) {
SystemClock.sleep(5000);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
hide();
image.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
}
With this layout file:
<FrameLayout
android:layout_width="100dp"
android:layout_height="100dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
android:id="#+id/image" />
<ProgressBar
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:id="#+id/pb"/>
</FrameLayout>
I saw the same behavior until I put the aSync task in which basically waits for 5 seconds before loading the image. This definitely shows that OnResponse is getting called so quickly that you aren't seeing the progress bar.
Looks like Michelle's answer has what you would look for to implement some pre-check logic.
Refer to this previous question for a detailed explanation for how onResponse(ImageLoader.ImageContainer response, boolean isImmediate) is working.
Volley, How many times the onResponse in ImageLoader.ImageListener called
I believe it is basically just immediately turning off your progress bar. Haven't done this particular thing before but based on the other question I think you want to add a check for:
if(!isImmediate)
holder.mProgressBar.setVisibility(View.GONE);

android:onClick doesnot work

I am using navigation drawer in activity like this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_registration);
FrameLayout contentFrameLayout=(FrameLayout)findViewById(R.id.contentView);
getLayoutInflater().inflate(R.layout.activity_registration,contentFrameLayout);
register=(Button)findViewById(R.id.register);
rname=(EditText)findViewById(R.id.name);
rmobile=(EditText)findViewById(R.id.mobile);
remail=(EditText)findViewById(R.id.email);
rpassword=(EditText)findViewById(R.id.password);
}
public void register(View v)
{
new DoRegistration().execute();
}
public class DoRegistration extends AsyncTask<Void,Void,Void>
{
JSONObject registrationResult;
#Override
protected Void doInBackground(Void... voids)
{
List<Pair> param=new ArrayList<>();
param.add(new Pair("R_name",rname.getText().toString()));
param.add(new Pair("R_mobile",rmobile.getText().toString()));
param.add(new Pair("R_email",remail.getText().toString()));
param.add(new Pair("R_password",rpassword.getText().toString()));
registrationResult=serviceHelper.Registration(param);
return null;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
register.setEnabled(false);
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
register.setEnabled(true);
if(registrationResult!=null) {
try {
if (registrationResult.getString("status").equals("done")) {
Intent LoginIntent = new Intent(Registration.this, Login.class);
LoginIntent.putExtra("Msg", "Registered Successfully.. Login Now");
startActivity(LoginIntent);
} else {
}
} catch (Exception e) {
}
}
}
}
So onclick doesnot work.now how to access setContentView.
when register detail error occure could not find onclick method.
activity_registration
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="top|center">
<Button
android:id="#+id/register"
android:layout_width="190dp"
android:layout_height="50dp"
android:text="#string/reg"
android:textSize="20sp"
style="#style/button"
android:background="#drawable/button"
android:onClick="register"
/>
</LinearLayout>
why this error occure.
Try to add a listener to the registration button , and remove the onclick trigger from the layout.
View rootView = inflater.inflate(R.layout.activity_registration,contentFrameLayout);
register = (Button) rootView.findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DoRegistration().execute();
}
});

Horizontal progress bar does not update its status

I am trying to show horizontal progress bar "Not ProgressDialog" on my activity like this
here is what my xml file contains
<ProgressBar
android:id="#+id/pdialog"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
I am trying to update its status using AsyncTask Class by setting pdialog.setProgress() but its not showing any progress, it works with progressdialog but not with horizontal progress bar.
public class MainActivity extends Activity {
private SQLiteDatabase db;
private Cursor cursor;
private ProgressBar pdialog;
private ImageButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
btn = (ImageButton) findViewById(R.id.startbtn);
pbar = (ProgressBar) findViewById(R.id.progressBar1);
pdialog = (ProgressBar) findViewById(R.id.pdialog);
pdialog.setMax(100);
pdialog.setProgress(20);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdialog.setVisibility(View.VISIBLE);
new DownloadFilesTask().execute();
}
});
}
private class DownloadFilesTask extends AsyncTask<Void, Integer, Integer> {
int load = 1;
protected Integer doInBackground(Void... params) {
try {
load = 10 * i;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pdialog.setProgress(load);
}
});
}
} catch (Exception e) {
}
}
protected void onProgressUpdate(Integer... progress) {
if (progress[0] == 100) {
pdialog.setVisibility(View.INVISIBLE);
}
}
protected void onPostExecute(Integer params) {
}
}
}
If load variable gets changed correctly:
Instead of this:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
pdialog.setProgress(load);
}
});
You could use:
publishProgress(load);
which would automatically call on UI Thread:
protected void onProgressUpdate(Integer... progress) {
int p = progress[0];
if (p >= 100) {
pdialog.setVisibility(View.INVISIBLE);
}else{
pdialog.setProgress(p);
}
}
UPDATE:
remove android:indeterminate="true" as pointed out in other answer.
In your layout file please remove the following attribute android:indeterminate="true" from ProgressBar element.
I had the same question, but
I found the problem is the interface View.OnClickListener().
When the pbar was put out of the btn.setOnClickListener(new View.OnClickListener() {}), it worked well. Otherwise, it did not update.
Then, I made a constructor which passed the pbar into the OnXXXClickListener.
private class OnXXXClickListener implements View.OnClickListener() {
private ProgressBar bar;
public OnXXXClickListener(ProgressBar bar) {
this.bar = bar;
}
#Override
public void onClick(View v) {
bar.setProgess(50);
new DownloadFilesTask().execute();
}
}
Then the pbar could work well.

progressBar and refresh webview combination android

EDIT:
I am using a ProgressBar for a Webview that works fine. Now I want to refresh my Webview, which also works. When I am trying to combine them, the Spinner doesn't end at all. This is my code:
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
//Toast.makeText(WebcamsScreen.this,"in runnable",Toast.LENGTH_SHORT).show();
doRefreshingStuff(id);
WebcamsScreen.this.mHandler.postDelayed(m_Runnable, 20000);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialitions
doRefreshingStuff(id);
this.mHandler = new Handler();
this.mHandler.postDelayed(m_Runnable,20000);
doRefreshingStuff(id);
}
public void doRefreshingStuff(String id){
setContentView(R.layout.web4);
webView7 = (WebView) findViewById(R.id.web_4_1);
webView7.getSettings().setJavaScriptEnabled(true);
webView7.getSettings().setJavaScriptEnabled(true);
progressBar = ProgressDialog.show(WebcamsScreen.this, "example", "...");
url="my url";
webView7.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url1) {
view.loadUrl(url1);
return true;
}
public void onPageFinished(WebView view, String url1) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView7.loadUrl(url);
what must I change?
It looks like you are refreshing your WebView every 20 seconds and popping up a new progress dialog when you do. Your code assumes that the old progress dialog has already been dismissed. If it hasn't, then the progress dialog just became orphaned and will remain on display forever. You can probably fix this by inserting this code:
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
}
just before the line progressBar = ....
But I wouldn't fix your code that way. You are doing a huge amount of work that you don't need to do. (For instance, you don't need to reload the same content view.) Here's my revised version:
private final Runnable m_Runnable = new Runnable() {
public void run() {
doRefreshingStuff(id);
mHandler.postDelayed(m_Runnable, 20000);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialitions
setContentView(R.layout.web4);
webView7 = (WebView) findViewById(R.id.web_4_1);
webView7.getSettings().setJavaScriptEnabled(true);
webView7.getSettings().setJavaScriptEnabled(true);
webView7.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (!mProgressBar.isShowing()) {
mProgressBar.show();
}
}
public void onPageFinished(WebView view, String url1) {
if (mProgressBar.isShowing()) {
mProgressBar.dismiss();
}
}
});
mProgressBar = new ProgressDialog(this);
mProgressBar.setTitle("example");
mProgressBar.setMessage("...");
mHandler = new Handler();
}
protected void onResume() {
super.onResume();
mHandler.post(m_Runnable);
}
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(m_Runnable);
}
public void doRefreshingStuff(String id) {
url="my url";
webView7.loadUrl(url);
}
Note that I moved the starting of the page loading loop to onResume() and kill the looping in onPause(). You may want slightly different logic, but you should definitely stop looping somehow when your activity pauses or finishes.

Categories

Resources