Alert Dialog and ASync Task - android

i am trying to use Alert Dialog Box and Async Task in the activity and am getting the following error
Caused by: java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare()
Code:
public class loginTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog loginDialog = new ProgressDialog(
LoginActivity.this);
#Override
protected void onPreExecute() {
loginDialog.setMessage("Please wait Logging in");
loginDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
if(loginUser()) {
loginDialog.dismiss();
alertbox("title", "winnn", "Okay");
} else {
loginDialog.dismiss();
alertbox("title", "message", "Okay");
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
loginDialog.dismiss();
Intent intentHome = new Intent(LoginActivity.this,
HomeActivity.class);
startActivity(intentHome);
}
}

You can't update UI inside the doInBackground() method directly. (Yes if you still want to execute then write the same inside the runOnUiThread() method inside the doInBackground())
Otherwise, do it inside the onPostExecute() method.
public class loginTask extends AsyncTask<Void, Void, Void>
{
public ProgressDialog loginDialog = new ProgressDialog( LoginActivity.this );
public Boolean flag;
#Override
protected void onPreExecute() {
loginDialog.setMessage("Please wait Logging in");
loginDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
if(loginUser())
flag = true;
else
flag=false;
return null;
}
#Override
protected void onPostExecute(Void unused) {
loginDialog.dismiss();
if(flag)
alertbox("title", "winnn", "Okay");
else
alertbox("title", "message", "Okay");
}
}

the onPreexecute and onPostExecute are part of the UI parts in the Async Task.. the doInBackground is a seperate thread so any thing done inside the doInBackground needs to be handled in the form of progressUpdate
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Example Reference: Link
reflects any changes you need to make to the UI inbetween the doInBackground process.

Related

how to make a asynctasc work and dismiss after sometime?

I have a asynctask and I want to make it to be canceled after some time, 60 sec for example.
I think I have to it inside a while statemant, but I dont know how to count the time.
Here is my idea:
public class ThreadWithAutoCancel extends AsyncTask<Void, Void, Void> {
public ThreadWithAutoCancel(int timeOut) {
WatchDog watchDog = new WatchDog(this);
watchDog.execute(timeOut);
}
#Override
protected Void doInBackground(Void... params) {
// Do the job
return null;
}
class WatchDog extends AsyncTask<Integer,Void,Void>{
private long startTime;
private AsyncTask task;
public WatchDog(AsyncTask taskToStop){
task = taskToStop;
}
#Override
protected void onPreExecute(){
startTime = System.currentTimeMillis()/1000;
}
#Override
protected Void doInBackground(Integer... params) {
while(System.currentTimeMillis()/1000 < startTime+params[0]){
}
task.cancel(true);
return null;
}
}
}
After starting the AsyncTask, hold a reference to it and call cancel on it 60 seconds later, perhaps on a UI Thread Handler. Inside your doInBackground method you will have to make sure you return if isCancelled returns true. I hope the following snippet will help:
public class MyActivity extends Activity {
private Handler mHandler;
private AsyncTask<?, ?, ?> mTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
}
#Override
protected void onPostResume() {
super.onPostResume();
mTask = new MyCustomTask();
mTask.execute(1, 2, 3);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mTask.cancel();
}, 60L);
}
}
And inside your custom task:
public class MyCustomTask extends AsyncTask<Integer, Float, String> {
#Override
protected String doInBackground(Integer... params) {
String output = "";
for (Integer i : params) {
// Check status for each param
if (isCancelled()) {
return output;
}
...
}
}
#Override
protected void onCancelled(String result) {
// This bit runs on the UI thread
...
}
You can do this using handler. For example this code will show "Completed" on TextView with R.id.mytext after asynctask will execute for 60 seconds:
final int FINISH = 1;
Thread waitingThread;
MyAsyncTask myAsyncTask;
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == FINISH)
{
myAsyncTask.cancel(true);
((TextView) findViewById(R.id.mytext)).setText("Completed");
}
};
};
// ...
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
waitingThread = new Thread(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(60);
mHandler.sendEmptyMessage(FINISH);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
waitingThread.start();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
while (true) {
// do something
}
}
}

Android - Progress Dialog crashes when changing message

I'm new to Android and I'm practicing creating a progress dialog. I want to change the message in the dialog every couple of seconds, but my application crashes when I change the message. Any ideas what I may be doing wrong?
private void progressDialogTest(final ArrayList<String> messages)
{
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>()
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Progress Dialog");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
for(int i=0; i<messages.size(); i++)
{
/******** APPLICATION SEEMS TO CRASH AT LINE BELOW ********/
progressDialog.setMessage(messages.get(i));
Thread.sleep(3000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
};
task.execute((Void[])null);
}
Move the code to onProgressUpdate instead, eg:
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
progressDialog.setMessage(messages.get(progress[0]));
}
#Override
protected void doInBackground(Void... arg0) {
/* ... */
//progressDialog.setMessage(messages.get(i)); Change this line to
publishProgress(i);
/* ... */
}

How to show dialog box from asyntask nonUI activity in android?

i have implemented code form the below link to check the idle time of the application
How to intent to another page on android/pop up a message from idle time?
Instead using thread i used asyntask...Now my problem once it reaches the idle time..i want to show dialog to the user application is end relogin from the login activity..
How can i call dialog from the asynctask onpostExcute
public class session extends AsyncTask<Void,Void,Void> {
private static final String TAG=session.class.getName();
private long lastUsed;
private long period;
private boolean stop;
Context context;
final Dialog dialog = new Dialog(context);
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//here i do the process.......
}
#Override
protected void onPostExecute(Void x){
//stuff to be done after task executes(done on UI thread)
// For Dialog Button**********************************
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Result");
final TextView dialogtxt = (TextView) dialog
.findViewById(R.id.textView1);
final Button closeButton = (Button) dialog
.findViewById(R.id.button1);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialogtxt.setText("session time out");
dialog.show();
// ****************************************************
}
#Override
protected void onPreExecute(){
//stuff to be done after task executes(done on UI thread)
}
}
You can do it by calling the dialog from either one of the methods except the doInBackground method.
You may call it in the onPreExecute and show the dialog there and after your background task is done you can cancel it from the onPostExecite method. If you want even more control you can also do it using onProgressUpdate. Just dispatch the progress from your background task by calling publishProgress and overwrite the onProgressUpdate method and do whatever you want there.
This is an example taken right out of the docs.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
The Asynctask need to get the Context.
If your Asynctask is embeded into the activity, just call the java Activity.this as a context.
You can also put a context as a field in the Asynctask and then give it as an arg to Asynctask.
You can call the Dialog.show in the onPostExecute, it's on UI Thread.
This sample AsyncTask is embeded into an activity
public class AsyncDialogBuilder extends AsyncTask {
private Context context = DriverOnTripActivity.this;
private final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
private Integer remoteAllWaitinOnCount;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
}
#Override
protected Integer doInBackground(Integer... integers) {
remoteAllWaitinOnCount = User.getRemoteAllWaitinOnCount(latestClosestKojo.getRemoteId());
if (remoteAllWaitinOnCount > 0) {
try {
makeDialog();
} catch (Exception e) {
e.printStackTrace();
}
return 100;
} else {
return 99;
}
}
private void makeDialog() {
dialog.setTitle(latestClosestKojo.getName()
+ " - "
+ remoteAllWaitinOnCount
+ " Kojoalas");
dialog.setPositiveButton("S'arreter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
isDialogPrompted = false;
dialogInterface.dismiss();
goToOnBoardingActivity();
}
});
dialog.setNegativeButton("Ignorer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
isDialogPrompted = false;
dialogInterface.dismiss();
}
});
}
#Override
protected void onPostExecute(Integer integers) {
if (integers >= 100 && dialog != null) {
dialog.show();
isDialogPrompted = true;
}
}
}

Progress bar doesn't update

I created a Progress bar but I can't see the loading animation. It's frozen. I want to display a progress bar when I click on the item and then see the bar working and not frozen. Here is my code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (((TextView) view).getText().equals("Zman-New (rus)")){
progDailog = ProgressDialog.show(testLoading.this, "Getting data", "Loading...",true,true);
new GetDataTask("stringurl.xml").execute();
}
Here is the getdata
private class GetDataTask extends AsyncTask<Void, Void, Integer> {
String url;
GetDataTask(String url){
this.url=url;
}
#Override
protected Integer doInBackground(Void... params) {
//do all your backgroundtasks
intent = new Intent(rusNewsP.testLoading.this, rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
return 1;
}
#Override
protected void onPostExecute(Integer result) {
//finish up ( or close the progressbar )
//do something with the result
progDailog.dismiss();
super.onPostExecute(result);
}
}
If you just want to test Progress try this:
private class Initialize extends AsyncTask<Short, Short, Short> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(yourlass.this);
pd.setMessage("test");
pd.show();
super.onPreExecute();
}
#Override
protected Short doInBackground(Short... params) {
try {
synchronized (this) {
wait(2000);
}
} catch (InterruptedException ex) {
}
return null;
}
#Override
protected void onPostExecute(Short result) {
pd.dismiss();
super.onPostExecute(result);
}
}
And don't call startActivity in the doInBackground-Method. Call it in OnPostExecute instead. GUI Operations should not be done in doInBackground.
Try to start the Activity Direct from the UI thread as that will be fast.
Still,if you want this way then try to start it from the onPostExecute Method.
Not from the doInBackground.
protected void onPostExecute(Integer result)
{
//do something with the result
progDailog.dismiss();
intent=new Intent(rusNewsP.testLoading.this,rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
}
And...don't call super.onPostExecute(result); after dismissing the progressDialog..after completing the doInBackground(Short... params),It will return directly to onPostExecute Method where it will dismiss the ProgressDialog first time and then execute the Constructor which will try again to dismiss the ProgressDialog which is already dismissed resulting into uncaught exception.

showing imported data on progress bar

I am working on Address book app in android.In my application i import contacts from phonebook in my app.while importing i am showing progress bar.I want to show the contacts being imported on the progressbar while importing.how to do this?
following is my code:-
public class Task extends AsyncTask<String, Integer, Void> {
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute()
{
System.out.println("IN PreExecute");
this.dialog = ProgressDialog.show(applicationContext, "Importing Contacts", "Please Wait...", true);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("IN BACKGROUND");
addcontacts();//return flag1;
//dialog.setMessage(name);
return null ;
}
protected void onProgressUpdate(String... progress)
{
System.out.println("IN update");
}
#Override
protected void onPostExecute(Void unused) {
this.dialog.cancel();
System.out.println("IN PostExecute");
final AlertDialog.Builder alertbox1=new AlertDialog.Builder(Import.this);
Cursor c=data.getData();
int num=c.getCount();
alertbox1.setMessage(+num+" contacts imported");
c.close();
// set a positive/yes button and create a listener
alertbox1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1)
{
call();
}
});
alertbox1.show();
}
onProgressUpdate gets called every time we call publishProgress and the arguments from publishProgress go to onProgressUpdate
So in doInBackground() you can do
protected Void doInBackground(String... params) {
for(int i=1; i<=totalContacts; ++i) {
importNextContact();
publishProgress(i/(float)totalContacts)*100);
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
Using dialog.setMessage("msg") is correct but remember that you can not change the ui in the
doInBackground(...) method, so either you post a msg using an handler or you use runOnUiThread.

Categories

Resources