AsyncTaskbackbutton - android

am able to sucessfully get data from the server.if data is success then am navigating NextScreen.1. if backbutton pressed when getting data then AsyncTask Dialog disappear, but after sometime it navigates to Nextscreen activity. so if i press backbuttob asyn task has to cancel and it should not navigate to next activity.
public class Screenone extends Activity {
EditText user,pass;
Button login;
InputStream is;
String productResponse;
EditText edit;
int responseCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainlog);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ((user.getText().length() > 0)
&& (pass.getText().length() > 0) ) {
new Load().execute(Status);
}
}
});
}
private class Load extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(LoginScreen.this);
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected String doInBackground(String... status) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("---url---");
responseCode =httpResponse.getStatusLine().getStatusCode();
}
catch (Exception e) {
}
return null;
}
protected void onPostExecute(String Result) {
// TODO Auto-generated method stub
super.onPostExecute(Result);
if (responseCode==200) {
Dialog.dismiss();
Intent intent =new Intent(Screenone.this, NextScreen.class);
startActivity(intent);
}
}
}
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
moveTaskToBack(true);
}
}

OK the problem is that you have no reference to your asynctask. Try creating a property in your Activity for the asynctask:
private Load myAsyncTask;
now in your onClick method:
myAsyncTask=new Load();
myAsyncTask.execute(Status);
and finally in your onBackPressed:
public void onBackPressed() {
super...
if(myAsyncTask!=null)
myAsyncTask.cancel(true);
}

you will need to Cancel AsyncTask, dismiss ProgressDialog and also abort HttpPost before moving back from current Activity . try it as :
#Override
public void onBackPressed() {
if(Load!=null){
if(!Load.getStatus() == AsyncTask.Status.FINISHED){
// first abort Httppost request
// post.abort();
httpclient.getConnectionManager().shutdown();
// now dismiss ProgressDialog
if (Dialog!=null&&Dialog.isShowing()) {
Dialog.dismiss();
}
// now cancel AsyncTask if running
if(Load.getStatus() == AsyncTask.Status.RUNNING){
Load.cancel(true);
}
}
}
}

Related

Confused about Simple Asyntask app

I am trying to make a simple AsynTask sample. I can't make it run. When I click the Button, ProgressDialog is supposed to be displayed. But nothing happens. I don't get any Exceptions. Probably I'm missing out a few things.
ProgressDialog dialog=null;
Button btnstart;
MyAsynTask mytask;
static final int SLEEP_TIME=(15*1000)/100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=(Button)findViewById(R.id.button1);
btnstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mytask=new MyAsynTask();
mytask.execute();
}
});
}
public class MyAsynTask extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
if(isCancelled()){
break;
}
else {
publishProgress(i);
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
You are doing it right.
Use Logs in onPreExecute(),doInBackBackground() to see what's happening actually.
Add one more method to Asynctask class
onPostExcute()
{
dialog.dismiss();
}
OnPost method in the asynctask excutes after doinbackgournd method there you need to dismiss the dialog

Displaying error message in an activity from a seperate public asyncTask class

I am creating the user registration part of my app. I am using the AsyncTask class to handle this work on a separate thread. I have my AsyncTask class in a seperate class file. This
public class CreateAccountTask extends AsyncTask<String, Void, String>{
private ProgressDialog mpDialog;
private CreateAccountTask task;
private Context context;
private Activity activity;
private CreateAccount createAccount;
private AsyncTaskListener asyncTaskListener;
public CreateAccountTask(Activity activity, AsyncTaskListener asyncTaskListener){
this.activity = activity;
this.asyncTaskListener = asyncTaskListener;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mpDialog = new ProgressDialog(activity);
//mpDialog.setTitle("Creating Account");
mpDialog.setMessage("Please wait.");
mpDialog.setCancelable(false);
mpDialog.setIndeterminate(false);
mpDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//task.cancel(true);
mpDialog.dismiss();
}
});
mpDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String fphoneNo = arg0[1];
String fpassword = arg0[0];
// create instance of the parseUser Class
ParseUser newUser = new ParseUser();
newUser.setUsername(fphoneNo);
newUser.setPassword(fpassword);
// here Check if progress dialog has been cancelled
if (!isCancelled()){
// if dialog has not been cancelled create the new user here
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
// Something went wrong Sorry!
if(e != null ){
if(!isCancelled()){
mpDialog.dismiss();
String errorMessage = e.getMessage().toString();
ErrorHappened(errorMessage);
}
else{
String errorMessage = "Registration Cancelled!";
ErrorHappened(errorMessage);
}
}
// No Problems
else {
if (!isCancelled()) {
// Wait for five seconds before starting the activity
//verifyingUser();
}
else {
String errorMessage = "Registration Cancelled2!";
ErrorHappened(errorMessage);
//Delete user in background
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
currentUser.deleteInBackground();
}
}
}
}
});
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
asyncTaskListener.onTaskComplete(result);
}
private void ErrorHappened(String errorMessage) {
Crouton CreateMagic = Crouton.makeText(createAccount, errorMessage, CroutonClass.ALERT);
CreateMagic.setConfiguration(CroutonClass.configure);
CreateMagic.show();
}
}
In my onPreExecute method, i start a progressDialog that shows while the background task is being executed. While in my doInBackground method i have i get the username and password supplied by the user in the main Activity and sign up the user. This is where my problem begins, If an error occurs during the user registration, i want to notify the user of this error using a Crouton (A cooler version of a toast). But the app crashes when it gets to the point of displaying the error with the crouton.
My question is:
How do i display the error message in my activity?
2.
here is my Activity:
public class CreateAccount extends ActionBarActivity implements AsyncTaskListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
mPassWord = (EditText) findViewById(R.id.password);
mcreateAccount = (Button) findViewById(R.id.createAcct);
mPhoneNumber = (EditText) findViewById(R.id.Phone_Number);
// create account Method
createAccount();
}//end of on create.
public void createAccount() {
mcreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
CreateAccountTask newTask = new CreateAccountTask(CreateAccount.this, new CreateAccount());
newTask.execute(passwordString, fpartphoneNo);
});
}
private void verifyingUser() {
}
private void shitHappened(String errorMessage) {
// TODO Auto-generated method stub
Crouton CreateMagic = Crouton.makeText(this, errorMessage, CroutonClass.ALERT);
CreateMagic.setConfiguration(CroutonClass.configure);
CreateMagic.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Crouton.cancelAllCroutons();
super.onBackPressed();
}
#Override
public void onTaskComplete(String result) {
// TODO Auto-generated method stub
}
}
Notifications and any other UI manipulation is only allowed from the UIThread. If you look at the documentation of AsyncTask, doInBackground() runs on its own Thread, while onPreExecute(), onPostExecute() and onCancelled() run on the UIThread.
In your case, you should use protected void onCancelled(String result) for the Notification. This runs on the UIThread and helps you to distinguish between a successful and unsuccessful operations. To use this, call cancel() and check in doInBackground() if the operation was cancelled.
onCancelled() will then be executed instead of onPostExecute()
In your special case it could be a problem of the context, because you are storing your CreateAccount.this in the constructor in activity of your CreateAccountTask, but you are using createAccount. Try changing it to the following:
Crouton.makeText(activity, errorMessage, CroutonClass.ALERT);
Use runOnUiThread as below...
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
mpDialog = new ProgressDialog(activity);
//mpDialog.setTitle("Creating Account");
mpDialog.setMessage("Please wait.");
mpDialog.setCancelable(false);
mpDialog.setIndeterminate(false);
mpDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//task.cancel(true);
mpDialog.dismiss();
}
});
mpDialog.show();
}
}

BadTokenException in Asynctask progress dialog

i'm new to android,this maybe simple question but i cant able to find the answer for it,i'm using tabactivity while changing the activities the bottom tab's are missing so i
used below code to hold the tab by changing the view,so it works fine
public void replaceContentView(String id, Intent newIntent) {
try {
#SuppressWarnings("deprecation")
View view = getLocalActivityManager().startActivity(id,
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
} catch (Exception e) {
e.printStackTrace();
}
}
Actually my problem is i want to select something from 2nd activity to 1st ActivityGroup,in the 2nd activity i have one button called done
Here is my 2nd activity
public class Woosuite_Twiter_Feed_list extends Activity implements
OnItemClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.woosuite_twitlist);
Button done = (Button) findViewById(R.id.btn1);
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(v.getContext(), Woosuite_Feed.class);
i.setClass(getParent(), Woosuite_Feed.class);
Woosuite_Feed feed = (Woosuite_Feed) getParent();
feed.replaceContentView("one", i);
}
});
while clicking done button in 2nd activity then first activitygroup asyncTask class is called,in that i'm getting
Android: “BadTokenException: Unable to add window; is your activity running?
i dont know how to solve this,please provide some solution.
here is my 1st ActivityGroup oncreate
public class Woosuite_Feed extends ActivityGroup implements OnClickListener
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.woosuite_feed);
LinkedFeeds feeds = new LinkedFeeds();
feeds.execute("");
}
Here is my 1st ActivityGroup AsyncTask
public class LinkedFeeds extends AsyncTask<String, Void, String> {
public ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
if(!isFinishing()){
dialog = new ProgressDialog(Woosuite_Feed.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
}
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
}
Thanks

backbutton for asyncTask

am able to sucessfully get data from the server.if data is success then it navigates to NextScreen.
1. if i press back button before data is appeared then Asyntask has to disappear and it should not navigates to NextScreen.it has to stay in Screenone only.
but if i press backbutton dailog disappearing after some few seconds it navigating to the NextScreen.so how to stop this.
public class Screenone extends Activity {
EditText user,pass;
Button login;
InputStream is;
String productResponse;
EditText edit;
int responseCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainlog);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ((user.getText().length() > 0)
&& (pass.getText().length() > 0) ) {
new Load().execute(Status);
}
}
});
}
private class Load extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(LoginScreen.this);
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected String doInBackground(String... status) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("---url---");
responseCode =httpResponse.getStatusLine().getStatusCode();
}
catch (Exception e) {
}
return null;
}
protected void onPostExecute(String Result) {
// TODO Auto-generated method stub
super.onPostExecute(Result);
if (responseCode==200) {
Dialog.dismiss();
Intent intent =new Intent(Screenone.this, NextScreen.class);
startActivity(intent);
}
}
}
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
LoginScreen.Load xx = new LoginScreen().new Load();
if(new Load()!=null){
if(!(new Load().getStatus() == AsyncTask.Status.FINISHED)){
httpclient.getConnectionManager().shutdown();
if (xx.Dialog!=null&&xx.Dialog.isShowing()) {
xx.Dialog.dismiss();
}
if(new Load().getStatus() == AsyncTask.Status.RUNNING){
new Load().cancel(true);
}
}
}
}
}
you will need to start next Activity on Back Button Click after AsyncTask canceled as :
if(new Load().getStatus() == AsyncTask.Status.RUNNING){
new Load().cancel(true);
// start Next Activity here...
Intent intent =new Intent(Screenone.this, NextScreen.class);
startActivity(intent);
}

Android splash screen and server communication

I am developing an application in android, where i need to display a splash screen and at the same time there will be server communication. The problem here is when i launch the app, first application is communicating with the server and then it is displaying the splash screen. I want to both server communication and splash screen at the same time.
The following is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
Thread thread = new Thread(this);
thread.start();
thread.join();
//Attractions
CommonMethods.getSystemOutput("Response Json Array String Attractions:::"+jArrayMobileAttractions);
attractionsDate = JsonParsing.getLatestDate(jArrayMobileAttractions);
attractionsDate = getDate(attractionsDate);
CommonMethods.getSystemOutput("Attractions Date:::::"+attractionsDate);
//Categories
CommonMethods.getSystemOutput("Response Json Array String Categories:::"+jArrayCategories);
categoryDate = JsonParsing.getLatestDate(jArrayCategories);
categoryDate = getDate(categoryDate);
CommonMethods.getSystemOutput("Category date:::"+categoryDate);
//Contacts
CommonMethods.getSystemOutput("Response Json Array String Contacts:::"+jArrayContacts);
contactsDate = JsonParsing.getLatestDate(jArrayContacts);
contactsDate = getDate(contactsDate);
CommonMethods.getSystemOutput("Contacts Date:::"+contactsDate);
} catch (Exception e) {
CommonMethods.getSystemOutput("Exception in Splash screen thread:::"+e);
}
}
public void run() {
// if (attractionsDate == null) {
jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL);
jArrayCategories = RequestHandler.getJSONfromURL(Constants.CATEGORY_URL);
jArrayContacts = RequestHandler.getJSONfromURL(Constants.CONTACTS_URL);
// } else {
// jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL+"?lastupdateddate="+attractionsDate);
// }
}
You can use the AsynchTask Manager in which it has a method
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Do Server Interaction Here
return response;
}
#Override
protected void onPreExecute(String result) {
//Show your Splash Screen
}
#Override
protected void onPostExecute(String result) {
//Gone the Splash Screen view
}
}
For this purpose it will be better start from "SplashActivity" - in onCreate() start new Thread for communication with server, and when all communication finished - call startActivityForResult(mainActivityIntent). For correct behavior back button finish splash activity on finish main activity. Approximate code:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setup view for activity
new Thread(new Runnable() {
public void run() {
// do here some long operation
startActivityForResult(new Intent(SplashActivity.this, MainActivity.class), 0);
}
}).start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
finish();
}
}
I had the same thing to do and I did it this way and it works just fine. I had to show the splashscreen and download some file from the server, unzip it, move files insto proper directories and then start the apps main screen. Here is the code, I used AsyncTask.
So, you have three AsyncTask classes, one for each task and in the onPostExecute() I call the next AsyncTask. I can't say if this is the best way but it works for me.
I removed unneccessary code but for clarity I left a call to a dialog where I ask a user ih he wants to proceed with downloading as it may take a while. Also I check if FIRST_RUN is true just so I know if I should download the package since for my app I need to do it only the first time, so if it is true I do the spashscreen activities and if it is false I proceed to MAINAPP activity.
Hope it helps.
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
boolean firstRun = settings.getBoolean("FIRST_RUN", true);
if (firstRun) {
showDialog(INITIAL_DLG);
} else {
startActivity(new Intent(appContext, MAINAPP.class));
}
}
/***
* First entry after YES on Dialog!
*/
protected void initialize() {
messageTV.setVisibility(TextView.VISIBLE);
progressBar.setVisibility(ProgressBar.VISIBLE);
downloadThread = new DownloadFiles();
downloadThread.execute();
}
protected void rollback() {
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
switch (id) {
case INITIAL_DLG:
builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.app_setup)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
initialize();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDlg = builder.create();
return alertDlg;
default:
return null;
}
}
protected class DownloadFiles extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//file download
} catch (Exception e) {
result = false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
unzipThread = new DecompressZipFile();
unzipThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 1/4:Downloading data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class DecompressZipFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//unzip files
return true;
} catch(Exception e) {
return false;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0]<0) progressBar.setMax(values[0]*-1);
else progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
moveDBThread = new MoveDBFile();
moveDBThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 2/4:Decompressing data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class MoveDBFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//moving files
return true;
} catch (Exception e) {
globalE = e;
finish();
return false;
}
}
#Override
protected void onPreExecute() {
messageTV.setText("Step 3/4:Shufflin'...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
getSharedPreferences(PREFS_NAME,0).edit().putBoolean("FIRST_RUN", false).commit();
startActivity(new Intent(appContext, MAINAPP.class));
} else {
rollback();
}
}
}
}

Categories

Resources