doInBackground process in AsyncTask Android doesn't work - android

I have the code which execute AsyncTask to call API, but there is nothing going on when I tried to debug it. The pointer exit from onPreExecute and not get in to doInBackground. I don't know why.
class MasterBrand extends AsyncTask<String, String, AsyncTaskResult<ResponBrand>> {
private ProgressDialog dialog;
#Override
protected void onPostExecute(AsyncTaskResult<ResponBrand> s) {
Log.e("", "CollectionResult.onPostExecute");
try{
if (dialog.isShowing()) {
dialog.dismiss();
}
}catch (Exception e){
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("", "CmoProductivity.onPreExecute");
dialog = new ProgressDialog(getActivity());
dialog.setCancelable(false);
dialog.setMessage("harap tunggu sebentar...");
dialog.show();
}
#Override
protected AsyncTaskResult<ResponBrand> doInBackground(String... params) {
ResponBrand cmoPoDp = new ResponBrand();
try
{
Type listTypeTaskHeader = new TypeToken<ResponBrand>() {}.getType();
JSONHttpClient jsonHttpClient = new JSONHttpClient();
List<NameValuePair> argsTaskHeader = new ArrayList<NameValuePair>();
Log.e("", "Get Task Header Data");
cmoPoDp = jsonHttpClient.Get(StringAPIurl, argsTaskHeader, ResponBrand.class);
}
catch (Exception e) {
if (dialog.isShowing()) {
dialog.dismiss();
}
Log.e("", e.getMessage());
e.printStackTrace();
}
return new AsyncTaskResult<ResponBrand>(cmoPoDp);
}
}
How can I fix this?

Related

How to make a Main Thread waiting for the AsyncTask android, without blocking the UI

I am trying to make login view.
I' d like to start a new AsyncTask that performs the REST call to the server and shows a progress bar. I need that the UI main thread wouldn't block and it must show a toast with message (like success or fail) depending on what the AsyncTask returns .
Here the code:
SetupActivity (main thread):
//Get reference SignUp Button
Button signupButton = (Button)myDialog.findViewById(R.id.button_signup_OK);
signupButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get all the textfield content from the form
name=((EditText)myDialog.findViewById(R.id.nameEditText)).getText();
surname=((EditText)myDialog.findViewById(R.id.surnameEditText)).getText();
email=((EditText)myDialog.findViewById(R.id.emailEditText)).getText();
password=((EditText)myDialog.findViewById(R.id.passwordEditText)).getText();
password_Retyped=((EditText)myDialog.findViewById(R.id.passwordRepEditText)).getText();
//Get hash from password
hashPassword=DigestMd5.md5(password);
hashPasswordRep=DigestMd5.md5(password_Retyped);
//Check if the fields are null
if(name.toString().equals("")){
((EditText) myDialog.findViewById(R.id.nameEditText)).setError(getString(R.string.mandatoryField));
}
if(surname.toString().equals("")){
((EditText) myDialog.findViewById(R.id.surnameEditText)).setError(getString(R.string.mandatoryField));
}
if(email.toString().equals("") ){
((EditText) myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.mandatoryField));
}else{
if(!new EmailValidator().validate(email.toString())){
((EditText)myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.emailWrong));
}
}
if(password.toString().equals("")){
((EditText) myDialog.findViewById(R.id.passwordEditText)).setError(getString(R.string.mandatoryField));
}
if(password_Retyped.toString().equals("")){
((EditText) myDialog.findViewById(R.id.passwordRepEditText)).setError(getString(R.string.mandatoryField));
}
//Check match password
if(!hashPassword.equals(hashPasswordRep)){
((EditText)myDialog.findViewById(R.id.passwordEditText)).setError(getString(R.string.passwordNotMatching));
((EditText)myDialog.findViewById(R.id.passwordRepEditText)).setError(getString(R.string.passwordNotMatching));
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//Start AsyncTask
new loadingBar().execute().get();
Boolean resultOK = ackJSON.has("result");
if(resultOK){
//close dialog
myDialog.dismiss();
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_success,(ViewGroup) findViewById(R.id.custom_toast_layout_id));
Toast toastOK = new Toast(getApplicationContext());
toastOK.setDuration(Toast.LENGTH_LONG);
toastOK.setView(layout);
toastOK.show();
}else{
//Feedback both using Toasts and textedit
((EditText) myDialog.findViewById(R.id.emailEditText)).setError(getString(R.string.userAlreadyIn));
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_erroruser,(ViewGroup) findViewById(R.id.custom_toast_no_user));
Toast toastNoUser = new Toast(getApplicationContext());
toastNoUser.setDuration(Toast.LENGTH_SHORT);
toastNoUser.setGravity(Gravity.TOP,0,50);
toastNoUser.setView(layout);
toastNoUser.show();
}
} catch (IOException e) {
// Inflate the Layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_errorconnection,(ViewGroup) findViewById(R.id.custom_toast_no_noConn));
Toast toastNoConn = new Toast(getApplicationContext());
toastNoConn.setDuration(Toast.LENGTH_SHORT);
toastNoConn.setGravity(Gravity.TOP,0,50);
toastNoConn.setView(layout);
toastNoConn.show();
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
class loadingBar extends AsyncTask<Void,Integer,JSONObject>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setProgress(0);
progress.show();
}
#Override
protected JSONObject doInBackground(Void... arg0)
{
ackJSON = null;
try
{
for(int i=0;i<2;i++)
{
publishProgress(new Integer[]{i*10});
Thread.sleep(1200);
}
String ack=HTTPRest.putNewUser(name.toString(),surname.toString(),email.toString(),hashPassword);
ackJSON=new JSONObject(ack);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ackJSON;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progress.dismiss();
ackJSON=result;
}
}
Please let me know for any error in code
Thank you
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
//checkLogin(email, password);
new AttemptLogin().execute();
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
class AttemptLogin extends AsyncTask<String, String, String>{
/** * Before starting background thread Show Progress Dialog * */
boolean failure = false;
#Override protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(AppConfig.URL_LOGIN, "POST", params);
// checking log for json response
//devraj......................
Log.d("Login attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1){
session.setLogin(true);
Log.d("Successfully Login!", json.toString());
Intent intent = new Intent(LoginActivity.this,Secondpage.class);
startActivity(intent);
return json.getString(TAG_MESSAGE);
}
else{
return json.getString(TAG_MESSAGE);
}
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
/** * Once the background process is done we need to Dismiss the progress dialog asap * **/
protected void onPostExecute(String message)
{
pDialog.dismiss();
if (message != null){
Toast.makeText(First.this, message, Toast.LENGTH_LONG).show();
}
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
All is correct but you will change for this code
if(name.toString().isEmpty()){
}
because your code is some time problem when you not enter any value then not check your condition. Your code will check only black space.
You can show Toast in your onPostExecute() method
The lifecycle of Asynktask is runs like this
onPreExecute() -> runs first
doInBackground() -> After onPreExecute
and
`onPostExecute()` -> After doInBackground
So you can update UI or show Toast in onPostExecute()
You can do your work inside onPostExecute method of AsyncTask
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progress.dismiss();
ackJSON=result;
//do your work here show toast or move to next activity
}
progress.setCancelable(false);

Dismiss Progress Dialog and handle exception in AsyncTask

I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}

Progressbar not working inside AsyncTask

I am using an AsyncTask to download some big amount of data from a server my AsyncTask work fine so i added a progress bar to make everything beautiful but problem is when its running progress bar get freeze half way down, and i use progress dialog that also the same its freeze half way down,
private class downloadChannelsfromserver extends
AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
data = getLinksfromServer(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog= ProgressDialog.show(Settings.this, "Synchronicing","Synchronicing", true);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
db.deleteAll();
final JSONArray jsonArray = json.getJSONArray("XXXX");
for (int i = 0; i < jsonArray.length(); i++) {
///use for insert datainto database
}
finish();
progressDialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("settings", "", e);
progressDialog.dismiss();
}
}
can and someone tell me why this happen, Pls
Follow this code
private ProgressDialog pdialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(pdialog ==null){
//display progress dialog like this
pdialog = new ProgressDialog(context);
pdialog.setCancelable(false);
pdialog.setMessage("Please Wait...");
pdialog.show();
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//dismiss progress dialog like this
if(pdialog!=null){
pdialog.dismiss();
pdialog = null;
}
}
Reason for progress bar get stuck was my JSON decoding since onPostExecute belongs to UI thread it take several time to decode the json results. so it will freeze the UI until JSON decode so move the decoding part to doInBackground will solve the UI freeze issue since doInBackground belongs to background thread
Please edit your code like this:
private class downloadChannelsfromserver extends
AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
public downloadChannelsfromserver()
{
progressDialog = new ProgressDialog(Settings.this);
progressDialog.setTitle("Synchronicing ...");
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
data = getLinksfromServer(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
db.deleteAll();
final JSONArray jsonArray = json.getJSONArray("XXXX");
for (int i = 0; i < jsonArray.length(); i++) {
///use for insert datainto database
}
finish();
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("settings", "", e);
}
finally
{
progressDialog.dismiss();
}
}
I hope this helps.
Just Use This Code:
runOnUiThread(object : Runnable {
override fun run() {
pausingDialog =
SweetAlertDialog(this#History_Activity, SweetAlertDialog.PROGRESS_TYPE)
pausingDialog!!.titleText = "Please wait...."
pausingDialog!!.setCancelable(false)
pausingDialog!!.show()
}
})
runOnUiThread(object : Runnable {
override fun run() {
}
})

how to stop AsyncTask if some condition is true

I use asynctask to get json data from remote url but sometimes this url return errors in json data like this :
{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: RNN.NES",
"type": "OAuthException",
"code": 803
}
}
in doInBackground, i check if there an error by json ..
if(true) {
//cancel asynctask and show toast with message i use
cancel(true)
}
but i do that the condititon is true but it is not cancelled
this is my code :
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Loading...",
"Data is Loading...");
}
#Override
protected Void doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
// addPageData(params[0]);
try {
if(json.getJSONObject("error") != null) {
Log.e("error", "true");
cancel(true);
}
name = json.getString("name");
fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
picName = downloadImage(picture, fid);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Now how can i stop that and show toast ???
thanks in advance
The method cancel(true) doesn't stop the AsyncTask. It just invokes onCancelled() instead of onPostExecute() after doInBackGround returns. You can use AsyncTask.isCancelled(), which will return true if you cancel the AsyncTask, to prevent further processing in doInBackground().
So override onCancelled() and put your Toast in there.
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(context, "Loading...",
"Data is Loading...");
}
#Override
protected Void doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(params[0]);
// addPageData(params[0]);
try {
if(json.getJSONObject("error") != null) {
Log.e("error", "true");
cancel(true); // after this AsyncTask.isCancelled() returns true
}
if(!this.isCancelled()){ // if it's true, prevent further processing
name = json.getString("name");
fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
picName = downloadImage(picture, fid);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// will be called instead onPostExecute after a cancel
#Override
protected void onCancelled() {
// Show your Toast
}
}
You can check using isCancelled() in onPostExecute() method and can show Toast in that method.Here is how you can do that -:
#Override
protected void onPostExecute(Void result) {
if(isCancelled()) {
Toast.makeText(context, "your text", Toast.LENGTH_SHORT).show();
return;
}
db = new DAOPages(context);
db.open();
db.addPage(name, fid, picName);
getPagePrefs(fid);
db.close();
mProgressDialog.dismiss();
Intent intent = new Intent(context, PagePrefsActivity.class);
intent.putExtra("fPageid", fid);
context.startActivity(intent);
}

Can we call two methods at a time in doinbackground method of asynchronous task in android?

I am working on android applications. I need some clarification regarding asynchronous task doinbackground method.
Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LongOperation2 op = new LongOperation2();
op.execute("");
}
public void test1() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("id", id));
try {
res1 = CustomHttpClient.executeHttpPost(
"http://website.com/folder1/firstpage.php",
postParameters);
System.out.println("response in test1" + res1.trim());
}
catch (Exception e) {
e.printStackTrace();
}
}
public void test2() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("value", value));
try {
res2 = CustomHttpClient.executeHttpPost(
"http://website.com/folder1/secondpage.php",
postParameters);
System.out.println("response in test2" + res2.trim());
}
catch (Exception e) {
e.printStackTrace();
}
}
private class LongOperation2 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
test1();
test2();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
dialog1.dismiss();
try {
Test.this.startActivity(new Intent(Page1.this, Page2.class));
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
dialog1 = ProgressDialog.show(Test.this, "Please wait...",
"Retrieving data ...", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
In the above code I have two methods test1() and test2(). In both the methods I am passing parameters to webservice. Now my doubt is can I call both the methods at a time in doInBackground() of asynchronous task? Is that ok? Please let me know or give me suggestion regarding this. Thanks in advance.
There is nothing wrong in calling two or more methods. But they will be executed one after another sequentially. There is no multiprocessing inside doBackground method.

Categories

Resources