Android AsyncTask keeps return opposite value - java

I got a problem with AsyncTask at Android Studio. What I am trying to do is before I create a new user, I am checking if the username and email exist in my database. Here is the part where I call the create AsyncTask:
new SignupAsyncTask(getBaseContext()).execute(userModel);
if(SignupAsyncTask.successCheck == false){
Toast.makeText(getBaseContext(), "Failed", Toast.LENGTH_SHORT).show();
} else if(SignupAsyncTask.successCheck == true){
Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
}
Inside my AsyncTask, I am getting all user. Then I perform a loop to check if there is any matching username or password. If there is, I set the successCheck to false.
public class SignupAsyncTask extends AsyncTask<User, Integer, Boolean> {
ArrayList<User> list = new ArrayList<User>();
DB_User userCtrl = new DB_User();
Context context;
public static boolean successCheck = false;
public SignupAsyncTask(){}
public SignupAsyncTask(Context context){
this.context = context;
}
#Override
protected Boolean doInBackground(User... params) {
try {
list = userCtrl.getAllUser();
for(int i = 0; i < list.size(); i++){
User userObj = list.get(i);
if(params[0].getUserName().equals(userObj.getUserName())){
successCheck = false;
break;
}
else if (params[0].getEmail().equals(userObj.getEmail())){
successCheck = false;
break;
} else{
successCheck = true;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(successCheck == true){
userCtrl.SignupUser(params[0]);
}
return successCheck;
}
#Override
protected void onPostExecute(Double result){
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
}
The problem that I have encountered now is for the first time when I am testing with a non-duplicate username and email, it can insert into database but somehow the toast printed out 'Failed'.
Then, when I try with another duplicate record, it does not insert into database as I set my username and email to be UNIQUE but the toast is printing out 'Success'.
It is operated in the opposite way as my code logic. Any ideas?
Thanks in advance
EDIT
public class SignupAsyncTask extends AsyncTask<User, Integer, Boolean> {
ArrayList<User> list = new ArrayList<User>();
DB_User userCtrl = new DB_User();
Context lcontext;
public static boolean successCheck = false;
public SignupAsyncTask(){}
public SignupAsyncTask(Context context){
lcontext = context;
}
#Override
protected Boolean doInBackground(User... params) {
try {
list = userCtrl.getAllUser();
for(int i = 0; i < list.size(); i++){
User userObj = list.get(i);
if(params[0].getUserName().equals(userObj.getUserName())){
successCheck = false;
break;
}
else if (params[0].getEmail().equals(userObj.getEmail())){
successCheck = false;
break;
} else{
successCheck = true;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return successCheck;
}
#Override
protected void onPostExecute(Boolean result){
if(successCheck)
{
//userCtrl.SignupUser(userobject);
Log.d("Check","Ran Success");
Toast.makeText(lcontext, "Success", Toast.LENGTH_SHORT).show();
}
else {
Log.d("Check","Ran Fail");
Toast.makeText(lcontext, "Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
}

It's because of AsyncTask, as its name, is an asynchronous task. You need to test the result in your SignupAsyncTask class.
Add the logic to your AsyncTask onPostExecute():
#Override
protected void onPostExecute(Boolean result){
if(result == false){
// Process if false
} else if(result == true){
// Process if true
}
}
Because you can't access UI thread from SignupAsyncTask (where your class is not a member class of your caller class), you need to define an interface as listener mechanism in your caller class to receive the result from your AsyncTask. So whenever there is a change in data, it will inform the caller who implements the interface.
Something like:
public interface OnSuccessCheckReceived{
void onSuccessCheckReceived(boolean isSuccess);
}
Then you add the callback interface to SignupAsyncTask:
public class SignupAsyncTask extends AsyncTask<User, Integer, Boolean> {
...
OnSuccessCheckReceived callBack;
public SignupAsyncTask(){}
public SignupAsyncTask(Context context, OnSuccessCheckReceived callBack){
this.context = context;
this.callBack = callBack;
}
...
#Override
protected void onPostExecute(Boolean result){
//if(result == false){
// // Process if false
// callBack.onSuccessCheckReceived(false); // Tell the caller
//} else if(result == true){
// // Process if true
//}
// a more compact code
callBack.onSuccessCheckReceived(result); // Tell the caller
}
Then you need to implement the listener interface to your caller class.
Something like:
public class YourCallerActivity implements OnSuccessCheckReceived {
...
#Override
public void onSuccessCheckReceived(boolean isSuccess) {
if(isSuccess){
Toast.makeText(getBaseContext(), "Failed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
}
}
...
}
Then you must call your AsyncTask with:
// this is pointing to your implemented interface.
new SignupAsyncTask(getBaseContext(), this).execute(userModel);
Suggestion,
Better if you don't add a context to an AsyncTask, because when your app terminated and AsyncTask not yet finished its job, your AsyncTask will throw an Error because the previous context its pointing is already gone.
So you need to change your SignupAsyncTask constructor to:
public SignupAsyncTask(OnSuccessCheckReceived callBack){
//this.context = context; Remove this.
this.callBack = callBack;
}
and call the SignupAsyncTask with:
new SignupAsyncTask(this).execute(userModel);
UPDATE
As #trooper pointing out, you need to change your:
#Override
protected void onPostExecute(Double result){
}
to
#Override
protected void onPostExecute(Boolean result){
}
So to tell the caller class, you need to tell about the result:
#Override
protected void onPostExecute(Boolean result){
// This is a more compact code that your previous code.
callBack.onSuccessCheckReceived(result); // Tell the caller
}
based on the other signatures in your AsyncTask.

Put your logic inside onPostExecute() :
protected void onPostExecute(Boolean result){
if(successCheck){
Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Failed", Toast.LENGTH_SHORT).show();
}
}
AsyncTask executes asynchronously i.e., It does not run on a Main thread. It spawns a separate thread known as Worker thread, executes its logic and then post back the results onto the Main thread.
Edit 1
Change your code as below :
public class SignupAsyncTask extends AsyncTask<User, Integer, Boolean> {
ArrayList<User> list = new ArrayList<User>();
DB_User userCtrl = new DB_User();
Context context;
public static boolean successCheck = false;
User user = null;
public SignupAsyncTask(){}
public SignupAsyncTask(Context context){
this.context = context;
}
#Override
protected Boolean doInBackground(User... params) {
try {
user = params[0];
list = userCtrl.getAllUser();
for(int i = 0; i < list.size(); i++){
User userObj = list.get(i);
if(user.getUserName().equals(userObj.getUserName())){
successCheck = false;
break;
}
else if (user.getEmail().equals(userObj.getEmail())){
successCheck = false;
break;
} else{
successCheck = true;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return successCheck;
}
#Override
protected void onPostExecute(Boolean result){
if(result){
Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
//Call SignupUser Code Here...
if(user != null) {
userCtrl.SignupUser(user);
}
} else {
Toast.makeText(getBaseContext(), "Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
}

Please modify your code like this
private ArrayList<User> list;
private DB_User userCtrl;
private Context context;
private SendResponse mRes;
public SignupAsyncTask(Context context,SendResponse res){
this.context = context;
userCtrl = new DB_User();
list = new ArrayList<User>();
mRes = res;
}
#Override
protected Boolean doInBackground(User... params) {
try {
list = userCtrl.getAllUser();
for(User userObj:userCtrl.getAllUser()){
if(params[0].getUserName().equals(userObj.getUserName())
|| params[0].getEmail().equals(userObj.getEmail()))
return false;
}else{
userCtrl.SignupUser(params[0]);
return true;
}
} catch (JSONException e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result){
//notify through interface to activity or fragment wherever you want to
//mRes.sendResponse(result);
}
#Override
protected void onProgressUpdate(Integer... progress) {
}

Related

How to call a method from MainActivity which takes views as parameters, from a class which extends JobService?

I want to execute this method which is in MainActivity...
public void checkNow(View view) {
new Thread(() -> {
//codes...
EditText getSite = findViewById(R.id.site);
site = getSite.getText().toString();
//codes...
Toast.makeText(this, "Connecting...", Toast.LENGTH_SHORT).show();
new MovieAsyncTask().execute(movie, url, site);
}).run();
}
...from the following class
public class MovieUpdatesService extends JobService {
private static final String TAG = "MovieUpdatesService";
private boolean jobCancelled = false;
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
public void doBackgroundWork(final JobParameters params) {
if (jobCancelled)
return;
//call checkNow() method here
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
#Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}
}
I want to call checkNow(View view) but I don't know how to access those views from this class.
I tried using interface but I can't understand how to make it work in my case.
I'm new to android so I'm looking for a simple solution if possible
To allow your service to save the value of the textview, you could add a member variable. Then you could expose a setter method for this string.
public class MovieUpdatesService extends JobService {
private static final String TAG = "MovieUpdatesService";
private boolean jobCancelled = false;
private String siteDetails = ""; <----
//Use this method from the Activity
public void setSiteDetails(String _siteDetails) {
siteDetails = _siteDetails
}
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
public void doBackgroundWork(final JobParameters params) {
if (jobCancelled)
return;
//use siteDetails here
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
#Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}
}

Android AsyncTask .get method in Expandable List View

I'm trying to disable setOnGroupClickListener in ExpandableListView in android through a value set by asynctask.
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
try {
new checkProgressValue().execute(i).get(3000,TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
}
Log.i("ResultPermission", String.valueOf(permission));
if (permission.equals(false)) {
return false;
}
else {
return true;
}
}
});
AsyncTask Code:
public class checkProgressValue extends AsyncTask<Integer, Void, Void> {
#Override
protected Void doInBackground(Integer... voids) {
Call<DefaultResponse> call = RetrofitClient.getInstance().getApi()
.checkQuizTopicForAttempt(user.getId(), topicList.get(voids[0]).getCourse_id());
final int temp = voids[0];
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
try {
if (response.body().getMessage() == null) {
progressValue = 0;
} else {
progressValue = Integer.parseInt(response.body().getMessage());
}
if (progressValue == 0 ) {
permission = false;
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Lock", Toast.LENGTH_SHORT).show();
permission = true;
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Permission", String.valueOf(permission));
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(getActivity().getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
permission = true;
Log.i("Permission", String.valueOf(permission));
}
});
return null;
}
}
Program doesn't wait at execute(i).get() method and always return true. The Log.i in this method print permission true while in AsyncTask print false.
I didn't get where I'm wrong. Or is there any way i handle onClick in PostExecute method?
just Call this function in onResponse :
expandableListView.expandGroup(positionOfGroup);

AsyncTask and boolean variable

I'm really struggling with a simple issue that I'm hoping someone could assist in .
I have a basic application that authenticates to a database using a basic query.This query is run in the async doinbackground and returns a boolean named isSuccess.
It is then passed to a button onclick method that then determines if the user has entered the correct password. The boolean get reinitialized to true on the async method .
The problem I'm experiencing is that it seems like at the onclick stage it gets the initialised true boolean and not the changed variable value in the indobackground section.
issueing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String passwordd = password.getText().toString();
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute(passwordd,passwordd);
password.getText().clear();
if (checkLogin.isSuccess)
Toast.makeText(MainActivity.this, "Issue Login", Toast.LENGTH_SHORT).show();
}
});
}
public class CheckLogin extends AsyncTask<String, String, String>
{
String z = "";
boolean isSuccess = true;
#Override
protected void onPreExecute()
{
//progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
}
#Override
public String doInBackground(String... args)
{
String usernam = args[0];
String passwordd = args[1];
{
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(db, un, pass); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else {
String query = " select * from employee where password = '"+ passwordd+"'" ;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
String employee,pw;
if (rs.next()) {
employee= rs.getString("employee");
pw = rs.getString("password");
z = "Success";
//setSuccess(true);
isSuccess = true;
}
else if (!rs.next())
{
//setSuccess(false);
//setSuccess(false);
isSuccess = false;
z = "Invalid Password";
}
}
}
catch (Exception ex)
{
isSuccess = false;
//setSuccess(false);
z = ex.getMessage();
}
}
return null;
}
I'm suspecting that the onclick doesn't get the changed boolean value in time because of it running in the background.
This is simply because when you're using the following code:
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute(passwordd,passwordd);
password.getText().clear();
if (checkLogin.isSuccess)
Toast.makeText(MainActivity.this, "Issue Login", Toast.LENGTH_SHORT).show();
}
you're thinking that the code is working in synchronous ways. CheckLogin is an AsyncTask which is working in a asynchronous way. So the CheckLogin code in the following code:
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute(passwordd,passwordd);
will make a separate task and not blocking the process until it finished its job. So, Toast in your following code:
if (checkLogin.isSuccess)
Toast.makeText(MainActivity.this, "Issue Login", Toast.LENGTH_SHORT).show();
}
won't be executed because checkLogin.isSuccess is still false.
The simple fixed is by moving your check to onPostExecute of AsyncTask. Something like this:
#Override
protected void onPostExecute(String r) {
if (checkLogin.isSuccess) {
// do something with the success
}
}
The proper way is by using a listener as a callback mechanism to tell the activity that the process is finished. This will separate your Activity and AsyncTask process to make it more maintainable in the future.
You can use an AsyncTask and callback with something like this:
public class CheckLoginTask extends AsyncTask<Void, Void, Boolean> {
private String mUserName;
private String mPassword;
private ResultListener mListener;
private String mMessage;
public interface ResultListener {
void onSuccess(String message);
void onFailure(String message);
}
public CheckLoginTask(String userName, String password, ResultListener listener) {
mUserName = userName;
mPassword = password;
mListener = listener;
}
#Override protected Boolean doInBackground(Void... voids) {
boolean isSuccess = false;
// do some process with username and password
// assume there is a a message
mMessage = "Invalid password";
return isSuccess;
}
#Override protected void onPostExecute(Boolean isSuccess) {
if(isSuccess) {
mListener.onSuccess(mMessage);
} else {
mListener.onFailure(mMessage);
}
}
}
that it can be used like this:
CheckLoginTask.ResultListener listener = new CheckLoginTask.ResultListener {
#Override
public void onSuccess(String message) {
// do something when success
}
#Override
public void onFailure(String message) {
// do something with failure
}
};
CheckLoginTask checkLoginTask = new CheckLoginTask(userName, password, listener);
checkLoginTask.execute();
For what i understand from your question, you want to check for
a password and then pass the result to the activity or somewhere else.
I suggest implementing interfaces to make your code simpler and more effective.
since AsyncTasks run on a different thread, they have methods to contact with the main thread such as onPreExecute() and onPostExecute(String r) , so what you have to do is the following :
create an interface that would look like something like that :
public interface PasswordChecker {
void onChecked(Boolean isSuccess);
}
the second thing is to make your activity or class implement this interface, it would be this way :
public class MyActivity extends AppCompatActivity implements PasswordChecker {
#Override
public void onChecked(Boolean isSuccess) {
if (isSuccess) {
//Do Stuff with your isSuccess Boolean
}
}
}
or you can initialize a PasswordChecker object variable and pass it as an argument in the third step.
Make your AsyncTask require a PasswordChecker and then you must pass your activity or class, or object as an argument to the constructor, your AsyncTask would look like this :
public class CheckLogin extends AsyncTask<String,String,Boolean> {
private PasswordChecker checker;
CheckLogin(PasswordChecker checker) {
this.checker = checker;
}
#Override
protected Boolean doInBackground(String... strings) {
boolean isSuccess;
//Do Your Work..
//...
//...
//if (condition)
isSuccess = true;
return isSuccess;
}
#Override
protected void onPostExecute(Boolean isSuccess) {
super.onPostExecute(isSuccess);
checker.onChecked(isSuccess);
}
}
Finally, you must initialize your AsyncTask using a PasswordChecker object as an argument :
//Passing the activity it self (which implements PasswordChecker) as an argument
final CheckLogin checkLogin = new CheckLogin(MyActivity.this);
or
//Or by passing a custom object
PasswordChecker myChecker = new PasswordChecker() {
#Override
public void onChecked(Boolean isSuccess) {
if (isSuccess) {
Toast.makeText(MyActivity.this , "Login Success!" , Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MyActivity.this , "Login Failed!" , Toast.LENGTH_LONG).show();
}
}
};
CheckLogin myCheckLogin = new CheckLogin(myChecker);
//Do the rest of the job
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Execute your task
checkLogin.execute("Username", "Password");
}
});
Conclusion : As you can see here, the result is passed through onPostExecute(String r), your interface will be fired ( by checker.onChecked(isSuccess); ) every time onPostExecute is called, passing the boolean as an argument, and executes the code inside it depending on its value.
The problem is doInBackground() works an a different thread then your onClick(). onClick() works on the UIThread. so you don't recieve any updates to that thread.
First change your Async task declaration to this:
public class CheckLogin extends AsyncTask<Void, Void, Boolean>
The third parameter is the result parameter that is returned by doinbackground.
so your doInBackground() and onPostExecute()will be something like this:
#Override
protected Boolean doInBackground(Void... params) {
if(some_condition) {
return true;
} else {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
// use the result
super.onPostExecute(result);
isSuccess = result;
};

Boolean Return from AsyncTask in Android

I want to return a Boolean after a AsyncTask.
This is the AsyncTask (not the whole code because isn't important and sstackoverflow give me error):
public class CallSoap extends AsyncTask<CallSoapParams, Void, Void> {
public interface AsyncResponse {
void processFinish(String output);
}
private Context activityContext;
public AsyncResponse delegate = null;//Call back interface
public CallSoap(Context context, AsyncResponse asyncResponse) {
activityContext = context;
delegate = asyncResponse;
}
#Override
protected Void doInBackground(CallSoapParams... params) {
request = new SoapObject(params[0].NAMESPACE, params[0].METHOD_NAME);
// no important things
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//dismiss ProgressDialog
delegate.processFinish(response.toString());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//create and show ProgressDialog
}
}
And this is the implementation on Activity (not the whole code because isn't important and sstackoverflow give me error):
private boolean checkDataRegistrationByServer() {
if (NickNameExist()) {
// DO STUFF
}
return true;
}
Boolean r;
private boolean NickNameExist() {
CallSoapParams callParams = new CallSoapParams(NICKNAME_EXIST);
CallSoap NickNameExistCall = new CallSoap(RegistrationActivity.this, new CallSoap.AsyncResponse() {
#Override
public void processFinish(String output) {
Log.d("Response From AsyTask:", output);
if (output.equals(FALSE_RESPONSE)) {
r = false;
Toast.makeText(getApplicationContext(), output + " - NickNameExistCall - Nick don't exist", Toast.LENGTH_SHORT).show();
} else {
r = true;
}
}
});
NickNameExistCall.execute(callParams);
return r;
}
I tried to create a global Boolean but the App crash. Someone can help me?
1) You don't have a response variable anywhere, and doInBackground has returned null instead of any response, so not clear how you got that value.
delegate.processFinish(response.toString());
2) You can't return from that function. And your app crashes probably because Boolean's can be null. boolean's cannot. However, you should not attempt to make a global variable here because that's not how asynchronous code should run.
What you need is to pass the callback through the function
private void checkDataRegistrationByServer(String data, CallSoap.AsyncResponse callback) {
CallSoap nickNameExistCall = new CallSoap(RegistrationActivity.this, callback);
CallSoapParams callParams = new CallSoapParams(data);
nickNameExistCall.execute(callParams);
}
Elsewhere...
final String nick = NICKNAME_EXIST;
checkDataRegistrationByServer(nick, new CallSoap.AsyncResponse() {
#Override
public void processFinish(String response) {
Log.d("Response From AsyncTask:", output);
boolean exists = !response.equals(FALSE_RESPONSE);
if (!exists) {
Toast.makeText(getApplicationContext(), output + " - NickNameExistCall - Nick " + nick + " doesn't exist", Toast.LENGTH_SHORT).show();
}
}
});
Note: If you make your AsyncTask just return a Boolean in the AsyncResponse you can shorten this code some.

Queuing images path when there's no internet connection

I'm havin difficulties of keeping track of my queue.
I'm trying to store image-paths into a queue so i can use the queue to start uploading my images once there's internet (at a later moment). The upload image is an asynctask and in the postExecute i'm trying to send a mail with the uploaded picture attached to it in another asynctask.
This is my UploadImage AsyncTask. I think i'm doing way too difficult and that it can be done much easier than it is right now.
private class UploadImageTask extends AsyncTask<Void, Void, Integer> {
ProgressDialog dialog;
/**
* Private integer which counts how many times we've tried to upload the
* Image.
*/
private int _counter = 0;
private List<String> imageUploadList = new ArrayList<String>();
#Override
protected void onPreExecute() {
super.onPreExecute();
if(AppStatus.haveNetworkConnection(_context)){
if(isPhotoTaken()){
dialog = new ProgressDialog(Step4.this);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage(getString(R.string.uploadingMessage));
dialog.setTitle(getString(R.string.uploadingTitle));
dialog.show();
}
}
}
protected Integer doInBackground(Void... params) {
init();
postData();
return null;
}
public void init(){
_counter = 0;
_beenHere = true;
for(String path : imageUploadList){
Debug.out("Path: "+path);
}
}
public void postData() {
if (isPhotoTaken()) {
if(AppStatus.haveNetworkConnection(_context)){
if(_beenHere){
ImageUploader.uploadFile(getPhotoPath(),
"http://obo.nl/android-upload-image.php", Step4.this);
} else {
for(String path : imageUploadList){
Debug.out(path);
ImageUploader.uploadFile(path,
"http://obo.nl/android-upload-image.php", Step4.this);
}
}
} else {
if (_counter == 0) {
_counter++;
_activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(_context,
getString(R.string.noInternetImageNotUploaded),
Toast.LENGTH_LONG).show();
}
});
imageUploadList.add(getPhotoPath());
}
try {
if(_beenHere){
_beenHere = false;
goToNextIntent();
}
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
postData();
}
}
}
private void goToNextIntent(){
Intent intent = new Intent(Step4.this, Step5.class);
intent.putExtra(EXTRA_MESSAGE, (Serializable) _user);
intent.putExtra(EXTRA_MESSAGE2, _isRepairable);
intent.putExtra(EXTRA_MESSAGE3, _injury);
intent.putExtra(EXTRA_MESSAGE4, _category);
intent.putExtra(EXTRA_MESSAGE5, _inch);
intent.putExtra(EXTRA_MESSAGE6, _size);
startActivity(intent);
}
protected void onPostExecute(Integer result) {
if(isPhotoTaken()){
if(dialog != null){
dialog.dismiss();
}
}
mailing(_isRepairable);
new MyAsyncTask().execute(_mail);
}
}
The line:
if(AppStatus.haveNetworkConnection(_context))
returns a boolean true if the user has a working internet connection. false otherwise.
What I want is to queue all the image paths (and mails sent afterwards) in the desired ArrayList so i can send them all at a later moment when the user has a working internet Connection. Please help me out!

Categories