I create an AlertDialog to let the user choose if download something from the server.
If the user choose to download, the AlertDialog is dismissed, and came up a ProgressDialog connected to a AsyncTask.
The ProgressDialog is never showed. The "ok" button of AlertDialog remains selected until the end of the operations of the AsyncTask.
If I "comment" the AsyncTask operation in the code, the AlertDialog is correctly dismissed, and the ProgressDialog shows up.
I haven't tried the application on a real device, but only the simulator.
Which is the problem?
Try this code this may help you
private class allinfo extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog dialog;
protected void onPreExecute(){
dialog = ProgressDialog.show(collection.this, "Loading", "Loading. Please wait...", true,false);
}
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
return json;
}
protected void onPostExecute(JSONObject json)
{
dialog.dismiss();
info(json);
}
}
final AlertDialog d = new AlertDialog.Builder(youclassname.this)
.setView(input)
.setTitle(R.string.message)
.setPositiveButton(android.R.string.ok,
new Dialog.OnClickListener() {
public void onClick(DialogInterface d, int which) {
//Do nothing here. We override the onclick
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
d.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startDownload();//begin downloading
d.dismiss();
}
});
}
});
d.show();
here is startDownload part.
private void startDownload() {
String url ="file download link";
Toast.makeText(dwn.this, url,Toast.LENGTH_LONG).show();
new DownloadFileAsync().execute(url);
}
here is the asynctask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.type");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
here is the code for progress dialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading PDF file");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
ProgressDialog implementation in AsyncTask example using AlertDialog positive button:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to go to AsyncTask!")
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
new MyAsyncTaskClass().execute();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Here is the start of the AsyncTask
class MyAsyncTaskClass extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
progressDialog.setMessage("Dialog Message");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(String... params) {
// TODO stuff
}
protected void onPostExecute(Void v) {
this.progressDialog.dismiss();
}
}
}
Related
i'am trying develop a game in android that, when my doll crash with a bottle in a screen, show a Dialog with 2 options but i don't know...
public void whenDollCrash(Grafico elementofaba,Grafico elementoBotella){
if((elementofaba.getPosX()+elementofaba.getAncho()>=elementoBotella.getPosX()+15)&&
(elementofaba.getPosX()+elementofaba.getAncho() <= elementoBotella.getPosX()+elementoBotella.getAncho()+15)&&
(elementofaba.getPosY()+elementofaba.getAlto()>=elementoBotella.getPosY())
&& (elementofaba.getPosY()+elementofaba.getAlto() <= elementoBotella.getPosY()+elementoBotella.getAlto())){
juego.detener();
hiloFaba.detener();
sonidoJuego.stop();
golpe.start();
Async a= main.new Async();
a.execute();
Log.i("parada", "esto furruca");
}
and my class AsyncTask is the next.
public class Async extends AsyncTask{
AlertDialog.Builder builder;
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
builder =
new AlertDialog.Builder(MainActivity.this);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
builder.setMessage("¿Confirma la acción seleccionada?")
.setTitle("Confirmacion")
.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
Help me!!
In the logCat always shows NullPointerException
This guy looks really suspicious
Async a= main.new Async();
You should use something like this
public class Async extends AsyncTask<Void, Void, Void> {
AlertDialog.Builder builder;
WeakReference<Activity> activityWeakRef;
public Async(Activity context) {
activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (activityWeakRef != null && activityWeakRef.get() != null) {
builder = new AlertDialog.Builder(activityWeakRef.get());
builder.setMessage("¿Confirma la acción seleccionada?").setTitle("Confirmacion").setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
}
}
and use it like this in your custom view
Async a = new Async((Activity) getContext());
a.execute()
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();
}
});
}
I have progress bar which show progress of downloading file by defining asyncTask to accomplish this. Now I want to show downloading status as the progress bar updated. Eg. "Current File: 40%" and on next iteration it shows "Current File: 80%" etc
Below is my code:
public class MainActivity extends Activity {
private ProgressDialog _progressDialog;
private int _progress = 0;
#Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final DownloadTask downloadTask = new DownloadTask(MainActivity.this);
downloadTask.execute("xyz.com");
}
});
}
protected
Dialog onCreateDialog(int id) {
switch (id) {
case 0:
//...
case 1:
_progressDialog = new ProgressDialog(this);
_progressDialog.setIcon(R.drawable.ic_launcher);
_progressDialog.setTitle("Downloading files...");
_progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
_progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Hide",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
Toast.makeText(getBaseContext(), "Hide clicked!",Toast.LENGTH_SHORT).show();
}
});
_progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
Toast.makeText(getBaseContext(), "Cancel clicked!",Toast.LENGTH_SHORT).show();
}
});
return _progressDialog;
}
return null;
}
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
int myProgressCount;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
try {
while (......) {
if (isCancelled())
return null;
myProgressCount++;
publishProgress(myProgressCount);
}
} catch (Exception e) {
return e.toString();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(1);
_progress = 0;
_progressDialog.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
_progressDialog.setIndeterminate(false);
_progressDialog.setMax(100);
_progressDialog.setProgress(progress[0]);
_progressDialog.setMessage("File:"+progress[0]);
}
#Override
protected void onPostExecute(String result) {
_progressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
}
}
How can we update setMessage as progress[0] changes?
Thanks
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
i want to show spinning wheel progress but it doesn't show anything.
final ProgressDialog dialog = ProgressDialog.show(AppListActivity.this,
"", "Loding...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
// Set our custom array adapter as the ListView's adapter.
listAdapter = new AppArrayAdapter(AppListActivity.this,
appsList);
mainListView.setAdapter(listAdapter);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
please figure out this one..
thanks..
you haven't written dialog.show()..
refer to this code
ProgressDialog UpdateDialog = new ProgressDialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
UpdateDialog.setTitle("MyApp");
UpdateDialog.setMessage("Processing data...");
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
//your code
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
//your code
UpdateDialog.dismiss();
}
ProgressDialog mPrograss=new ProgressDialog(location.this);
mPrograss.setTitle("loading....");
mPrograss.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mPrograss.setMax(1);
mPrograss.setProgress(2000);
mPrograss.setButton("save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
mPrograss.setButton2("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
mPrograss.show();
i think u can use the code below.
private ProgressDialog pd;
pd = ProgressDialog.show(context, "Please wait...", "Saving to database...", true,false);
.
pd.dismiss();