Android: Trying to create a dialog within a AsyncTask<String object - android

I'm using a AsyncTask
I use parent to create the intent no errors.
The line to creat a dialog gives a
parent cannot be resolved to a ye.
new parent.AlertDialog.Builder(this)
The error I get is that parent does not exist, but I use parent in the same methed to call the intent
code block
private class SendTextOperation extends AsyncTask {
#Override
protected void onPreExecute() {
//Update UI here
}
#Override
protected String doInBackground(String... params) {
// Talk to server here to avoid Ui hanging
rt=TalkToServer("http://besttechsolutions.biz/projects/bookclub/login.php");
return(rt);
}
#Override
protected void onPostExecute(String result) {
if (rt.contains("ok"))
{
Intent i = new Intent(parent, cChat.class);
startActivity(i);
}
else
{
new parent.AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Your time is up, You saved "
+" Million more people!!")
.setNeutralButton("Try Again",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int i)
{
}} ).show();
}
}
}

For showing AlertDialog from non Activity you will need to pass Current Activity Context to non Activity class in your case to SendTextOperation class.
Create an Constructor for SendTextOperation as :
public class SendTextOperation extends AsyncTask<String,Void,String>{
Context context;
public SendTextOperation(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
//Update UI here
}
#Override
protected String doInBackground(String... params) {
// Talk to server here to avoid Ui hanging
rt=TalkToServer("http://besttechsolutions.biz/projects/bookclub/login.php");
return(rt);
}
#Override
protected void onPostExecute(String result) {
if (rt.contains("ok"))
{
Intent i = new Intent(context, cChat.class);
startActivity(i);
}
else
{
new context.AlertDialog.Builder(context)
.setTitle("Game Over")
.setMessage("Your time is up, You saved "
+" Million more people!!")
.setNeutralButton("Try Again",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int i)
{
}} ).show();
}
}
}
and start SendTextOperation AsyncTask as :
SendTextOperation sendtxtasyncTask = new SendTextOperation(CurrentActivity.this);
sendtxtasyncTask.execute("");

Lets say you have that class declared inside a class named MyActivity
Then use instead of this, MyActivity.this when creating the Dialog.

It looks like you should be calling it like this:
final AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setMessage(_context.getString(R.string.error) + ": " + _errorMessage)
.setTitle(_context.getString(R.string.loginError))
.setIcon(android.R.drawable.ic_dialog_alert)
.setCancelable(true)
.setPositiveButton(_context.getString(R.string.ok), null);
final AlertDialog alert = builder.create();
alert.show();
(My own sample code)
It looks like your error is trying to do parent.AlertDialog.Builder(this), where you need to use new AlertDialog.Builder(parent), if parent is your context.

Related

How to show AlertDialog in AsyncTask without leaking Context?

I have the below code working fine to find and read a record in a Room database via an id. Android Studio required adding a try/catch block which I've included below.
Two questions:
Can I leave the if{} section blank in onPostExecute() if there is no Exception?
How do I show an AlertDialog here without leaking contect and without using a hack via WeakReference?
// AsyncTask for reading an existing CardView from the database.
private static class ReadAsyncTask extends AsyncTask<Integer, Void, Quickcard> {
private QuickcardDao asyncTaskDao;
Exception e;
ReadAsyncTask(QuickcardDao dao) {
asyncTaskDao = dao;
}
#Override
public Quickcard doInBackground(final Integer... params) {
Quickcard result;
try {
result = asyncTaskDao.readCardForUpdate(params[0]);
} catch (Exception e) {
this.e = e;
result = null;
}
return result;
}
#Override
protected void onPostExecute(Quickcard quickcard) {
if (e == null) {
// *** Okay to leave this blank? If not, what should go here?
}
else {
// *** How do I show an AlertDialog here with leaking context?
}
}
}
You cannot use a view object while using a thread that operates in background.. U must implement the dialog in the UI thread. When you are implementing the the asynchronous class, in that method you should show the alert dialog. Hope this helps..
This is what I will do to prevent leaks from happening.
private static class showDialog extends AsyncTask<String, String, String> {
private WeakReference<MainActivity> mainActivityWeakReference;
showDialog(MainActivity mainActivity){
this.mainActivityWeakReference = new WeakReference<>(mainActivity);
}
#Override
protected String doInBackground(String... params) {
//do your long long time consuming tasks here.
return "Done";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
//Just building an alert dialog to show.
if (mainActivityWeakReference.get() != null){
final MainActivity activity = mainActivityWeakReference.get();
new AlertDialog.Builder(activity).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(activity, "Yes was clicked", Toast.LENGTH_SHORT).show();
}
}).show();
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}

How to convert this inner AsyncTask in outer one?

I created this AsyncTask inner class and now I want to make it outer. Here is the code:
private class DownloadDataFromServer extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
boolean connErr = false;
boolean soErr = false;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(HomePage.this); !!!!PROBLEM!!!!
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(false);
dialog.setTitle("Download");
dialog.setMessage("Updating...");
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
// do something
}
protected void onProgressUpdate(Integer... progress) {
// Update the progress
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
if (connErr || soErr) {
String msg = "Bad connection";
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(HomePage.this); !!!!PROBLEM!!!!
builder.setCancelable(false);
builder.setTitle("Connection timeout");
builder.setMessage(msg);
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
new DownloadDataFromServer().execute(new String[] { "http://www.example.com" });
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish(); !!!!PROBLEM!!!!
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (Integer.parseInt(result) <= 0) {
Toast.makeText(getBaseContext(), "Error!", Toast.LENGTH_SHORT).show(); !!!!PROBLEM!!!!
} else {
Toast.makeText(getBaseContext(), "OK!", Toast.LENGTH_SHORT).show(); !!!!PROBLEM!!!!
}
}
dialog.dismiss();
}
}
Please note "!!!!PROBLEM!!!!" strings in the above code: there are all the errors that I get. I tried to apply some workarounds but finally I could not make it working. In addition I also have to use
private Database db = new Database(this);
but I do not know what to put in place of "this". Please help me to convert this inner class in the right way.
You should make one argument constructor to DownloadDataFromServer class and pass Context as argument like
Context mCon;
public DownloadDataFromServer(Context con){
this.mCon=con;
}
and used this mCon context to anywhere in your DownloadDataFromServer like so
builder = new AlertDialog.Builder(mCon);
and at last called DownloadDataFromServer from any Activity like
new DownloadDataFromServer(your_Activity.this).execute(......);
Make yout DownloadDataFromServer have a constructor accepting HomeScreen, save the home screen in a field in the constructor and then use that field everywhere instead of HomeScreen.this.
You may have to make some of your private fields of HomeScreen public (or provide accessors) because of that.
You do not want to do all that though, what's the advantage?

Android AlertDialog Activity & Async Error

I have a fully functional asynctask in my android app, but when I'm not connected it causes my app to crash in the Error message within my Activity (in AlertDialog.Builder) stemming from the Async not connecting. I pass Context to my async, so that may have something to do with it, but not sure.
Below is the code from Async class and Activity. LogCat is telling me error is occurring in the AlertDialog alert builder.create(). How can I solve?
From Async class:
InputsRecapUploadTask extends AsyncTask<String, Void, Integer> {
public InputsRecapUploadTask(InputsRecap activity,
ProgressDialog progressDialog, Context ctx) {
this.activity = activity;
this.myCtx = ctx;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
}
#Override
protected Integer doInBackground(String... arg0) {
//// http code
responseCode = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
progressDialog.dismiss();
activity.showLoginError("");
}
return responseCode;
}
#Override
protected void onPostExecute(Integer headerCode) {
progressDialog.dismiss();
if (headerCode == 1)
activity.login(id);
else
activity.showLoginError("");
}
Activity Class:
public void showLoginError(String result) {
AlertDialog.Builder builder = new AlertDialog.Builder(InputsRecap.this);
builder.setPositiveButton("okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setMessage("unable to upload database");
AlertDialog alert = builder.create();
alert.setCancelable(true);
alert.show();
}
If an exception is thrown in your doInBackground method these two lines:
progressDialog.dismiss();
activity.showLoginError("");
Will cause Exception - you can not modify the UI from within the doInBackground method. Instead set a flag and show the error dialog in the onPostExecute which is executed in the main thread.
Check the link below especially the topic under heading The 4 steps.
http://developer.android.com/reference/android/os/AsyncTask.html

How to call a the activity method finish() from the Application object?

I have a piece of code to delete an Item in database. I am calling the same code from two different activities. So to avoid code repetition, I want to shift the code to the Application object. The code in one of the activities looks like this:
private void deleteItem() {
AlertDialog.Builder alert = new AlertDialog.Builder(Activity1.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DbHelper db = new DbHelper(Activity1.this);
AsyncTask<Long, Void, Object> deleteTask = new AsyncTask<Long, Void, Object>() {
#Override
protected Object doInBackground(Long... params) {
db.deleteItem(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
Now to put it in application object, I changed the function to public, gave it two parameters for input: Context and rowID. But in the onPostExecute method of AsyncTask I have to close the activity. In the activity, I did this by finish(). How do I do it in this context? I have attached the code in application object also.
public void deleteItem(final Context context, final long rowID) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DbHelper db = new DbHelper(context);
AsyncTask<Long, Void, Object> deleteTask = new AsyncTask<Long, Void, Object>() {
#Override
protected Object doInBackground(Long... params) {
db.deleteItem(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
Context can be cast to Activity :
Activity activity = (Activity) context;
And than just use :
activity.finish();
Instead of shifting it to Application, create a BaseActivity(which extends Activity class) class, all your activities extend BaseActivity .. and common code will be place in BaseActivity
I think that what you are trying to do is fundamentally not a good idea.
Outside of the Activity code, there are no guarantees that the activity still exists - the memory manager may have cleaned it up, the user may have pressed Back etc.
The final design decision is up to you but I advise you to consider if this is really necessary.
A little redundancy is okay in my opinion if it leads to more program stability and reliability.
Its simple, add activity instance as well
public void deleteItem(final Context context, Activity activity,final long rowID){
activity.finish();
}
It's impossible to call Application.finish() like in C# . You can use method like this :
Activityname.finish();
It's good solution.
I hope I helped.

Android Asynch Task inside AlertDialog not working

I display an Alertbox with ok or cancel.
I want to implement an asynch task on the press of OK. Havent done asynch and been struggling with it for awhile. I dont understand where the asych class goes also. Does it go outside the method that is being executed or outside of it? Current code as follows:
private abstract class DoAsynchTask extends AsyncTask<Void,Void,Void>
{
protected void doInBackground()
{
Drawable drawable= getImage(imageSelect);
MakeWallPaper(drawable,1);
}
/* protected void onProgressUpdate(Integer... progress)
{
setProgress(progress[0]);
}*/
protected void onPostExecute()
{
Toast.makeText(getApplicationContext(), "Wallpaper Saved.",Toast.LENGTH_LONG).show();
AlertDialogProcessing=0;
}
}
public void getWallpaper(final View v)
{
if(AlertDialogProcessing==0)
{
final String title="Set Image to Wallpaper";
final String message="Press OK to set as Wallpaper or CANCEL.\nWait after pushing OK.";
final String ok="OK";
final String cancel="CANCEL";
final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setCancelable(true);
alertbox.setIcon(android.R.drawable.ic_dialog_alert);
alertbox.setTitle(title);
alertbox.setMessage(message);
alertbox.setNegativeButton(cancel, null);
final AlertDialog dlg = alertbox.create();
alertbox.setPositiveButton(ok,new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dlg, int which)
{
DoAsynchTask.execute(null,null,null); //<<<<Wrong
dlg.dismiss();
Vibrate(ClickVibrate);
}
});
alertbox.setNegativeButton(cancel,new DialogInterface.OnClickListener(){ public void onClick(DialogInterface arg0, int arg1){AlertDialogProcessing=0;
Vibrate(ClickVibrate); } });
alertbox.show();
}
}
There's a couple problems in the code.
1) First of all, the compiler is probably giving you this message:
The type MyActivity.DoAsynchTask must implement the inherited abstract
method
AsyncTask.doInBackground(Void...) MyActivity.java
If you look closely at the error message, you'll realize that what you defined was this:
protected void doInBackground() {
which is not what is needed. Even though it might seem silly, when your AsyncTask subclass takes Void as the generic parameter types, that means that doInBackground() must look like this:
protected Void doInBackground(Void... arg0) {
The compiler complains because you haven't implemented that (exact) method. When you inherit from an abstract class, and fail to implement all of its required/abstract method(s), then you can only get it to compile by marking the subclass as abstract, too. But, that's not really what you want.
So, just change your code to (remove abstract from your class):
private class DoAsynchTask extends AsyncTask<Void,Void,Void>
and
protected Void doInBackground(Void... arg0) {
{
Drawable drawable= getImage(imageSelect);
MakeWallPaper(drawable,1);
return null;
}
2) And the second problem, as others have pointed out, is that you must start your task with:
new DoAsynchTask().execute();
not
DoAsynchTask.execute(null,null,null);
Your code would only be correct if execute() was a static method in AsyncTask, which it's not. In order to invoke the non-static execute() method, you first need a new instance of the DoAsynchTask class. Finally, the null, null, null parameter list is also not necessary, although I don't think it will cause the code to fail either.
Since your doInBackground() does not specify any parameters, you should call DoAsynchTask.execute() without parameters.
Why is your class abstract? Normally an AsyncTask should be an inner class of the activity starting it. So create your dialog in the activity, and execute the AsyncTask when clicking on OK button, like you do.
//final working copy -Thanks ALL
public void getWallpaper(final View v)
{
Vibrate(ClickVibrate);
final class SetWallPaperAsynchTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... arg0)
{
Drawable drawable= getImage(imageSelect);
MakeWallPaper(drawable,1);
return null;
}
#Override
protected void onPostExecute(Void result)
{Toast.makeText(getBaseContext(), "Wallpaper Saved.", Toast.LENGTH_LONG).show();
AlertDialogProcessing=0;
}
}
if(AlertDialogProcessing==0)
{
ProgressDialog progress;
final String title="Set Image to Wallpaper";
final String message="Press OK to set as Wallpaper or CANCEL.";
final String ok="OK";
final String cancel="CANCEL";
final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setCancelable(true);
alertbox.setIcon(android.R.drawable.ic_dialog_alert);
alertbox.setTitle(title);
alertbox.setMessage(message);
alertbox.setNegativeButton(cancel, null);
final AlertDialog dlg = alertbox.create();
alertbox.setPositiveButton(ok,new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
new SetWallPaperAsynchTask().execute();
dlg.dismiss();
Vibrate(ClickVibrate);
}
});
alertbox.setNegativeButton(cancel,new DialogInterface.OnClickListener(){ public void onClick(DialogInterface arg0, int arg1){AlertDialogProcessing=0; Vibrate(ClickVibrate); } });
alertbox.show();
}
}

Categories

Resources