Async task to show an AlertDialog - android

For the past few days, I haven't been able to solve an issue with my dialog box. I am running a thread to show the dialog box for 5000ms and removing it. and I am trying to show a toast("SUCCESS"). The problem is I am getting the dialog box for the second time also. I am new to android development and I need to solve this with Async Task so that I can delay the second thread and show a alert dialog.builder with a positive button instead of toast. I goggled a lot but I confused to to implement this
Here I am sending my credentials to server and while sending I am showing a progress dialog box for 5000ms and I want to have a separate thread in order to show the dialog.builder with a positive button.( When the user get a response in the logcat for that I should check the responsecode==1 or not from the logcat to show the builder)
plz someone help me to solve this with some code snippet if possible.
Thanks in advance.
this is the code where I need to implement Async task
Button signin = (Button) findViewById(R.id.regsubmitbtn);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// showDialog(0);
t = new Thread() {
public void run() {
register();
try {
while (counter < 2) {
showmsg(0);
Thread.sleep(5000);
removeDialog(0);
// Toast.makeText(Register.this, "Registerd", Toast.LENGTH_LONG).show();
showmsg(1);
// toast.show();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: {
++counter;
dialog = new ProgressDialog(this);
if (counter == 1) {
dialog.setMessage("Registering...");
}
else {
String resultsRequestSOAP = "";
if (Log.v("TAG", String.valueOf(resultsRequestSOAP)) == 1)
;
{
Context context = getApplicationContext();
CharSequence text = "Registerd";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
public void showmsg(int actionsToBePerformedOnScreen) {
Message msg = new Message();
msg.what = actionsToBePerformedOnScreen;
handler.sendMessage(msg);
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
showDialog(0);
break;
case 1:
// clear all images in the list
removeDialog(0);
break;
}
};
};

Easy: show dialog onPreExecute, register() in doInBackground and hide dialog in onPostExecute. Finally, do new RegisterTask().execute() in your onclick.
private class RegisterTask extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Signing in...");
this.dialog.show();
}
protected Boolean doInBackground(final Void unused) {
return Main.this.register(); //don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (result.booleanValue()) {
//also show register success dialog
}
}
}

Why you don't use Android AsyncTask?
For example:
public class MyPreloader extends AsyncTask<InputObject, Void, OutputObject>{
private Context context;
private ProgressDialog dialog;
public MyPreloader(Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
super.onPreExecute();
}
#Override
protected ResponseBase doInBackground(InputObject... params) {
InputObject input = params[0];
//some code for background work
}
#Override
protected void onPostExecute(OutputObject result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
super.onPostExecute(result);
}

Related

Set Progress Dialog properly in asynctask

I currently trying to show a progress dialog on OnclickListener of a Dialogbox since my items are taking too long to fetch from Server.
I use Async task as suggested here (Android progress dialog) and this post (android problem with progress dialog) to show progress dialog The progress dialog is shown , however the code returns exception when it goes to do background that " Looper is not set". And when I set looper nothing happens.
I am not sure at this stage what is it that I am doing wrong.
public void firstMethod()
{
final CustomObj obj = getCustomObj();//not imp
Messages.getInstance().showAlert(MainActivity.this, "message", false, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
gotoAnotherPge(obj);
}
});
}
public void gotoAnotherPge(final CustomObject obj)
{
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
new AsyncTask<Object, Object, Boolean>()
{
protected void onPreExecute()
{
pd.setMessage(String.format(Statics.getText(MainActivity.this, R.raw.dictionary, "subscriptions_loading_unsubscribing")));
pd.show();
}
protected Boolean doInBackground(Object... params)
{
try{
Looper.prepare();
final LocalPopulator lp = new LocalPopulator(MainActivity.this, 0)
{
#Override
public void populate()
{
List<Serializable> items = Arrays.asList(getItemHere(obj));
List<Serializable> listItems = new ArrayList<Serializable>();
listItems.addAll(items);
Serializable[] sItems = listItems.toArray(new Serializable[menuItems.size()]);
result = sItems;
}
};
showNextPage(true, 1, 0, lp);
Looper.loop();
}catch (Exception e){
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
return true;
}
protected void onPostExecute(Boolean result)
{
pd.dismiss();
}
};
MainActivity.this.runOnUiThread (new Runnable()
{
#Override
public void run()
{
// dismiss the progressdialog
pd.dismiss();
}
});
}

WindowManager$BadTokenException near dialog.show in AsyncTask android

How to show a dialog box in AsyncTask. Getting BadToketException in dialog.show();
I tried many ways but I could not solve it.
Also tried to pass context to the dialog box in different ways, but it is giving me the same result.
public class RetriveStock extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
message = client.clientReceive(1); // I get data here.
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
if (message.contains("AlertExecuted:")) {
final Dialog dialog = new Dialog(CreateAlert.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.display_dialog);// Dialog layout
TextView dialogText = (TextView) dialog.findViewById(R.id.digMsg);
dialogText.setText("Alert Executed!");
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
try {
dialog.show(); //WindowManager$BadTokenException
} catch (Exception e) {
e.printStackTrace();
}
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Please help.
protected void onPreExecute() {
// TODO Auto-generated method stub
// progressDialog = ProgressDialog.show(this, "", "loading news content");
progressDialog = new ProgressDialog(context , AlertDialog.THEME_HOLO_LIGHT);
progressDialog.setMessage(""+getString(R.string.laodnews));
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.animate));
progressDialog.setCancelable(false);
progressDialog.show();
}
start dailoge in pre execute and stop in onpostexecute..
is CreateAlert registered activity in manifest..if not then you have to pass registered activity context

Dismissing ProgessDialog on Android

I've been to get rid of a ProgressDialog for some time now. After some googling and reading through questions on stackoverflow I round that I can only run ProgressDialog.dismiss() from the UI Thread. After some more reading I learned I need to create a handler and attach it to the UI Thread like this: new Handler(Looper.getMainLooper()); but alas, the stubborn ProgressDialog still refuses to die.
Here's what my code looks like:
/* Members */
private ProgressDialog mProgressDialog;
private Handler mHandler;
/* Class' constructor method */
public foo() {
...
this.mHandler = new Handler(Looper.getMainLooper());
...
}
/* The code that shows the dialog */
public void startAsyncProcessAndShowLoader(Activity activity) {
...
mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
doAsyncStuff(); // My methods have meaningful names, really, they do
...
}
/* After a long process and tons of callbacks */
public void endAsyncProcess() {
...
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Getting rid of loader");
mProgressDialog.dismiss();
mProgressDialog = null;
Log.d(TAG, "Got rid of loader");
}
});
...
}
This doesn't seem to work, debugging shows that certain members of the PorgressDialog (mDecor) are null. What am I missing?
You should use the AsyncTask to do your async task:
AsyncTask task = new AsyncTask<Void, Void, Void>() {
private Dialog mProgressDialog;
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
}
protected Void doInBackground(Void... param) {
doAsyncStuff(); // My methods have meaningful names, really, they do
return null;
}
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
};
task.execute(null);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Log.d(TAG, "Got rid of loader");
}
});
Try this:
public static final int MSG_WHAT_DISMISSPROGRESS = 100;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg){
swtich(msg.what){
case MSG_WHAT_DISMISSPROGRESS:
mProgressDialog.dismiss();
break;
}
}
}
public void endAsyncProcess(){
handler.obtainMessage(MSG_WHAT_DISMISSPROGRESS).sendToTarget();
}

add progress bar when one activity loads other activity

This is my activity oncreate() method. I set a positive button ok with a dialogue window.
when I click on it, it navigates UI activity staticDisplay.class. I want to set a progress bar after clicking ok in the dialogue window until it loads the next activity.
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ACTIVITY ONCREATE");
super.onCreate(savedInstanceState);
// setContentView(R.layout.dialog);
setContentView(R.layout.main);
if (Registration.isRunning == false) {
TextView title = new TextView(this);
title.setText("DM2");
title.setBackgroundColor(Color.DKGRAY);
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);
/* alert message */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCustomTitle(title);
builder.setMessage(R.string.app_description).setPositiveButton(
"Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (Registration.isRunning == false) {
startService(new Intent(
getApplicationContext(),
Registration.class));
}
staticInfo();
if (Registration.ruid == null)
Registration.ruid = uId;
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
}
StaticDisplay.class on create method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statdisplay);
usage_btn = (Button) findViewById(R.id.appstat);
usage_btn.setOnClickListener(this);
setting_btn = (Button) findViewById(R.id.setting);
setting_btn.setOnClickListener(this);
}
you can use AysncTask for background process to be done and showing progressdialog as follows,
call the class
new Task().execute(CurrentActivity.this);
In Task Class:
private class Task extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialog;
Context context;
public Task(Context context)
{
this.context=context;
//constructor for this class
}
protected void onPreExecute() {
//create the progress dialog as
dialog=new ProgressDialog(context);
}
protected Void doInBackground(Void... JSONArray) {
//Place your background process code
}
protected void onPostExecute(Void unused) {
//dismiss the progressdialog
dialog.dismiss();
}
}
This Code , Working For me
private ProgressDialog progress;
Button CallButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
progress = new ProgressDialog(Page.this);
CallButton=(Button)findViewById(R.id.button1);
CallButton.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()) {
case R.id.button1:
progress.setMessage("Please Wait Loading...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
new Thread()
{
public void run()
{
Intent i = new Intent(Page.this,Update.class);
startActivity(i);
progress.dismiss();
}
}.start();
break;
}
}
Please look at to following code snippet,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your loading code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
In the run() method, you can put your loading code.

Android Async task porgress bar doesn't comes until background process is completed

I am building a project in which i use async task to show progress bar.
I am using get() method to wait the main thread so we can do the other task before .
but progress bar is showing after completion of doInBackground thered.
I Want to show the loading bar when the loading starts.
It will dismiss when onPostExecute calls.
public class TempConverterActivity extends Activity {
pojo p;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
try {
new LoadData().execute().get();
} catch (Exception e) {
Log.e("async brix--", e.getMessage());
}
runned();
}
private void runned() {
ArrayList<String> al = p.getData();
for (String str : al){
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(TempConverterActivity.this);
protected void onPreExecute() {
dialog.setMessage("Loading data...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params) {
p = new pojo();
new SoapParser(p);
return null;
}
}}
Please help . Thanks in advance.
You can try following code,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
Edited: In my previous answer I suggested using a Handler; however, AsyncTask eliminates the need to do this which I didn't spot.
Why do you feel the need to call AsyncTask.get()? This is a blocking call, and you call this from the UI thread, thus it is ultimately a race condition as to whether it or onPreExecute() is run first.
I see no reason why you should call get() in this context. You want to call runned() after the AsyncTask completes, but you could do this by launching a new thread from onPostExecute(). Alternatively you could do as you do now, using get(), but call that from a new thread instead of the UI thread.

Categories

Resources