How to finish ProgressDialog from onBackPressed - android

I am using progress bar for showing progress. But when I'm pressing the back button it keep showing progress bar.I don't want it. how to remove it.
My code for calling Progress circle is-
public void onClick(final View v) {
ProgressCircle progressBar = new ProgressCircle();
progressBar.start(v.getContext());
click(v);
if(progressBarStatus==1)
{
progressBar.stop();
}
}
Following is the click(View) method:
Intent intent = new Intent(AddFriend.this, AddFriendSend.class);
startActivity(intent);
Following is the Progress Circle class:
public class ProgressCircle {
private ProgressDialog progressBar;
public void start(Context context) {
ProgressDialog progressBar = new ProgressDialog(context);
progressBar.setCancelable(true);
progressBar.setMessage("Processing...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
public void stop() {
if (progressBar != null) {
progressBar.dismiss();
}
}
}
Please help me out.

In your Activity you override the onBackPressed method like this:
#Override
public void onBackPressed() {
progressBar.stop();
super.onBackPressed();
}

Try to override back button in android as below -
#Override
public void onBackPressed() {
super.onBackPressed();
progressBar.stop();
}
Don't forget to declare progressBar as class member.

No Like this:
ProgressCircle progressBar = null;
public void onClick(final View v) {
progressBar = new ProgressCircle();
progressBar.start(this);
click(v);
if(progressBarStatus==1)
{
progressBar.stop();
}
}
#Override
public void onBackPressed() {
if(progressBar!=null)
progressBar.stop();
else
super.onBackPressed();
}

It was a simple mistake-
we can do this by following code -
ProgressCircle progressBar = null;
public void onClick(final View v) {
progressBar = new ProgressCircle();
progressBar.start(this);
click(v);
if(progressBarStatus==1)
{
progressBar.stop();
}
}
#Override
public void onBackPressed() {
if(progressBar!=null)
progressBar.stop();
else
super.onBackPressed();
}

Related

Reshow a progress dialog from Async Task if it gets dismissed

I have a progress dialog that shows how many files are left for uploading in my Async Task and the user can dismiss this dialog if he wants to. However I want to have a button that will be able to show again that progress dialog at its current stage and I don't know how to do that since you I can't just create a function in the Async Task and call it from a different activity. Any thoughts?
You can make a singleton class to handle the Async Task progress which holds only one listener (the Activity who wants to listen for the progress of your AsyncTask).
Your Singleton class can be like below:
public class ProgressDialogUtil {
public interface ProgressDialogUtilListener{
void showProgressDialog();
void dismissProgressDialog();
void updateProgressDialog(int value);
void setProgressDialogMessage(String message);
}
private ProgressDialogUtilListener listener;
private static ProgressDialogUtil mInstance;
public static ProgressDialogUtil getInstance() {
if (mInstance == null) {
synchronized (ProgressDialogUtil.class) {
if (mInstance == null) {
mInstance = new ProgressDialogUtil();
}
}
}
return mInstance;
}
public void setListener(ProgressDialogUtilListener listener) {
this.listener = listener;
}
public void showProgressDialog(){
if(listener!=null)
listener.showProgressDialog();
}
public void dismissProgressDialog(){
if(listener!=null)
listener.dismissProgressDialog();
}
public void updateProgressDialog(int value){
setProgressDialogMessage("Files Downloaded: "+ value);
if(listener!=null)
listener.updateProgressDialog(value);
}
public void setProgressDialogMessage(String message){
if(listener!=null)
listener.setProgressDialogMessage(message);
}
}
Then you can use this Singleton class (ProgressDialogUtil) in your AsyncTask like below to inform for any update occurred:
public class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {
public final ProgressDialogUtil progressDialogUtil;
public MyAsyncTask(ProgressDialogUtil progressDialogUtil){
this.progressDialogUtil = progressDialogUtil;
}
#MainThread
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialogUtil.setProgressDialogMessage("Start Download files..");
progressDialogUtil.showProgressDialog();
}
#WorkerThread
#Override
protected Boolean doInBackground(Void... params) {
//download your files here in the Background Thread...
//below is a sample loop
for (int i=0; i <= 50; i++) {
try {
Thread.sleep(1000);
publishProgress(i);
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}
return true;
}
#MainThread
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialogUtil.updateProgressDialog(values[0]);
}
#MainThread
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressDialogUtil.setProgressDialogMessage("Finished Download!");
progressDialogUtil.dismissProgressDialog();
}
}
Then in your first Activity where you start the AsyncTask you can create a new instance of your Progress Dialog and set a listener ProgressDialogUtilListener to listen for any AsyncTask progress to show/hide/update the Progress Dialog like below:
ProgressDialog pd = new ProgressDialog(this);
ProgressDialogUtil progressDialogUtil = ProgressDialogUtil.getInstance();
progressDialogUtil.setListener(new ProgressDialogUtil.ProgressDialogUtilListener()
{
#Override
public void showProgressDialog() {
if (!pd.isShowing())
pd.show();
}
#Override
public void dismissProgressDialog() {
if (pd.isShowing())
pd.dismiss();
}
#Override
public void updateProgressDialog(int value) {
pd.setProgress(value);
}
#Override
public void setProgressDialogMessage(String message) {
pd.setMessage(message);
}
});
new MyAsyncTask(progressDialogUtil).execute();
Finally when you navigate to a new Activity you can use the same Singleton Instance ProgressDialogUtil and change the listener to the new Activity now all AsyncTask events will be handled to the new Activity and the dialog can be opened/closed via a button through this singleton class like below:
ProgressDialog pd = new ProgressDialog(this);
ProgressDialogUtil progressDialogUtil = ProgressDialogUtil.getInstance();
progressDialogUtil.setListener(new ProgressDialogUtil.ProgressDialogUtilListener()
{
#Override
public void showProgressDialog() {
if (!pd.isShowing())
pd.show();
}
#Override
public void dismissProgressDialog() {
if (pd.isShowing())
pd.dismiss();
}
#Override
public void updateProgressDialog(int value) {
pd.setProgress(value);
}
#Override
public void setProgressDialogMessage(String message) {
pd.setMessage(message);
}
});
//Show Progress Dialog from a Button Click
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialogUtil.showProgressDialog();
}
});
//Dismiss Progress Dialog from a Button Click
dismissButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialogUtil.dismissProgressDialog();
}
});
You can have a Live data in any singleton class like below to share the progress between activities.
object ProgressHelper {
val progress = MutableLiveData<Int>()
}
Then update the progress values from the AsyncTask like below:
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
ProgressHelper.progress.value = 100
}
In your activity you can observe the progress like below:
ProgressHelper.progress.observe(this, Observer {
val progress = it
})

Android, showProgress() and hideProgress() properly

I'm new on android development, so decided to learn simple login using MVP architectural pattern, in general everything is working fine, as checking user credentials, calling repository...etc.
However, only the implementations of showProgress() & hideProgress() that works in a weird way, for me at least.
Note that the showProgress() only works if the user inter valid credentials.
Thanks.
// Presenter Class
package com.example.mvp.login;
import android.util.Log;
import com.example.mvp.login.LoginContract;
import com.example.mvp.utils.SharedPrefManager;
public class LoginPresenterImpl implements LoginContract.Presenter{
SharedPrefManager sharedPrefManager;
private LoginContract.View view;
private LoginContract.Service service;
public LoginPresenterImpl(LoginContract.View view, LoginContract.Service service) {
this.view = view;
this.service = service;
sharedPrefManager = SharedPrefManager.getInstance(view.getContext());
}
#Override
public void onLoginClicked() {
String username = view.getUsername();
if (username.isEmpty()){
view.showUsernameError();
view.hideProgress();
return;
}
String password = view.getPassword();
if (password.isEmpty()){
view.showPasswordError();
view.hideProgress();
return;
}
view.showProgress(); // this method is called, but doesn't show in the UI Thread
boolean loginSucceeded = service.login(username, password);
if (loginSucceeded){
sharedPrefManager.userLogin(username);
view.navigateHome();
return;
}
view.hideProgress();
view.showLoginError();
}
#Override
public void isUserLoggedIn() {
if(sharedPrefManager.isLoggedIn())
view.navigateHome();
}
}
// View Class
public class LoginActivity extends AppCompatActivity implements LoginContract.View{
private EditText ed_username, ed_password;
private Button login;
private TextView signUp;
private ProgressBar progressBar;
LoginContract.Presenter presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView(this);
presenter = new LoginPresenterImpl(this, new LoignServiceImpl());
presenter.isUserLoggedIn();
login.setOnClickListener(click);
}
View.OnClickListener click = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.login:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
presenter.onLoginClicked();
}
}, 1200);
}
}
};
public void initView(LoginActivity view){
ed_username = view.findViewById(R.id.username);
ed_password = view.findViewById(R.id.password);
login = view.findViewById(R.id.login);
signUp = view.findViewById(R.id.sign_up);
progressBar = view.findViewById(R.id.progressBar);
}
#Override
public String getUsername() {
return ed_username.getText().toString();
}
#Override
public String getPassword() {
return ed_password.getText().toString();
}
#Override
public void showProgress() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void hideProgress() {
progressBar.setVisibility(View.GONE);
}
#Override
public void showUsernameError() {
ed_username.setError("Must not be empty");
}
#Override
public void showPasswordError() {
ed_password.setError("Must not be empty");
}
#Override
public void navigateHome() {
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
}
#Override
public void showLoginError() {
Toast.makeText(this,
"User not Found",
Toast.LENGTH_SHORT).show();
}
#Override
public Context getContext() {
return this;
}
}
Thanks to h4rd4r7c0r3 and Ionut J. Bejan, for highlighting several aspects i wasn't a ware of, in particular Working Thread(UI THREAD) and Another Thread(Background Thread).
Although i don't know yet how to implement them very well, i found way after searching the internet.
The main scenario are:
When the user enter username and password, UI should show indication
(Progress Bar) checking credentialiy of the user, implementing
showProgress().
When the checking is finished, UI should stop the indication.
implementing hideProgress().
An action to be taken based on the result, for example: Navigate to
new Activity or Toast "Wrong Username/Passowrd".
//LoginActivity
#Override
public void showProgress() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void hideProgress() {
progressBar.setVisibility(View.GONE);
}
// LoginPresenter
public void onLoginClicked() {
String username = view.getUsername();
if (username.isEmpty()){
view.showUsernameError();
view.hideProgress();
return;
}
String password = view.getPassword();
if (password.isEmpty()){
view.showPasswordError();
view.hideProgress();
return;
}
view.showProgress();
service.login(username,password, this);
}
#Override
public void isUserLoggedIn() {
if(sharedPrefManager.isLoggedIn())
view.navigateHome();
}
// implementing onFinished from FinishedListiner interface, to capture the result
#Override
public void onFinished(boolean bool) {
view.hideProgress();
if (bool){
sharedPrefManager.userLogin(view.getUsername());
view.navigateHome();
return;
}
view.showLoginError();
}
// Service, which will connect to the datasource
public class LoginServiceImpl implements LoginContract.Service {
UserRepository userRepository;
#Override
public void login(final String username, final String password, final FinishedListiner listener) {
userRepository = UserRepositoryImpl.getInstance();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// The method which will be used in the presenter class.
listener.onFinished(userRepository.checkUser(username, password));
}
}, 1200);
}
Try this below snippet :
Step 1:- Create BaseActivity extend to AppCompactActivity
Step 2:-Setting BaseActivity as per your requirement
Step 3:-Create Instance of your Progress Dialog
Step 4:-Create function showProgress()
Like:-
private fun showProgress(){
if(!progress.isShowing){
progress.show()
}
}
Step 5:- Create function HideProgress()
Like:-
private fun hideProgress(){
if(progress.isShowing){
progress.dismiss()
}
}
And use as per your requirement.
Your View just run presenter on another thread. See your Handler. Then it update the view and can not access to the UI. To fix this, just make sure your showProgress() is doing work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
//show your proress here.
}
});

Unity Ads 3.0.0 show banner ads in Android

I want to show Unity banner ads (Unity ads 3.0.0) for my Java Android app.
I have read https://unityads.unity3d.com/help/android/integration-guide-android
According to the guide lines the following code has to be added to get banner ads.
public class UnityBannerExample extends Activity {
private View bannerView;
private Button bannerButton;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.unityads_example_layout);
final Activity myActivity = this;
final IUnityBannerListener unityBannerListener = new UnityBannerListener ();
final IUnityMonetizationListener unityMonetizationListener = new UnityMonetizationListener ();
UnityBanners.setBannerListener (unityBannerListener);
bannerButton = (Button) findViewById (R.id.unityads_example_banner_button);
bannerButton.setEnabled (true);
bannerButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick (View v) {
if (bannerView == null) {
UnityBanners.loadBanner (myActivity, "banner");
} else {
UnityBanners.destroy ();
}
}
});
final Button initializeButton = (Button) findViewById (R.id.unityads_example_initialize_button);
initializeButton.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick (View v) {
UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
}
});
}
private class UnityBannerListener implements IUnityBannerListener {
#Override
public void onUnityBannerLoaded (String placementId, View view) {
bannerView = view;
((ViewGroup) findViewById (R.id.unityads_example_layout_root)).addView (view);
}
#Override
public void onUnityBannerUnloaded (String placementId) {
bannerView = null;
}
#Override
public void onUnityBannerShow (String placementId) {
}
#Override
public void onUnityBannerClick (String placementId) {
}
#Override
public void onUnityBannerHide (String placementId) {
}
#Override
public void onUnityBannerError (String message) {
}
}
private class UnityMonetizationListener implements IUnityMonetizationListener {
#Override
public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
}
#Override
public void onPlacementContentStateChange (String placementId, PlacementContent placementContent, UnityMonetization.PlacementContentState previousState, UnityMonetization.PlacementContentState newState) {
}
#Override
public void onUnityServicesError (UnityServices.UnityServicesError error, String message) {
}
}
}
There are two buttons bannerButton and initializeButton.
But I don't want to show buttons to the user to initialize and show the banner ad. I want to show the ads in the on start method of the activity.
What is the proper way to show the banner ads without bannerButton and initializeButton.
You can just use OnResume method of your activity:
#Override
protected void onResume() {
....
....
UnityMonetization.initialize (myActivity, "1234567", unityMonetizationListener, true);
if (bannerView != null) {
UnityBanners.destroy ();
}
UnityBanners.loadBanner (myActivity, "banner");
}
But it is not the end. You should also take care about Banner visibility and refresh.
#Override
public void onPlacementContentReady (String placementId, PlacementContent placementContent) {
UnityBanners.loadBanner (myActivity, "banner");
}

when click button, while connected wifi, show progress dialog on android

recently, When clicking the button WI-FI connect.
but I want during connecting , showing progress dialog
How can I do ?
protected final ScanResult mScanResult;
private OnClickListener mConnectOnClick = new OnClickListener() {
#Override
public void onClick(View v) {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean connResult = false;
if (config != null) {
connResult = Wifi.connectToConfiguredNetwork(mFloating, mWifiManager, config, false);
// I Think this part progress dialog.
}
if (!connResult) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
mFloating.finish();
if finish connect wifi,
I want stop progress dialog
thanks.
For this you can use async task
class WIFIConfigurationTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
protected final ScanResult mScanResult;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Your_Activity.this);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.setMessage(Constant.KEY_PLEASE_WAIT);
dialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
//Background Task
}
#Override
protected void onPostExecute(Boolean response) {
try {
super.onPostExecute(response);
if (isCancelled())
return;
dialog.dismiss();
private OnClickListener mConnectOnClick = new OnClickListener() {
#Override
public void onClick(View v) {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean connResult = false;
if (config != null) {
connResult = Wifi.connectToConfiguredNetwork(mFloating, mWifiManager, config, false);
// I Think this part progress dialog.
}
if (!connResult) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
mFloating.finish();
}
}
May it work.(Not Tested)

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.

Categories

Resources