Cannot run the async example ..? - android

When i tried to run the code, only main toast is running. Progress Dialog and other toast message is not running.This program is simple async example for sleeping process.The main issue is that it is not showing the Progressdialog.
Did i need to add xml file(it contain only a textView and a Button).
Please help me to solve this.Thank You
package com.example.asyncexample;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
public class MainActivity extends Activity {
ProgressDialog progressBar;
int prorgessInc = 1; // incrementing the progress dialog
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(startTaskListener);
}
private OnClickListener startTaskListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
progressBar = new ProgressDialog(v.getContext());
BackgroundTask test = new BackgroundTask();
test.execute(context);
CharSequence text = "Main Thread is Running";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
private class BackgroundTask extends AsyncTask<Context, Integer, String>{
protected void OnPreExecute() {
CharSequence msg = "BackgroundTask is Operating";
progressBar.setCancelable(true);
progressBar.setMessage(msg);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
#Override
protected String doInBackground(Context... params) {
//BackgroundTask Is Running
for(int i =0; i<=100; i+=prorgessInc){
try {Thread.sleep(100);}
catch (InterruptedException e) { e.printStackTrace();}
publishProgress(prorgessInc);
if(isCancelled()) break;
}
return getString(R.string.backgndcompld);
}
protected void OnProgressUpdate(Integer...values ) {
//Update Progress bar
progressBar.incrementProgressBy(prorgessInc);
}
protected void PostExecute(String result){
//Dissmiss progressbar
progressBar.dismiss();
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast2 = Toast.makeText(context, result, duration);
toast2.show();
}
}
}

Right, your problem is in your method naming for the AsyncTask.
You have defined:
protected void OnPreExecute()
protected void OnProgressUpdate()
protected void PostExecute()
However the real methods are:
protected void onPreExecute()
protected void onProgressUpdate()
protected void onPostExecute()
Note the difference in case. If you had used the #Override as below your IDE would likely have shown you that.
I have done some cleaning of that and other parts of your code. Take a look:
public class MainActivity
extends Activity
implements View.OnClickListener
{
private Button button;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_example);
button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
Log.d("click", "start button clicked, starting task");
BackgroundTask test = new BackgroundTask();
test.execute();
}
private class BackgroundTask
extends AsyncTask<Void, Integer, String>
{
int PROGRESS_INCREMENT = 1;
int PROGRESS_MAX = 100;
String DIALOG_MSG = "AsyncTask is Operating";
#Override
protected void onPreExecute()
{
progressBar = new ProgressDialog(getApplicationContext());
progressBar.setCancelable(true);
progressBar.setMessage(DIALOG_MSG);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(PROGRESS_MAX);
progressBar.show();
}
#Override
protected String doInBackground(Void... params)
{
for (int i = 0; i <= 100; i += PROGRESS_INCREMENT)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
publishProgress(PROGRESS_INCREMENT);
if (this.isCancelled())
{
break;
}
}
return "[some result text]";
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressBar.incrementProgressBy(PROGRESS_INCREMENT);
}
#Override
protected void onPostExecute(String result)
{
progressBar.dismiss();
Toast.makeText(getApplicationContext(),
result,
Toast.LENGTH_LONG)
.show();
}
}
}
Notable changes:
Activity implements View.OnClickListener so you can move your onClick() method to your Activity eliminating the anonymous inner class.
Button moved to a class level scope. Defining it in your listener could be error prone.
prepare and display your PrgressDialog from the onPreExecute() method. That's what it's for.
Cleaned up your Toast. No need to use all those variables and waste space with useless objects.
Instead of Toast messages use the built in Log for debug messages. Toast messages can very quickly begin to spam your screen and because of the display lengths are very inaccurate for knowing when things happen.

Related

Update ProgressDialog from Thread inside Service

i want to increment a progress dialog from a thread inside a service, i have really hard time doing that, this is my code please help me.
I tried many different ways including asyncTask (I had problem with context)
and tried with static functions but its not working properly,
I pretty new with android please explain me the problem here.
the activity
public class MainActivity extends Activity {
ProgressDialog progressBar;
private void showProgrssBar() {
progressBar.show();
}
private void dismissProgressBar() {
progressBar.dismiss();
}
private void increaseProgressBar(int total) {
progressBar.incrementProgressBy(total);
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createProgressBarDialog();
Intent n = new Intent(this, myService.class);
startService(n);
}
private void createProgressBarDialog()
{
progressBar = new ProgressDialog(this);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setMax(200);
progressBar.setMessage("Recieving bluetooth data");
progressBar.setCanceledOnTouchOutside(false);
}
the service:
public class myService extends Service
{
private myThread myThread;
Handler handler = new Handler()
{
#Override
public void handleMessage(android.os.Message msg)
{
int total = msg.getData().getInt("total");
if (total == -1)
{
dismissProgressBar();
}
else if (total == 0)
{
showProgrssBar();
}
else
{
increaseProgressBar(total);
}
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
myThread = new myThread(handler);
myThread.start();
return START_STICKY;
}
the thread
class myThread extends Thread
{
Handler h;
int numOfLinesToRead = 220;
int line = 0;
public myThread(Handler h)
{
this.h = h;
}
private void increaseProgressBarOnActivity(int i_MsgType)
{
Message msg = h.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", i_MsgType);
msg.setData(b);
h.sendMessage(msg);
}
#Override
public void run() {
super.run();
int increase;
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
for (; line < 220; line++)
{
increase = (line*100/numOfLinesToRead);
if (increase != 0)
{
increaseProgressBarOnActivity(increase);
try
{
Thread.sleep(90);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
Despite you having already tried AsyncTask, I still would strongly recommend to use it.
Just take a look at the onProgressUpdate() method. It is made to update the UI from AsyncTask.
Here is an example of how it could look like:
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
private ProgressDialog progressBar;
#Override
protected void onPreExecute(){
super.onPreExecute();
progressBar= new ProgressDialog(getApplicationContext());
progressBar.setMessage("Loading...");
progressBar.show();
}
protected Long doInBackground(String... params) {
long someLong;
// do something here with params
// the Integer variable is used for progress
publishProgress(i);
// call it for example while downloading a file
return someLong;
}
// this is called whenever you call puhlishProgress(Integer)
protected void onProgressUpdate(Integer... progress) {
progressBar.incrementProgressBy(progress[0]);
}
// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(Long result) {
// do something with the result
progressBar.dismiss();
}
}
You said your problem was getting the Context. Well: Service is a Context
So you could simply make the AsyncTask an inner class of your Service and then use its Context.

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;
}
}
}

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.

How to display progressbar in android while loading the data from remote database?

How to display progressbar i'm calling intent from class A to class B.
In which class B lloads the data from the using parsing mean while
this happens i'm getting blank screen in this time i'd like to show
progressbar how can i do that.
Right now i'm writing the code as follows..
class A extends Activity{
oncreate(){
...
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new performBackgroundtask().execute();
}
}
class performBackgroundtask extends AsyncTask<Void, Void, Void> {
//
ProgressDialog progressDialog = new ProgressDialog(Main.this);
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Main.this,"", "Please wait...");
super.onPreExecute();
/*
* progressDialog.setMessage("Please wait while loading ...");
* progressDialog.show(); progressDialog.setCancelable(true);
*/
}
#Override
protected Void doInBackground(Void... params) {
Intent in = new Intent(A.this, B.class);
startActivity(in);
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
}
class B { ...
/*
* In which this class has another view which has to get the data from
* URL using SAXPArsing.
*
* ... for this where i need to write progress bar code.
*/
}
I've done something similar using a handler. When the handler recieves it's response from a thread, you can dismiss your progressdialog.
Some code to help you understand:
final Handler handler = new Handler()
{
#Override
public void handleMessage( Message message )
{
progressBar.setVisibility( View.GONE );
// My irrelevant code here
}
};
new Thread( new Runnable()
{
public void run()
{
// Do your stuff here
Message message = handler.obtainMessage( 1, text );
handler.sendMessage( message );
}
}).start();
Instead of calling another Activity class to do your downloading, move this functionality into another class that each Activity can use.

How do I show and then remove an android progress dialog

I can get a progress bar to appear with the following code
pd = ProgressDialog.show(myActivity.this, "", "Loading. Please wait...", true);
straight forward, but once I have the code execute I want it to go away, but when I run the dismiss method after I never see the dialog box show at all.
Heres the code in context which is wrapped in oncreate
pd = ProgressDialog.show(myActivity.this, "", "Loading. Please wait...", true);
runCode();
setListAdapter(new CustomAdapter(myActivity.this));
pd.dismiss();
I thought you can show/dismiss progress dialog's anywhere in the activity but I must be wrong.
here is the code that I got to work
private class UpdateFeedTask extends AsyncTask<MyActivity, Void, Void> {
private ProgressDialog mDialog;
protected void onPreExecute() {
Log.d(TAG, " pre execute async");
mDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected void onProgressUpdate(Void... progress) {
Log.d(TAG, " progress async");
}
#Override
protected Void doInBackground(MyActivity... params) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Void result) {
Log.d(TAG, " post execute async");
mDialog.dismiss();
}
}
refer the sample code sinnpet of mine,hope this may help you
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ProgressBar;
public class PlayActivity extends Activity {
/** Called when the activity is first created. */
private ProgressBar mProgress;
private int mProgressStatus = 0;
private int count=0;
private Handler mHandler=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgress = (ProgressBar) findViewById(R.id.ProgressBar01);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (mProgressStatus<=100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
mProgressStatus=mProgressStatus+10;
count=mProgressStatus;
Log.d("mProgressStatus",Integer.toString(count));
mProgress.setProgress(mProgressStatus);
if(count > 80)
{
Log.d("mProgressStatus",Integer.toString(mProgressStatus));
counter.start();
}
}
};
};
}
To remove a progressBar
ProgressBar progressbar = (ProgressBar)findViewById(R.id.progressbarID);
progressBar.setVisibility(View.INVISIBLE) ;
hide the progressbar in xml and show it like
ProgressBar progressbar = (ProgressBar)findViewById(R.id.progressbarID);
progressBar.setVisibility(View.VISIBLE) ;

Categories

Resources