show and hide dialog in android studio - java

I am having a situation that my dialog doesn't show up in my asyncTask.
The codes below are my asyncTask
private class AsyncCallListWS extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
Log.i(TAG, "--------------------------------------------------");
Log.i(TAG, "pending ws: onPreExecute");
showLoadingDialog();
}
#Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "pending ws: doInBackground");
//listDataParent = new ArrayList<Tn_Parent>();
listPending();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i(TAG, "Call pending ws: onPostExecute");
dismissLoadingDialog();
//Log.i(TAG, "I am not up there "+status.toString());
if(getContext()!=null) {
//adapter = new Tn_ListViewAdapter(getActivity(), newList, selectAll);
//listView.setAdapter(adapter);
lvAdapter = new Tn_ListViewAdapter(getActivity(), lvList, selectAll);
listView.setAdapter(lvAdapter);
// .............. below is not needed .....................
//listAdapter = new Tn_ExpandableAdapter(listDataParent,getContext(), selectAll);
//expListView.setAdapter(listAdapter);
}
}
}
And below is my dialogbox codes. The dialog work well in other class.
public void showLoadingDialog() {
if (bar == null) {
bar = new ProgressDialog(getActivity());
bar.setMessage(getString(R.string.loading_message));
//bar.setCanceledOnTouchOutside(getRetainInstance());
bar.setCanceledOnTouchOutside(false);
}
bar.show();
}
public void dismissLoadingDialog() {
if (bar != null && bar.isShowing()) {
bar.dismiss();
}
}
I really wish to know what are the problems. The dialog show up when I put showLoadingDialog() in the onCreateView(), but the problem is that the dialog will not dismiss if i put it inside the onCreateView(). Please help.

For your dismiss() problem inside onCreate, try to change
public void dismissLoadingDialog() {
if (bar != null && bar.isShowing()) {
bar.dismiss();
}
}
to
public void dismissLoadingDialog() {
if (bar != null) {
bar.dismiss();
bar = null;
}
}
The problem to not showing up your dialog inside AsynTask might be your if (bar == null) { condition, because at that time your bar object will not be null. So that the time when you are dismissing the dialog you have to initialize it to null. And please write bar.show(); this line of code inside if(...) condition.

As Preetika Kaur suggested you should pass a Context object to you showLoadingDialog() and call bar = new ProgressDialog(yourContextObject); cause otherwise the bar would always be null.

Related

How to mimic AsyncTask for displaying a loading dialog in Android?

I've seen some of the answers to similar questions on here but they aren't working for me.
What I want to do is start a Thread and run some code in it, but before I start the thread, I want to display a loading dialog, and as soon as the thread is finished running, close the loading dialog.
So something like this:
LoadingDialog dialog = new LoadingDialog(MainActivity.this);
class MyThread {
...
void send() {
dialog.displayDialog();
// DO THINGS HERE
new Thread((Runnable) () -> {
try{
...
} catch (...) {
}
}).start();
// Close the dialog with dialog.closeDialog();
}
}
(displayDialog() and closeDialog() are just methods I created in my LoadingDialog class to start and dismiss the dialogs)
I'm not sure exactly how to do this, I've seen some uses of handler on this site but they're all different and not working for me so I'm a little stuck.
Thanks
Solution
public class MainActivity extends AppCompatActivity {
LoadingDialog dialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new LoadingDialog(MainActivity.this);
MyThread myThread = new MyThread(MainActivity.this);
myThread.start();
}
static class MyThread extends Thread {
private WeakReference<MainActivity> activityRef;
public MyThread(MainActivity activity) {
activityRef = new WeakReference<>(activity);
}
#Override
public void run() {
send();
}
void send() {
// Display dialog
if (getActivity() != null) {
getActivity().dialog.displayDialog();
}
// DO THINGS HERE
// TODO: Write your code that execute in a background here
// Close dialog
if (getActivity() != null) {
getActivity().dialog.closeDialog();
}
}
private MainActivity getActivity() {
return activityRef.get();
}
}
}

Progress Dialog: android.view.WindowLeaked: has leaked window DecorView#6995336[] that was originally added here

I tried to change the orientation of my device on recycler view but it always crashes when progress dialog shows up.
How to solve this?
Here is my code:
private class LoadOrdersListAgent extends AsyncTask {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OrdersActivity.this);
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders_agent);
emptytv = findViewById(R.id.empty_view_orders_agent);
emptytv.setVisibility(View.GONE);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
rvor.setItemAnimator(new DefaultItemAnimator());
dialog.setMessage("Loading....");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
final OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
srl.setRefreshing(false);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (ordersList.isEmpty()) {
Log.d("TESTING.....", "LIST OF ORDERS ----->" + ordersList);
rvor.setVisibility(View.GONE);
srl.setVisibility(View.GONE);
emptytv.setVisibility(View.VISIBLE);
} else {
rvor.setVisibility(View.VISIBLE);
srl.setVisibility(View.VISIBLE);
emptytv.setVisibility(View.GONE);
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
ordersList = OrdersApi.getOrders(url, key);
return null;
}
}
private void swipeOrderLayout() {
srl = findViewById(R.id.swipe);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
new LoadOrdersListAgent().execute();
// new LoadOrdersListAdmin().execute();
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
srl.setRefreshing(false);
}
});
}
I got this error when i was Finishing/Destroying the activity without Dismissing progress Dialogue.
Solution use dialog.dismiss(); to dismiss the progress dialogue before destroying or pausing the activity
in your case remove the if condition and just call dialog.dismiss(); in postExecute method
Declare your ProgressDialog in Global using :
Add this code above onCreate() :
private ProgressDialog dialog;
Add this code within a onCreate():
dialog = new ProgressDialog(OrdersActivity.this);
dialog.setMessage("Loading....");
dialog.show();
Add this code within as onPreExecute method ,
if (!dialog.isShowing()) {
dialog.show();
}

Android AsyncTask: when it starts?

I'm doing background things using AsyncTask. I have been knowing that operations are just executed parallelly in AsyncTask however don't know about when it starts.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lec_refer_room);
String subCode = null;
try{
System.out.println(subCode);
}catch(Exception e){
finish();
}
new GetRefer(subCode, page).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// this is AsyncTask
}
I tried to finish activity when string subCode is null. However above code occurs exception in GetRefer().executeOnExecutor()
Does AsyncTask starts along with main thread?
Then how can I use try-catch with AsycTask?
I've created a sample to show to you how AsyncTask works hope it what you was asking for
public class TaskTest extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... params) {
Boolean StringNull = false;
String subCode = params[0];
if (subCode == null){
StringNull = true;
}
return StringNull;
}
protected void onPostExecute(Boolean result) {
if (!result) {
System.out.println(subCode);
} else {
finish();
}
}
}
To execute it you have to do as follows :
TastkTest tasktest = new TaskTest();
tasktest.execute(subCode);
Edit (Final Code)
Inside of your onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lec_refer_room);
String subCode = null;
TastkTest tasktest = new TaskTest();
tasktest.execute(subCode);
}
The InnerClass still the same.
Edit2
If you want to put it on onCreate() do as follows...
String subCode = null;
if(subCode==null){
finish();
}
You could call finish () in your onCreate() but it's not something you probably want to do as the user would have no idea why the Activity didn't start.
This article will help explain the way AsyncTask works: http://hiqes.com/androids-asynctask-explained/

Progress dialog async task taking longer time than expected

I am new to android programming. I am developing a web crawler for which i am using a Async Task and it is working well.In order to keep user informed,i am using progress dialog. My problem is,if i use a Progress Dialog my program takes more time to execute and when i won`t use the progress dialog,it executes faster.
Done Work
OnCreate Method
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
Intent intent = getIntent();
s1 = intent.getStringExtra("Number1");
s2 = intent.getStringExtra("Number2");
s3=intent.getIntExtra("selectedItem",0);
HttpAsyncTask asyncTask = new HttpAsyncTask();
asyncTask.execute();
}catch (Exception e)
{
messageBox("Exception",e.getMessage());
}
}
Async Task Class
private class HttpAsyncTask extends AsyncTask<List<String>, Integer, List<String>> {
private ProgressDialog dialog;
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(Results.this);
dialog.setIndeterminate(true);
dialog.setMessage("Please Wait");
dialog.setCancelable(true);
dialog.show();
super.onPreExecute();
}
#Override
protected List<String> doInBackground(List<String>... urls) {
//android.os.Debug.waitForDebugger();
// spinner.setVisibility(View.VISIBLE);
List<String>resultList=new ArrayList<String>();
try
{
if(isCancelled())
return resultList;
resultList=WebCrawlerClass.GetPost(s1,s2,s3);
}catch (Exception e)
{
messageBoxs("Error", e.getMessage());
}
return resultList;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(List<String> result)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
if(s3 == 2)
{
docListAdapter=new ListViewData(Results.this,result);
}
else {
docListAdapter = new NameNumListData(Results.this, result);
}
docList=(ListView)findViewById(R.id.listView2);
docList.setAdapter(docListAdapter);
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
Am I missing something? Need help..
Thanks and Regards,
Abhinav
In you activity
// Start the progress dialog
..
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// dismiss the progress dialog
}
};
HttpAsyncTask asyncTask = new HttpAsyncTask(handler);
asyncTask.execute();
In your asynctask class
private class HttpAsyncTask extends AsyncTask<List<String>, Integer, List<String>> {
private Handler handler = null;
public HttpAsyncTask (Handler handler) {
this.handler = handler;
}
protected Void doInBackground(Void... params) {
//Perform your task
// When you know that task is finished , fire following code
if (null != handler) {
Message message = handler.obtainMessage();
message.obj = Any data you want to sent to the activity
message.what = 1 ; ( Optional )
handler.sendMessage(message);
}
}
Thus when sendMessage function is called from doInbackground.. your handleMessage in your activity will get triggered and then you should dismiss the progress dialog
Hope this will improve the performance issue what you are facing
Remove super.onPreExecute(); in onPreExecute() method and check .It might Help

Activity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#46029dd0

I am developing an feedback kind of application, when I click the "submitnow" button I am getting the following error
Activity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView#46029dd0
Following is my code, please help me out.
public class SignOut_Activity extends SherlockActivity implements
OnClickListener {
Button btnSubmitNow, btnSubmitLater;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.signout);
((TextView) findViewById(R.id.tvSubTitle))
.setText(StoresListAdapter.StoreName);
btnSubmitNow = (Button) findViewById(R.id.btnSubmitNow);
btnSubmitLater = (Button) findViewById(R.id.btnSubmitLater);
btnSubmitNow.setOnClickListener(this);
btnSubmitLater.setOnClickListener(this);
progressDialog = new ProgressDialog(SignOut_Activity.this);
progressDialog.setMessage("Uploading data, please wait...");
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; finish activity to go home
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
// Set title
getSupportActionBar().setTitle("Sign Out");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmitNow:
// Submit now
// Sample upload image
UploadImage.uploadImage("testimage");
new AsyncTask<Void, Void, Void>() {
// called before execution // main/UI thread
protected void onPreExecute() {
progressDialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Submit the store data
StoreData.postData(StoreList_Activity.storesList
.get(StoresListAdapter.Position));
return null;
}
// on store data uploaded // main/UI thread
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setSignOut();
StoreList_Activity.storesList
.get(StoresListAdapter.Position).isSubmitted = true;
SignOut_Activity.this.finish();
};
}.execute();
break;
case R.id.btnSubmitLater:
// Submit later
setSignOut();
StoreList_Activity.storesList.get(StoresListAdapter.Position).isSubmitLater = true;
VisitOps_Activity.isSubmitLater = true;
SignOut_Activity.this.finish();
break;
default:
break;
}
}
#SuppressLint("SimpleDateFormat")
private void setSignOut() {
VisitOp visitOp10 = new VisitOp();
visitOp10.setName("Sign Out");
visitOp10.setStatus("");
SampleData.visitOpsList.add(visitOp10);
if (VisitOps_Activity.VisitOps.SignOut == null)
VisitOps_Activity.VisitOps.SignOut = new SignOut();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
VisitOps_Activity.VisitOps.SignOut.SignOutTime = "Out: "
+ currentDateandTime;
}
}
Leak comes because you are keeping reference of activity after it destroyed also so use
if(progressDialog !=null)
{
progressDialog = null;
}
progressDialog = new ProgressDialog(this.getApplicationContext());
progressDialog.setMessage("Uploading data, please wait...");
OR
use this it will help
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmitNow:
// Submit now
// Sample upload image
UploadImage.uploadImage("testimage");
new AsyncTask<Void, Void, Void>() {
// called before execution // main/UI thread
protected void onPreExecute() {
progressDialog = new ProgressDialog(SignOut_Activity.this);
progressDialog.setMessage("Uploading data, please wait...");
progressDialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Submit the store data
StoreData.postData(StoreList_Activity.storesList
.get(StoresListAdapter.Position));
return null;
}
// on store data uploaded // main/UI thread
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setSignOut();
StoreList_Activity.storesList
.get(StoresListAdapter.Position).isSubmitted = true;
SignOut_Activity.this.finish();
};
}.execute();
Why this Error...?
this error happen when you keep reference of unused activity
Solution
remove reference of progress bar , dialog .....etc after use it .
by dismiss them or make them equal null
you can approach this when no longer need of it
Recommended put it in onStop
#Override
protected void onStop() {
super.onStop();
if(_dialog.isShowing()){
_dialog.dismiss();
}
if(_dialog != null){
_dialog = null;
}
}
Dismiss the dialog after its use, it won't let your application crash.
dialog.dismiss();
use that code progressDialog.dismiss();
Make sure you dismiss() the dialog, after dialog use and before any next background process to be initiated.

Categories