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();
}
}
Related
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);
}
I have this async task that call an web service and parse an xml
#Override
protected void onPreExecute(){
super.onPreExecute();
time = System.currentTimeMillis();
}
protected Boolean doInBackground(Integer... params) {
//code
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
}
while async task is executing I want to display an loading screen,but the loading screen finishes before async task finish if I am doing like this
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
final CallWebService callTarif = new CallWebService(6,sett.getDeviceId());
callTarif.execute();
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
}
}
},callTarif.difftime);
Actually postDelayed is called before completing the AsyncTask.
Just put these code lines
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
in opPostExecute() of AsyncTask.
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
}
And remove Handler new Handler().postDelayed(new Runnable(){
start your loading screen onPreExecute method and kill it onPostExecute method of the async task
No need to use Handler for showing loading when accessing webservice using async task . use onPreExecute() method of AsyncTask to Show loading Screen and finish it inside onPostExecute because this method called when doInBackground execution complete . change code code as :
#Override
protected void onPreExecute() {
// show loading bar here
}
#Override
protected String doInBackground(String... params) {
// do network operation here
return null;
}
#Override
protected void onPostExecute(String result) {
// dismiss loading bar here
}
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
Am I doing it right?
I have a Splash screen (just an image), and onCreate() I start the main activity after running a heavy function:
SPLASH_DISPLAY_LENGHT=2500;
new Handler().postDelayed(new Runnable(){
public void run() {
LONG_OPERATING_FUNCTION();
Intent mainIntent = new Intent(this, MainActivity.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
I think I have a memory leak, and I'm trying to find it.
I don't think the Splash really is finishing.
LONG_OPERATING_FUNCTION() should not be done on the main application thread, as you have it here.
Ideally, you do not use a splash screen, but rather only enable selected features of MainActivity while do your LONG_OPERATING_FUNCTION() in an AsyncTask or something.
If somebody is pointing a gun at your head and forcing you to implement a splash screen lest it be your brains that get, er, splashed, I would do this:
Eliminate your Handler and postDelayed() call
Replace that with an AsyncTask
In doInBackground() of AsyncTask, do your LONG_OPERATING_FUNCTION()
If, when LONG_OPERATING_FUNCTION() is done, SPLASH_DISPLAY_LENGHT [sic] time has not elapsed, use SystemClock.sleep() to sleep for the remaining time (or not)
In onPostExecute(), start MainActivity and call finish()
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
openingSound = MediaPlayer.create(Splash.this, R.raw.applause);
openingSound.start();
setContentView(R.layout.firstanimal);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openingSplash = new Intent("com.softech.LearnAnimal1.STARTINGPOINT");
startActivity(openingSplash);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
openingSound.release();
finish();
}
This is a complete java code in this u'll have openingSound with 5 seconds break and then u it'll move on your menu or second activity but remeber one thing u also have to put activity with intent filters in your manifest :)
Enjoy :)
Intent intent = new Intent(getApplicationContext(), AActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
通过使用getApplicationContext()的context就不会内存溢出;
public class RunnableActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("RunnableActivity onCreate");
setContentView(R.layout.activity_main);
mHandler.postDelayed(mRunnable, 3000);
}
#Override
protected void onResume() {
super.onResume();
System.out.println("RunnableActivity onResume");
}
#Override
protected void onPause() {
super.onPause();
System.out.println("RunnableActivity onPause");
}
#Override
protected void onDestroy() {
super.onDestroy();
System.out.println("RunnableActivity onDestroy");
}
private Handler mHandler = new Handler(Looper.getMainLooper());
private Runnable mRunnable = new Runnable() {
private WeakReference<Activity> weak = new WeakReference<Activity>(RunnableActivity.this);
#Override
public void run() {
Activity a = weak.get();
if (a != null) {
Intent intent = new Intent(a.getApplicationContext(), AActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
a.getApplicationContext().startActivity(intent);
a.finish();
}
}
};}
My app frequently throws exception like below:
E/WindowManager( 6282): android.view.WindowLeaked: Activity
com.myActivity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView#4479b710 that
was originally added here
The app shows a progress dialog when the main activity starts and starts a task. When the task is done, it will dismiss the progress dialog.
My code is like below. Can someone help me?
public class MyActivity extends Activity {
private static int ID_DIALOG_PROGRESS = 2001;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
showDialog(ID_DIALOG_PROGRESS);
new MyTask().execute(null, null, null);
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == ID_DIALOG_PROGRESS) {
ProgressDialog loadingDialog = new ProgressDialog(this);
loadingDialog.setTitle("");
loadingDialog.setMessage("");
loadingDialog.setIndeterminate(true);
loadingDialog.setCancelable(false);
return loadingDialog;
}
return super.onCreateDialog(id);
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
/* Do something expensive here...*/
/* Start other activity*/
Intent intent = new Intent(MyActivity.this, OtherActivity.class);
startActivityForResult(intent, 1000);
}
return null;
}
protected void onPostExecute(Void arg0) {
dismissDialog(ID_DIALOG_PROGRESS);
}
}
}
Most of the time, the exception was thrown from showDialog() call. The other time, the exception was thrown from dismissDialog() call.
Thank you in advance!
You're starting a new activity in doInBackground() before you dismiss the dialog in onPostExecute(), which is probably what is causing the dialog to leak. I would move
Intent intent = new Intent(MyActivity.this, OtherActivity.class);
startActivityForResult(intent, 1000);
to onPostExecute() after the dismissDialog() call and see what happens.
It's also good practise to place a try...catch around
dismissDialog(ID_DIALOG_PROGRESS);
Otherwise you will probably receive random application crashes when under some circumstances the dialog is not available anymore e.g. after screen rotation.