In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am developing one Android app in which there are two activities.
First activity: With button to go onto Facebook already login page. I want to know how to fetch data (like Name, DOB, Place, Email ID) from Facebook into my app.
Second activity (with EditText): How to match there API or what is required please let me know. I searched everywhere but did not find any answer.
I have done this, but it is showing errors.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
facebook = (Button) findViewById(R.id.facebook);
facebook.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onClickFacebookLogin();
// Intent in = new Intent(FacebookActivity.this,GetDataFromFacebook.class);
// in.putExtra("email", );
// startActivity(in);
}
});
}
public void onClickFacebookLogin() {
// Session.openActiveSession(this, true, new Session.StatusCallback() {
openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
// ((GlobalFilename)Login.this.getApplication()).setfbSession(session);
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user,
Response response) {
// TODO Auto-generated method stub
if (user != null) {
final GraphUser graphuser=user;
try{
new AsyncTask<Void, Void, Void>() {
String fbemail,fname,lname,mediaid,image_url,gender,dob;
ProgressDialog progressDialog;
ImageLoader imageLoader;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (progressDialog == null) {
progressDialog = createProgressDialog(MyAccount.this);
progressDialog.show();
} else {
progressDialog.show();
}
}
#Override
protected Void doInBackground(Void... params) {
Object g = graphuser.asMap().get("email");
if(g==null)
{
fbemail="";
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
System.out.println("===>accountname inside null"+fbemail);
return null;
}
else{
fbemail= graphuser.asMap().get("email").toString();
gender =graphuser.asMap().get("gender").toString();
image_url = "https://graph.facebook.com/"+graphuser.getId()+"/picture?type=square";
// image_url=String.format(image_url);
//accountName =graphuser.getProperty("email").toString();
System.out.println("fb email====>"+fbemail);
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
dob=graphuser.getBirthday();
System.out.println("Gender"+gender);
System.out.println("Image==>"+image_url);
try {
InputStream in = new java.net.URL(image_url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
if(mIcon11==null)
{
System.out
.println("null in doinbackground");
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), userid, Toast.LENGTH_LONG).show();
System.out.println("fb email====>"+fbemail);
//Toast.makeText(getApplicationContext(), accountName, Toast.LENGTH_LONG).show();
return null;
}
}
#Override
protected void onPostExecute(Void v) {
super.onPreExecute();
progressDialog.dismiss();
tvname.setText(fname+" "+lname);
tvemail.setText(fbemail);
imageLoader = new ImageLoader(MyAccount.this);
System.out
.println("imageurlonpost==>"+image_url);
// imageLoader.DisplayImage(image_url,fbprofileimage);
if (mIcon11 != null
){
// do what you need to do with the bitmap :)
fbprofileimage.setImageBitmap(mIcon11);
}
else{
Toast.makeText(MyAccount.this,"Null",Toast.LENGTH_LONG).show();
}
}
}.execute();
}catch(Exception e) {
//findViewById(R.id.progressbar).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Facebook configuration error!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
},Arrays.asList("email"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
Showing errors at new Session.StatusCallback()(under onClickFacebookLogin()) & getActiveSession() (at onActivityResult)
Here is the complete working code.Set up your developer account and call this method.Also dont forget to call onActivityResult() once the control return from facebook.
//Method invoked when facebook login button is clicked
public void onClickFacebookLogin() {
// Session.openActiveSession(this, true, new Session.StatusCallback() {
openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
// ((GlobalFilename)Login.this.getApplication()).setfbSession(session);
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user,
Response response) {
// TODO Auto-generated method stub
if (user != null) {
final GraphUser graphuser=user;
try{
new AsyncTask<Void, Void, Void>() {
String fbemail,fname,lname,mediaid,image_url,gender,dob;
ProgressDialog progressDialog;
ImageLoader imageLoader;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (progressDialog == null) {
progressDialog = createProgressDialog(MyAccount.this);
progressDialog.show();
} else {
progressDialog.show();
}
}
#Override
protected Void doInBackground(Void... params) {
Object g = graphuser.asMap().get("email");
if(g==null)
{
fbemail="";
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
System.out.println("===>accountname inside null"+fbemail);
return null;
}
else{
fbemail= graphuser.asMap().get("email").toString();
gender =graphuser.asMap().get("gender").toString();
image_url = "https://graph.facebook.com/"+graphuser.getId()+"/picture?type=square";
// image_url=String.format(image_url);
//accountName =graphuser.getProperty("email").toString();
System.out.println("fb email====>"+fbemail);
fname=graphuser.getFirstName();
lname=graphuser.getLastName();
mediaid=graphuser.getId();
dob=graphuser.getBirthday();
System.out.println("Gender"+gender);
System.out.println("Image==>"+image_url);
try {
InputStream in = new java.net.URL(image_url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
if(mIcon11==null)
{
System.out
.println("null in doinbackground");
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), userid, Toast.LENGTH_LONG).show();
System.out.println("fb email====>"+fbemail);
//Toast.makeText(getApplicationContext(), accountName, Toast.LENGTH_LONG).show();
return null;
}
}
#Override
protected void onPostExecute(Void v) {
super.onPreExecute();
progressDialog.dismiss();
tvname.setText(fname+" "+lname);
tvemail.setText(fbemail);
imageLoader = new ImageLoader(MyAccount.this);
System.out
.println("imageurlonpost==>"+image_url);
// imageLoader.DisplayImage(image_url,fbprofileimage);
if (mIcon11 != null
){
// do what you need to do with the bitmap :)
fbprofileimage.setImageBitmap(mIcon11);
}
else{
Toast.makeText(MyAccount.this,"Null",Toast.LENGTH_LONG).show();
}
}
}.execute();
}catch(Exception e) {
//findViewById(R.id.progressbar).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Facebook configuration error!", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
},Arrays.asList("email"));
}
My splash screen syncronize my app :
When I use :
sd.execute("init_sync", null).get();
My logo (defined in xml) disappear. If I quit .get(), it appears.
Here is my code :
public class SplashScreen extends Activity {
private Context ctx = null;
private Usuario mUser = null;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ctx = this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
new Handler().post(new Runnable() {
#Override
public void run() {
// Check if user exists
Gson gson = new Gson();
String jsonUser = prefs.getString("usuario", "");
mUser = gson.fromJson(jsonUser, Usuario.class);
if (NetworkUtils.isOnline(ctx)) {
if (mUser != null) {
SyncData sd = new SyncData(ctx);
try {
sd.execute("init_sync", null).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
}
} else {
if (mUser != null) {
Intent i = new Intent(SplashScreen.this, DashBoard.class);
startActivity(i);
} else {
Toast.makeText(ctx, "Necesita Internet para loguearse", Toast.LENGTH_LONG).show();
finish();
}
}
}
});
}
}
I have several asyncTask that I use to upload pics, and sync MySQL database with my SQLite database. So, I need to wait till all the processes end to know if there is any error.
The thing is I put it in a thread, so that it would not affect UI. Where am I wrong?
When you use get() it causes the UI thread to wait. Don't use get(). You need to override the onPostExecute method in AsyncTask.
private Boolean task1Finished = false;
private Boolean task2Finished = false;
private Boolean task3Finished = false;
//...
SyncData sd1 = new SyncData(ctx) {
#Override
protected void onPostExecute(Object result) {
task1Finished = true;
goToNextActivity();
}
};
SyncData sd2 = new SyncData(ctx) {
#Override
protected void onPostExecute(Object result) {
task2Finished = true;
goToNextActivity();
}
};
SyncData sd3 = new SyncData(ctx) {
#Override
protected void onPostExecute(Object result) {
task3Finished = true;
goToNextActivity();
}
};
try {
sd1.execute();
sd2.execute();
sd3.execute();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
//...
private void goToNextActivity() {
if (task1Finished && task2Finished && task3Finished)
// all tasks complete
}
Like #ashishduh says, I was in UI Thread. So I changed:
new Handler().post(new Runnable() {
#Override
public void run() {
....
}
}
by
Runnable sync = new Runnable() {
#Override
public void run() {
....
}
};
Thread t = new Thread(sync);
t.start();
And it solved my problem!
I have an app that sends a file through a socket. While doing this I want to show the progress in a ProgressDialog. The app sends the file perfectly but I'm not able to make the dialog appear.
public class ProgressDialogActivity extends Activity {
private ProgressDialog downloadDialog = null;
private String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
filePath = getIntent().getExtras().getString("filePath");
downloadDialog = new ProgressDialog(this);
Task myTask = new Task();
myTask.execute(0);
}
private void showMessage(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), msg, `enter code here`Toast.LENGTH_SHORT).show();
}
});
}
private class Task extends AsyncTask<Integer, Integer, Boolean> implements Observer
{
private Thread t;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
downloadDialog.setTitle("SENDING");
downloadDialog.setMessage("................");
downloadDialog.setCancelable(false);
downloadDialog.setIndeterminate(false);
// downloadDialog.setMax(100);
downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadDialog.show();
}
#Override
protected Boolean doInBackground(Integer... params) {
SendFile send = new SendFile(filePath);
downloadDialog.setMax(0);
t = new Thread(send);
send.registerObserver(this);
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
t.start();
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
int counter = values[0].intValue();
downloadDialog.setProgress(counter);
if(filePath != null)
{
downloadDialog.setMessage(filePath+"...");
}
}
#Override
public void update(Subject subject) {
// TODO Auto-generated method stub
if(subject instanceof SendFile)
{
SendFile e = (SendFile) subject;
if(e.getException() != null)
{
t.interrupt();
showMessage(e.getException());
} else
{
if(!e.isStarted())
{
initializeProgressBar(e.getNumIter());
} else
{
refreshProgressBar(e.getNumIter());
}
if(e.isSent())
{
t.interrupt();
showMessage("File sent");
}
}
}
}
public void initializeProgressBar(int max){
downloadDialog.setMax(max);
}
public void refreshProgressBar(int amount){
publishProgress(downloadDialog.getMax()-amount);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(downloadDialog != null)
{
downloadDialog.dismiss();
}
finish();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
t.interrupt();
showMessage("TASK CANCELLED");
}
};
}
SendFile is the class that contains the socket to send the files.
I think the problem is due to I'm calling the thread inside the AssyncTask because when I make Thread.sleep(10000) I can see the ProgressDialog for that time, but I don't know how to fix it.
Also, when I run the debugger I can see that the variable 'counter' is incremented every time I call it, but if I add a watch with 'downloadDialog.getProgress()' the progress is always 0.
You are creating an AsyncTask, which doInBackground() method RUNS IN BACKGROUND. In there, you don't do anything, but start a new thread... Now this thread does the work, but your AsyncTask finishes, because it has nothing to do after starting the other thread... So, your ProgressDialog is shown for some milliseconds, then your AsyncTask finishes and the ProgressDialog is hidden again. But the thread that is doing the work is still running, only your AsyncTask has finished.
Solution : Either use an AsyncTask OR use a thread.
You need to call publishProgress on doinBackground()
Example:
protected String doInBackground(Void... params) {
try {
int i = 0;
Log.i("Thread","1");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","2");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","3");
Thread.sleep(1000);
Log.i("Thread","4");
Thread.sleep(1000);
Log.i("Thread","5");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "done";
}
Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().
i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}