Android - displaying alert dialog during doinbackground while catching exception - android

I have this code and it goes to catch as soon as it hits Source.httpConn and it sends the exception down below to catch.
try
{
JSONTokener sbTokener = new JSONTokener(Source.httpConn(infoUrlStr, Main.this).toString());
//array için hazırlandı
JSONArray jArray=new JSONArray(sbTokener);
//arraye eklendi
for(int i=0; i<(jArray.length()); i++)
.
.
.
}
Down in the catch part there is my alert dialog method. It normally works pretty well but I suspect that I have the problem because of the doInBackground. The application crashes before displaying the below alert dialog. All the try-catch is in my doInBackground method in ASyncTask.
catch (Exception e) {
AlertDialogDisp(Main.this, noServ, noServLog);
}
How can I make my application NOT crash and just display this alert dialog and then return to my Main activity as it was. Here is my alert dialog method:
protected void AlertDialogDisp(Context dialogContext, String head, String log) {
new AlertDialog.Builder(dialogContext)
.setTitle(head)
.setMessage(log)
.setPositiveButton("okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// On Alert Dialog Button
dialog.dismiss();
}
})
.show();
}

You cannot update ui from doInbackground. doInbackground is invoked on a backgroudn thread. Ui should be updated on the ui thread. Return result in doInbackground and update ui in onPostExecute
For more info check the docs
http://developer.android.com/reference/android/os/AsyncTask.html
You can also use runOnUithread which is a method of activity class
runOnUiThread(new Runnable(){
public void run() {
// dispaly dialog here
// no network related operation here
}
});

Show your dialog in runOnUiThead which is a method of activity class.
runOnUiThread(new Runnable(){
public void run() {
//write your alert dialog code here
}
});

Related

Handle with AlertDialog into the doInBackground

I am trying to call AlertDialog into AsyncTask. I wrote this code and it works, but when I choose item in the AlertDialog and then call uiHandler.getLooper().quit(); to continue code proccesing, AlertDialog is freezes (doesnt closing, staying until activity finishes) but backgroundUI continue proccesing. I think it's because AlertDialog has no time to perform dismiss() method before infinity loop is ending. Please, help me to solve this problem. I need to do this only in doInBackground method.
#Override
protected Void doInBackground(Void... arg0) {
Looper.prepare();
final Handler uiHandler = new Handler();
uiHandler.post(new Runnable() {
public void run() {
AlertDialog.Builder chooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("Choose")
.setCancelable(false)
.setItems(faculties, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
uiHandler.getLooper().quit();
}
})
.create()
.show();
}
});
Looper.loop();
}
PS: It's not full code for easier reading.
You have to run you alert before the doInBackground (onPreExecute) and dismiss your dialog after it (onPostExecute)
Technically, It is not passible to do UI related task in doInBackground() method on Asyntask. You have to use onPostExecute()/onPreExecute() of Asyntask for showing AlertDialog.

Why doesnt Android Dialog show on UI when called before ParseQuery.find

I am using Parse in my android app and want to block the UI with a dialog while the query runs to get the data. I first create and show a dialog and then do the ParseQuery.find(). However, the dialog never shows up on the UI. Am I missing something?
//Show Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Some Title...")
.setMessage("Please wait...")
.setCancelable(false);
dialog = builder.create();
dialog.show();
List<ParseObject> objects;
try {
objects = query.find();
//read is successful
if (objects != null && objects.size() > 0) {
...........
........
dialog.cancel();
......................
Yes unfortunately you are missing something.
I am assuming that you are calling your code on the main thread, first dialog.show() and then doing query.find() after that.
Your problem is that you are (probably) doing all this work on the main thread, and the dialog will not show until the main thread has time to parse your .show() command. But since you are blocking the main thread by doing query.find() it won't show until that code has finished executing.
You should solve this problem by doing your query on the background thread, e.g. using AsyncTask, Thread, or some other method.
Let me show you how to do it using thread.
public class MainActivity extends Activity {
AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Show Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Some Title...").setMessage("Please wait...").setCancelable(false);
dialog = builder.create();
dialog.show();
new Thread() {
public void run() {
// Do you heavy lifting
List<ParseObject> objects;
try {
objects = query.find();
// read is successful
if (objects != null && objects.size() > 0) {
}
} catch (Exception e) {
}
// Since we are in a thread you need to post the cancel on the
// main thread, otherwise you'll be in trouble.
runOnUiThread(new Runnable() {
public void run() {
dialog.cancel();
}
});
}
}.start();
}
}
Hopefully you'll find my answer helpful!
Best Regards,
Erik

Android AsyncTask Dialog Alert

I have a splash screen which check an URL if there's any new content on the server. If show i wish to show a AlertDialog, to the app user so that depending on the action of user,i.e if YES download new contents from the server and get it to database else if NO load the contents for the app from the server.
However i am not being able to use an alert dialog inside AsyncTask
My snippet code is as:
protected String doInBackground(String... mode){
/* I AM QUERY MY DATABASE FOR THE PREVIOUS CONTENT(SAY CONTENT 1, CONTENT 2);
* then i start my connection to the server which has an xml file with the content
* info (say content 3), at this stage .
* i Check certain condition here,
* say if result ==0 then i wish to display an alertdialog.
* I used an alert dialog and i get some error. Stating use Looper or Handler.
* Can anyone help me with this?
*/
}
Edited
So in
doInBackGround(String... mode){
if(result==0){
// how do i implement this alert show that if the dialog appears and on clicking Yes i wish to exectute the URL handling part below
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Updates Found");
alert.setMessage( "New Updates for has been found.\n Would you like to download ?\n"
+ "Whats the update: Checking "+pld.result.get(i).get( "issue" ));
alert.setIcon(android.R.drawable.ic_dialog_info);
alert.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
URL url = new URL(pld.result.get(i).get("link"));
ManageZipFile.getArchive(url,pld.result.get(i).get("issue"), file);
}
catch (Exception ex) {
Log.d(TAG, "Exception from URL"+ ex.getMessage());
}
progressState += updateProgressBar(20);
pld.saveCoverData(pld.result.get(i).get("issue"));
try {
pldContent = new PullLoadData(getString(R.string.files_path)
+ pld.result.get(i).get("issue")
+ "/contents.xml",context);
pldContent.getNewsItems();
progressState += updateProgressBar(20);
}
catch(XmlPullParserException e) {
Log.e(TAG, "GetNEWSITEM "+ e.getMessage());
}
catch (IOException e) {
Log.e(TAG, "XML FIle not found" + e.getMessage());
}
}
});
alert.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
AlertDialog showAlert = alert.create();
showAlert.show();
}
}
This is because the method doInBackground runs on a non-UI thread, and an AlertDialog needs to be displayed on the UI-thread.
To solve your problem, move the code for your AlertDialog to the method onProgressUpdate in AsyncTask, then when you want to display the Dialog call publishProgress() from doInBackground
protected String doInBackground( String... mode ) {
if( something )
//Conditions for showing a Dialog has been met
}
protected void onProgressUpdate( Void... params ) {
//Show your dialog.
}
If you need to pass some kind of variable/data to the dialog, you can pass the kind of data you declared in extends AsyncTask<Params, Progress, Result> - where Progress is the type of parameter you can pass via the publishProgress( myVariable )-method.
UI thread means it is associated directly with your UI.you cant do operations like network datafetch,disk access etc which require large processing time in your UI thread. They should be done in seperate thread.
AsyncTask helps to carry out theese operations in seperate thread which may otherwise results in infamous ANR error.(application not responding).
AsyncTask contain methods like onPreExecute() onPostExecute() onProgressUpdate() ,doInBackground ()etc you can access UI thread from onPreExecute() onPostExecute() onProgressUpdate() .The operation requiring longer processing time should be carried out in doinbackground().
I can't understand the functionality demands from your question but if you want to display Alert Dialog before data fetching operation,Display it from onPreExecute()
or if you want to display after data fetch Do it from onPostExecute().

ProgressDialog communicate with AsyncTask in android

Tips or ideas on how ProgressDialog can communicate with asyncTask.
For example when I click the button, the program will validate the input to internet, This is should not be interupted. so I use ProgressDialog.
After progressDialog.dismiss(), I need to refresh the view by calling the asyncTask.
I have tried some ways but it's failed, for example
* I execute asynTask after progressdialog.dismiss().
* put execution asynctask inside dialogbox after progressdialog thread.
in other word, is there any way to tell asynctask that progressdialog has been dismissed. Or is there communication such as message between threads ?
here is the example of my code:
btnPost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stockProgressDialog = ProgressDialog.show(PostActivity.this,
"Please wait...", "Check the post");
new Thread() {
public void run() {
try{
/* Connect to Internet API */
stockProgressDialog.dismiss();
} catch (Exception e) { }
// Dismiss the Dialog
}
}.start();
new LookUpTask().execute();
}
});
Yes, there is a way to tell asyncTask that progressDialog has been dismissed. you can use one onDismissListener
#Override
public Dialog onCreateDialog(int id){
if(id==DIALOG_PROGRESS_DIALOG){
stockProgressDialog = new ProgressDialog(Main.this);
stockProgressDialog.setTitle("Please wait...");
stockProgressDialog.setMessage("Check the post");
stockProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
textView.setText("Waiting the 5 secs...");
myAsyncTask.execute("start it");
//Or myAsyncTask.cancel(true); if you want to interrupt your asyncTask
}
});
return stockProgressDialog;
} else return super.onCreateDialog(id);
}
You can cancel an AsyncTask by calling AsyncTask.cancel(..) and then start up a new AsyncTask. You are not supposed to run the AsyncTask as a parallel activity - it is supposed to be able to run and finish without outside intervention.
Extend async and look into returning a result from doInBackground. onProgress update can dismiss your Progress dialog under control of the async task. Handle the result from doInBackground in onPostExecute.
//create the task
theBackground = new Background();
theBackground.execute("");
--------
private class Background extends AsyncTask<String, String, String>{
protected String doInBackground(String...str ) {
publishProgress("##0");
//do a bunch of stuff
publishProgress(#001);
return("true");
}
protected void onProgressUpdate(String... str ) {
//do stuff based on the progress string and eventually
myProgressDialog.dismiss();
}
protected void onPostExecute(String result) {
}
}
I'm not sure why you're using a thread in one case, but an AsyncTask in another when you could just use two AsyncTasks... Actually, unless I'm missing something, in your case the most straightforward way is to combine the two bits of work into one AsyncTask and simply create and destroy the dialog in the AsyncTask callbacks. In pseudo-code:
onPreExecute
show dialog
doInBackground
do internet stuff
onPostExecute
update views
close dialog
Is there a reason why you're trying to update the views in its own AsyncTask? If you're updating views, you probably need to do the work in the UI thread anyway...

Check if AsyncTask is taking too long

I have an AsyncTask that get info from the web. Sometimes the connection fails and the AsyncTask processdialog is running forever.
In the doInBackground I have a check in the end if my catched info are empty and if this is the case, it should appear Positive button/Negative button, but this is not happening. The dialog is just running.
How can I check if an AsyncTask is taking too long time (Maybe 5 seconds) and dismiss the dialog?
Code snippet (doInBackground):
//orders is my ArrayList<Order> object, from my own Order class.
if(orders==null) {
pdia.dismiss();
AlertDialog.Builder alt_bld = new AlertDialog.Builder(ctx);
alt_bld.setMessage("Try agin?")
.setCancelable(false)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
button_refresh.setVisibility(View.GONE);
new ListTask().execute(null, null , null);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Connection failed!");
alert.show();
}
else {
return orders;
}
Thanks in advance and tell me if you need more info!
Instead of checking your result in doInBackground() you can get the value from the process and check it in onPostExecute(), like this:
protected void onPostExecute(ArrayList<Order> localOrders){
super.onPostExecute(localOrders);
if (localOrders==null) {
// Paste the positive and negative DialogListeners here
// and dismiss the dialog.
}
}
The result from your doInBackground() process passes into onPostExecute's parameter, thence you can check if your ArrayList object is empty or not.
But then writing the above code snippet in the onPostExecute will defeat the purpose right? We want the user to not wait past 5 seconds for an answer from the webservice and therefore we must handle the timeout within doInBackground itself.

Categories

Resources