Using AsyncTask to start activity - android

I am using asyncTask to show Dialog and then after few minutes then launch a new activity.
unfortunately that activity start before task finished ???
package com.android.grad;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.Toast;
public class LoginTask extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
private ProgressDialog pd;
public LoginTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(activity, "Signing in",
"Please wait while we are signing you in..");
}
#Override
protected Boolean doInBackground(Void... arg0) {
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
}
pd.dismiss();
return true;
}
#Override
protected void onPostExecute(Boolean result) {
Toast.makeText(activity, Boolean.toString(result), Toast.LENGTH_LONG).show();
}
}
and i execute the task from button click listener :S
private OnClickListener loginOnClick = new OnClickListener() {
public void onClick(View v) {
new LoginTask(LoginActivity.this).execute();
startActivity(new Intent(LoginActivity.this, BuiltInCamera.class));
}
};
Is there way to startActivity from my subClass ofAsyncTask .

Yes, you can start activity from AsyncTask's sub class. See below:
#Override
protected void onPostExecute(Boolean result) {
Toast.makeText(activity, Boolean.toString(result), Toast.LENGTH_LONG).show();
activity.startActivity(new Intent(activity, BuiltInCamera.class));
}
After making this change, make sure you do remove startActivity from OnClickListener

Call this startActivity(new Intent(LoginActivity.this, BuiltInCamera.class)); from onPostExecute() after Displaying toast message.
In this way, new activity will be called after your AsyncTask is over.

You can also use
Intent intent = new Intent(activity, PageViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.getApplicationContext().startActivity(intent);

Call startActivity inside onPostExecute method of AsyncTask

Related

ProgressDialog doesn't show with I using intent in Android

Everything is working fine, and the second Activity is running but My progress Dialog doesn't appear when I using Intent.
Is there an error in the code? , I can't find stack.
an idea ???
Please help me , Thanks!
public class StartActivity extends AppCompatActivity {
private Intent mIntent;
private final int totalProgressTime = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
public void onClick(View view) {
new DownloadTask().execute();
mIntent = new Intent(this, MainActivity.class);
startActivity(mIntent);
}
private class DownloadTask extends AsyncTask<String,Void,Object>{
ProgressDialog mIndicator = new ProgressDialog(StartActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
mIndicator.setMessage("Wait..");
mIndicator.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mIndicator.setProgress(0);
mIndicator.setMax(totalProgressTime );
mIndicator.show();
new Thread(new Runnable() {
#Override
public void run(){
int counter = 0;
while(counter < totalProgressTime ){
try {
Thread.sleep(300);
counter ++;
mIndicator.setProgress(counter);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mIndicator.dismiss();
}
}).start();
}
#Override
protected Object doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
mIndicator.dismiss();
}
}
}
Let's not talk about how wrong is to use AsyncTask as you used it here. I suppose you have some bigger picture, and this is just some test snippet.
So with
new DownloadTask().execute();
you started AsyncTask.
And just after that you started new activity:
mIntent = new Intent(this,MainActivity.class);
startActivity(mIntent);
So, AsyncTask continue to work in separate thread, but StartActivity is no longer active (probably not even visible), because MainActivity is in foreground now.
So, you want to see ProgressBar in StartActivity, but you are in MainActivity.
Try to wait AsyncTask to finish, than start MainActivity.
#Override
protected void onPostExecute(Object o) {
mIndicator.dismiss();
mIntent = new Intent(this, MainActivity.class);
startActivity(mIntent);
}

How to use intent in Asynctask class?

Please share how to use intent in doinbackground() or onpostexecute() methods Asynctask class.When I tried to use these codes it shows error.
Intent intent = new Intent(asynctask.this, home.class);
startActivity(intent);
finish();
private Class<Home> clazz;
public asynctask(Class<Home> clazz){
this.clazz = clazz;
}
Asynctask doInBackground() method:
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, clazz);
startActivity(intent);
finish();
Toast.makeText(cxt, "welcome", Toast.LENGTH_SHORT).show();
return null;
}
Try this way,hope this will help you to solve your problem.
How to asynctask class :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyCustomAsyncTask(this).execute();
}
MyCustomAsyncTask.java
public class MyCustomAsyncTask extends AsyncTask<Void,Void,Void> {
private Context context;
public MyCustomAsyncTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
// write show progress Dialog code here
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// write service code here
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(context, "welcome", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, home.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
Move this Intent part in onPostExecute(...) method of AsynckTask
doInBackground(Void... arg0) should do only background task
you should put other code in onPostExecute(...) method. so that when background task is over move to other activity.
** Don't try to touch UI from doInBackground(....) your app may crash.
You cann't interact with UI in doInBackground(....). you can only interact with UI in onPostExecute(...). Just like thread you cann't interact with UI in Thread for UI we use Handler.
Always put intent in onPostExecute. This will ensure that your UI thread is in sync.
For example if your want to show that on receiving right credentials the user should move to next activity or else should be shown a message "Invalid credentials" in case they're wrong. Your onPostExecute should look like this:
protected void onPostExecute(final Boolean success) {
if(success){
Intent intent = new Intent(<CurrentActivity>.this, <NextActivity>.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}

Cannot run the async example ..?

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.

how to add progress dialog in button with asynctask

i try this Tutorial
i still confused how to add progress dialog in button logout with asynctask
here is my activity.
package hariff.ltis.mainmenu;
import hariff.ltis.inputhama.CInputHamaApp;
import hariff.ltis.library.DatabaseHandler;
import hariff.ltis.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import hariff.ltis.mainmenu.R;
public class MainMenu extends Activity{
UserFunctions userFunctions;
Button btnLogout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.main);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
loadUser();
View button3Click = findViewById(R.id.button3);
button3Click.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// Perform action on click
DataHama();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
/*private void InputData(){
Intent i = new Intent(this, SaveData.class);
startActivity(i);
}
private void CheckData(){
Intent i1 = new Intent(this, CheckData.class);
startActivity(i1);
}*/
private void loadUser() {
TextView txt = (TextView) findViewById(R.id.textUser);
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
SQLiteDatabase dbs = db.getReadableDatabase();
Cursor cursor = dbs.rawQuery("SELECT * FROM login", null);
if (cursor.moveToFirst()) {
do {
String emailid=cursor.getString(2); // Here you can get data from table and stored in string if it has only one string.
txt.setText(emailid);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
if(db!=null)
{
db.close();
}
// Creating adapter for spinner
}
private void DataHama(){
Intent i2 = new Intent(this, CInputHamaApp.class);
startActivity(i2);
}
}
so when i click button logout, the progress dialog show and have a time, example 5 second. how to do that?
the button logout EDIT :
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
logoutUserOperation loguttask = new logoutUserOperation(MainMenu.this);
loguttask.execute("");
}
});
here is the logoutUser function
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
EDIT: here is the asynctask
private class logoutUserOperation extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressDialog;
Context context;
public logoutUserOperation(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", "Logout...");
}
#Override
protected Boolean doInBackground(String... params) {
boolean boollogout=userFunctions.logoutUser(context);
return boollogout;
}
#Override
protected void onPostExecute(Boolean result) {
progressDialog.dismiss();
if(result){
Intent login = new Intent(context,LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(login);
// Closing dashboard screen
context.finish();
}else{
// your code here...
}
}
}
when i try but show error
The method finish() is undefined for the type Context
BR
Alex
EDIT : this is the code to sleep 5 second
protected Boolean doInBackground(String... params) {
boolean boollogout=userFunctions.logoutUser(context);
try{
Thread.sleep( 5000 );
} catch( Exception e ){
Log.i("Logout", e.getMessage() );
}
return boollogout;
}
you can show ProgressDialog on button click using AsyncTask as:
private class logoutUserOperation extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressDialog;
Context context;
public logoutUserOperation(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", "Logout...");
}
#Override
protected boolean doInBackground(String... params) {
boolean boollogout=userFunctions.logoutUser(context);
return boollogout;
}
#Override
protected void onPostExecute(boolean result) {
progressDialog.dismiss();
if(result){
Intent login = new Intent(context,
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(login);
// Closing dashboard screen
context.finish();
}else{
// your code here...
}
}
}
and start AsyncTask as on button click :
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
logoutUserOperation loguttask = new logoutUserOperation(MainMenu.this);
loguttask.execute("");
}
});

show progressbar on button click when going from 1 intent to other and data is coming from server

I have a button in one page and when I click on that button I
am able to go another activity through Intent(), but onbuttonclick()
in which activity I am going in that activity data in spinner
coming from server means on button click
I load that data on spinner from server.so it takes times for moving my button click activity
to other activity so I want to show progress bar when my button is clicked
and untill data is not coming from server...how to achieve this..and I want to show progress bar
on buttonclick page means on my first activity when I click the button.
My code of of on button click is given below.
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
});
Actually I know asynchronous task but using this I will be able to show progress bar on 2nd activity, I want to show it on my first activity until data is not loaded in second activity, so I want progree bar above the button on first activity, and when data is loaded on second activity it moves to second.
You need to use AsyncTask as the way I am guiding here.
Create Async Task in first activity. On button click event call that AsyncTask. In background do loading data from server. and onPostExecute start second activity
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
new ProgressTask(MyClassName.class).execute(null);
}
});
Async Task
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
protected Boolean doInBackground(final String... args) {
try{
//load data from server
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Thanks
Deepak
have a look at this code
package com.exercise.AndroidBackgroundThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidBackgroundThread extends Activity {
Thread backgroundThread;
TextView myText;
boolean myTextOn = true;
boolean running = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
void setRunning(boolean b){
running = b;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();
backgroundThread = new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage());
}
}
});
setRunning(true);
backgroundThread.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
}
}
and for more detail look at this guide http://tech-aamir.blogspot.in/2012/06/how-to-make-progress-bar-when.html
Best of luck
aamirkhan i.
To build on the first answer, since you are familiar with AsyncTask. You can have the AsyncTask perform the work to retrieve whatever data you'll need in your first activity. And during that process, you display your progress bar. Once the AsyncTask completes, you remove the progress bar, put your data in a bundle (by calling putExtras), and send it off with your intent to start the 2nd Activity.
You can use the ProgressBar or ProgressDialog in the currentlocmap class.
Use AsyncTask class for that and when the data is fetched, set the layout using setContentView() and dismiss the ProgressDialog.
Refer to these links:
Fetch data from server and refresh UI when data is fetched?
How to start and finish progressBar dynamically in android

Categories

Resources