I have an asynctask which gets data from the local Sqlite database and shows it to the user. If the data isnt there in the sqlite, a network call will be made to the server to retrieve server side data.
The issue is that when i call the db and i get the data, i add it to the list. I check the size of the list and it shows content.
Then when i try to notify the adapter of the arraylist, it shows list size 0 without any clear() call being made
The files are as follows:
package com.example.project.recommendedapp.AsyncTasks;
//SuggestionsGetterAsync start----------------------------------------------------------------------------------------------------------------
public class SuggestionsGetterAsync extends AsyncTask<String,Void,Void> {
private String queryString;
private WeakReference<Activity> weakReference;
private Activity localReference;
private Fragment localFragment;
private ArrayList<Suggestions> localSuggestionsList;
double latitude,longitude;
String cityName;
int request_counter_in_fragment;
public SuggestionsGetterAsync(Activity passedReference, Fragment passedFragment, ArrayList<Suggestions> localSuggestionsList,int request_counter_in_fragment,double ...coordinates){
weakReference=new WeakReference<Activity>(passedReference);
localReference=weakReference.get();
localFragment=passedFragment;
this.localSuggestionsList=localSuggestionsList;
latitude=coordinates[0];
longitude=coordinates[1];
this.request_counter_in_fragment=request_counter_in_fragment;
}
#Override
protected Void doInBackground(String... params) {
queryString=params[0];
cityName=params[1];
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
localSuggestionsList.clear();
((LocalFragmentInteractionInterface)localFragment).notifyAdapter();
}
});
//cancel the call to avoid load if it is a previously dispatched useless servelet
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()!=request_counter_in_fragment){
this.cancel(true);
return null;
}
}
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing() && !queryString.equals("")){
//cancel the call to avoid load if it is a previously dispatched useless servelet
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()!=request_counter_in_fragment){
this.cancel(true);
return null;
}
LocalDatabaseHelper localDatabaseHelper = LocalDatabaseHelper.getInstance(localReference);
localSuggestionsList=localDatabaseHelper.getLocalSearchSuggestions(queryString);
Log.d("FragmentCreate","localSuggestionsList size after db call is "+localSuggestionsList.size()); // prints ok and shows that the list has values
}
Log.d("FragmentCreate","localSuggestionsList size now is"+localSuggestionsList.size()); // prints ok and shows that the list has values
if (localSuggestionsList.size()==0) {
//basically first query the local cache, if nothing is found locally, go fetch the data from the server
//put the fetched results inside the local database
try {
//String serveleturl = "http://192.168.1.7:8080/Servelet/SearchSuggestionsServelet?latitude="+latitude+"&longitude="+longitude+"&cityName="+cityName+"&queryString="+URLEncoder.encode(queryString,"UTF-8");
String serveleturl = "http://kushan.dynu.com:8080/Servelet/SearchSuggestionsServelet?cityName="+URLEncoder.encode(cityName,"UTF-8")+"&queryString="+(queryString.equals("")?null:URLEncoder.encode(queryString,"UTF-8"));
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30000, TimeUnit.MILLISECONDS)
.readTimeout(30000,TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(false)
.build();
Request request = new Request.Builder()
.url(serveleturl)
.build();
Response response = client.newCall(request).execute();
switch (response.code()){
case 444:
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("No search results found",false);
}
});
}
break;
case 222:
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("Hide the errortext",true);
}
});
}
JSONArray suggestionsArray = new JSONArray(response.body().string());
if(suggestionsArray.length()!=0){
try{
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()){
LocalDatabaseHelper localDatabaseHelper = LocalDatabaseHelper.getInstance(localReference);
localDatabaseHelper.putSuggestions(suggestionsArray);
}
}catch (Exception e){
Log.e("FragmentCreate","Error saving the suggestion inside db",e);
}
}
for(int i=0;i<suggestionsArray.length();i++){
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) {
localSuggestionsList.add(new Suggestions(suggestionsArray.getJSONObject(i)));
}else{
return null;
}
}
break;
default:
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("No search results found",false);
}
});
}
break;
}
response.close();
}catch (Exception e){
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment) && !isCancelled()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
((LocalFragmentInteractionInterface)localFragment).setErrorText("Check your Internet connection or try again after some time",false);
}
});
}
}
}else{
if (localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("FragmentCreate","before postExecute the size of the list is "+localSuggestionsList.size()); // prints size as zero for no reason
((LocalFragmentInteractionInterface)localFragment).setErrorText("Hide the errortext",true);
}
});
}
}
return null;
}
#Override
public void onPostExecute(Void voided){
if((localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) && (((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()==request_counter_in_fragment)) {
Log.d("FragmentCreate","request counter in asynctask ="+request_counter_in_fragment+" queryString is = "+queryString+" "+localSuggestionsList.size()); // prints size as zero for no reason
((LocalFragmentInteractionInterface) localFragment).notifyAdapter();
if(queryString.equals("")){
((LocalFragmentInteractionInterface)localFragment).setErrorText("",true);
}
}
weakReference=null;
localReference=null;
localFragment=null;
queryString=null;
localSuggestionsList=null;
}
#Override
public void onCancelled(){
Log.d("FragmentCreate","AsyncTaskCancelled");
}
}
The function returning the List from sqlite is as follows:
public ArrayList<Suggestions> getLocalSearchSuggestions(String searchString) throws SQLiteException{
//localSuggestionsList.clear();
ArrayList<Suggestions> localSuggestionsList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT "+TableAndColumnNames.SEARCH_RESULTS_DATA+" FROM "+TableAndColumnNames.SEARCH_RESULTS_TABLE_NAME+" WHERE "+TableAndColumnNames.SEARCH_RESULTS_SUGGESTION+" LIKE '%"+searchString+"%' limit 20";
Cursor c = db.rawQuery(sql,null);
JSONObject suggestionObject;
if(c!=null){
if(c.moveToFirst()){
do{
try{
//Log.d("FragmentCreate",c.getString(0)+" found in suggestion");
suggestionObject = new JSONObject(c.getString(0));
localSuggestionsList.add(new Suggestions(suggestionObject));
}catch (JSONException je){
Log.d("FragmentCreate","Data got corrupted for searched list");
}
}while(c.moveToNext());
}
c.close();
}
return localSuggestionsList;
}
if(localReference!=null && !localReference.isDestroyed() && !localReference.isFinishing()) {
localReference.runOnUiThread(new Runnable() {
#Override
public void run() {
localSuggestionsList.clear();
((LocalFragmentInteractionInterface)localFragment).notifyAdapter();
}
});
//cancel the call to avoid load if it is a previously dispatched useless servelet
if(((GetRequestCounterFromFragment)localFragment).getRequestDispatchedCounter()!=request_counter_in_fragment){
this.cancel(true);
return null;
}
}
Here you clear list and notify adapter
first check your db data update or not.
Related
I have three fragments in a FragmentPagerAdapter, and each of them would fetch a list of frames/data from a server using Volley. This data would later be used to update the Fragment's RecyclerView Adapter as a Cursor.
VolleyRestClientUtils.get(getString(R.string.PATH_SHOP), LOG_TAG, params, true, false, new JsonHttpResponseHandler() {
public void onSuccess(JSONObject response) {
Log.d(LOG_TAG, "request Response : " + response.toString());
try {
String status = response.getString("status");
if (RestClientUtils.STATUS_OK.equals(status)) {
final JSONArray frames = response.getJSONArray("items");
Log.d(LOG_TAG, "request Response : " + frames.length());
if (frames != null && frames.length() > 0) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
List<ContentValues> listShopFrame = ShopFrame.fromJSONArray(frames, sort);
if (listShopFrame.size() > 0 && isActivityActive()) {
ContentResolver cr = getActivity().getContentResolver();
if (!isRequestMore) {
cr.delete(ShopFrame.CONTENT_URI, ShopFrame.COLUMN_CATEGORY + "=?",
new String[]{sort});
paramSkip = frames.length();
} else {
paramSkip += frames.length();
}
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
String log = listShopFrame.size()+" ";
for (int i = 0; i < listShopFrame.size(); i++) {
operations.add(ContentProviderOperation
.newInsert(ShopFrame.CONTENT_URI)
.withValues(listShopFrame.get(i))
.build());
log += listShopFrame.get(i).toString()+"\n";
}
Log.i("loader_callback_"+sort, log);
//cr.applyBatch(ShopFrame.CONTENT_AUTHORITY, operations);
ContentValues[] opsAsArray = new ContentValues[listShopFrame.size()];
listShopFrame.toArray(opsAsArray);
cr.bulkInsert(ShopFrame.CONTENT_URI, opsAsArray);
//return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
dataRefreshed = true;
Log.i("loader_callback_"+sort, "response post execute");
if (result) {
loadSucceed();
PicMixApp.getInstance().setRefreshed(ShopFrameFragment.this.getClass().getName());
} else {
loadFailed(null);
}
}
}.execute();
} else {
//TODO
//Handle error
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} else if (VolleyRestClientUtils.STATUS_RESOURCE_NOT_FOUND.equals(status)) {
hasMore = false;
loadSucceed();
} else {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception:" + e.getMessage());
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
}
#Override
public void onJSONError(String responseString) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
#Override
public void onFailure(String errMessage, int statusCode, Map<String, String> headers, byte[] responseBytes) {
loadFailed(getString(R.string.err_load_s, getString(R.string.frame)));
}
});
Whereas loadSucceed() has this following code:
if (this.recyclerView != null) {
final RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onChanged");
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
Log.i(DefaultRecyclerFragment.this.getClass().getName(), "onItemRangeRemoved:" + positionStart + ", itemcount:" + itemCount);
adapter.unregisterAdapterDataObserver(this);
isLoading = false;
}
});
if (adapter instanceof CursorRecyclerAdapter && loadMoreView != null) {
((CursorRecyclerAdapter) adapter).removeFooter(loadMoreView);
}
}
}
I've put the code to initialize the loader in the onResume() method of each fragment:
int id = 100+Integer.valueOf(sort);
Loader l = getLoaderManager().getLoader(id);
Log.i("loader_callback_"+sort, "success loading volley "+l);
if(l == null) {
getLoaderManager().restartLoader(id, null, this);
}
My problem is that there seems to be some sort of race condition happening, that the currently viewed fragment's adapter seem to be updated twice, and sometimes thrice. The initial cursor fetched by the Fragment's Loader has 10 rows, sure, but after the update, most of the time it only has 7 of the 21 rows expected to be put in.
I thought all the ContentResolvers' operations are synchronous (can only be done one after another, not simultaneously). What's going on here?
EDIT: Should I just put the loader init code in the loadSuccess() callback?
EDIT2: I should note that these Fragments extend android.support.v4.app.Fragment, and I'm using the version 27.1.1 of the Support Library.
I am fetching data from database. My views are updating only first time when I open the activity. Then when I again open the activity, my views are not updated.(Activity is starting again, hence onCreate() is called again & all settings are same). If I getText() after setting the text, I am getting proper values in log but nothing is displayed in view.
Here is my code snippet:
//My Call Back method
#Override
public void onRatingDataLoaded(ReviewJsonModel review) {
int ratingCount = 0, ownRating = 0;
String averageRating = "0";
if (review != null) {
ratingCount = review.review_count;
DecimalFormat format = new DecimalFormat("##.00");
averageRating = format.format(review.rating);
if (review.ownreviews != null) {
try {
ownRating = Integer.parseInt(review.ownreviews.rating);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
} else {
// do something
}
mTotalRatingCount.setText(String.format(getResources().getString(R.string.review_count), ratingCount));
mAverageRating.setText(averageRating);
// Log.v("LoggingReview", mTotalRatingCount.getText().toString().trim);
myRating.setRating(ownRating);
}
//Here I am setting listner as well as loading data.
public void loadReviewData(RatingDataLoadListener listener, int destinationId) {
if (mDataLoadListener == null)
mDataLoadListener = listener;
new getReviews().execute(destinationId);
}
Next is my asyntask
private class getReviews extends AsyncTask<Integer, Void, ReviewJsonModel> {
#Override
protected ReviewJsonModel doInBackground(Integer... integers) {
Cursor appCursor = mRatingApi.getDestinationReview(integers[0]);
ReviewJsonModel mReviewData = new ReviewJsonModel();
if (appCursor != null && appCursor.getCount() > 0) {
appCursor.moveToFirst();
while (!appCursor.isAfterLast()) {
mReviewData = getDocument(appCursor);
appCursor.moveToNext();
}
appCursor.close();
}
return mReviewData;
}
#Override
protected void onPostExecute(ReviewJsonModel result) {
super.onPostExecute(result);
if (mDataLoadListener != null)
mDataLoadListener.onRatingDataLoaded(result);
}
}
Can't find cause of problem. Any help is appreciated.
Looks like there is callback issue, can you please try below
public void loadReviewData(RatingDataLoadListener listener, int destinationId) {
mDataLoadListener = listener;
new getReviews().execute(destinationId);
}
I have this function where it checks what are the choices of the users made.
So for example
there is a 4 choices:
InfoOfUp
InfoOfArt
InfoOfParish
InfoOfAteneo.
So when the user selects InfoOfUp and InfoOfArt then on the next activity, i will click a button that contains function : selected() it will check the items that was choosen by the user. if the user choose item InfoOfUp it will run a specific function and if the user choose item InfoOfArt it will also run a specific function
The problem is every item has it's own function and every item have progress dialog that marks if the function is already done or not.
So the user choose 2 items there's an error because there's 2 function being called up at the same time;
I want the function to be call 1by1 where the function waits to the other function to finish.
To avoid confusion, i call methods as function.
public void selected() {
if (InfoOfUp.select == 1) {
if (ayala == 0) {
ayala();
ayala = 1;
} else if (ayala == 1) {
}
}
if (InfoOfArt.select == 1) {
if (art == 0) {
ArtInIsland();
art = 1;
} else if (art == 1) {
}
}
if (InfoOfParish.select == 1) {
if (parish == 0) {
parish();
parish = 1;
} else if (parish == 1) {
}
}
if (InfoOfAteneo.select == 1) {
if (ateneo == 0) {
ateneogallery();
ateneo = 1;
} else if (ateneo == 1) {
}
}
Additionally, if the function calls, it will run an asynctask to get data.
here is my asynctask:
public class connectAsyncTask3 extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
private traffic traffic;
private boolean displayDestinationDetails;
String url;
boolean launchDestination;
connectAsyncTask3(String urlPass, traffic traffic, boolean displayDestinationDetails) {
this.url = urlPass;
this.traffic = traffic;
this.displayDestinationDetails = displayDestinationDetails;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
try {
super.onPreExecute();
progressDialog = new ProgressDialog(traffic.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if (result != null) {
Log.d("momo2", " : " + result);
traffic.drawPath(result);
speakOut();
}
if (displayDestinationDetails) {
Intent i = new Intent(traffic.this, poppers.class);
i.putExtra("currentMarker", traffic.markers.size());
traffic.startActivity(i);
}
}
}
Classic multi threading situation.
Create two threads, each one in the method related, start them and use
thread.join()
to begin second thread only after first finished.
great example here
I am working on a task that calls my AsyncTask , once the async task is executed , I wait for 20 seconds to get the data from server , if it is still loading I am cancelling it (handling timeout)
public void handleServerTimeOut() {
getStore = new GetStore();
getStore.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (getStore != null && getStore.getStatus() != AsyncTask.Status.FINISHED) {
boolean result = getStore.cancel(true);
Log.e(TAG, " handleServerTimeOut() reached 20 seconds");
Log.e(TAG, "" + result);
}
}
}, 20000);
}
AsyncTask
class GetStore extends AsyncTask<Void, Void, String> {
String status, message;
JSONArray jsonArray;
String buildingIdGuest, buildingIdUser, finalBuildingID;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isCancelled()) {
return;
} else {
buildingIdUser = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_USER, "");
buildingIdGuest = utilClass.getSharePerefernce(getActivity(), KEY_BUILDING_ID_GUEST, "");
if (buildingIdUser.equals("0") || buildingIdUser.equals("")) {
finalBuildingID = buildingIdGuest;
} else {
finalBuildingID = buildingIdUser;
}
error_flag = 0;
gridView.setVisibility(View.VISIBLE);
error_layout.setVisibility(View.INVISIBLE);
img_no_internet.setVisibility(View.INVISIBLE);
img_no_results.setVisibility(View.INVISIBLE);
img_server_error.setVisibility(View.INVISIBLE);
progressDialog.setMessage("Getting nearby stores ...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
if (NetworkCheck.isNetworkAvailable(getActivity())) {
try {
jsonObj = userFunction.getStores(OS, MAKE, MODEL, finalBuildingID);
Log.e(TAG, jsonObj.toString());
status = jsonObj.getString("status");
message = jsonObj.getString("message");
if (status.equalsIgnoreCase("success")) {
jsonArray = jsonObj.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
gridModel = new GridModel();
gridModel.setId(jsonArray.getJSONObject(i).getString("id"));
gridModel.setStore_name(jsonArray.getJSONObject(i).getString("name"));
gridModel.setImage_name(jsonArray.getJSONObject(i).getString("image_name"));
gridListData.add(gridModel);
}
Log.e(TAG, "****** = " + gridListData.toString());
} else if (status.equalsIgnoreCase("invalid parameters")) {
error_flag = 2;
Log.e(TAG, "invalid parameters");
} else if (status.equalsIgnoreCase("no stores")) {
error_flag = 3;
Log.e(TAG, "No Data");
}
Log.e(TAG, "****** status " + status);
return String.valueOf(jsonObj);
} catch (Exception e) {
error_flag = 1; // Handling server timeout.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
return;
}
});
Log.e(TAG, e.toString());
}
} else {
Log.e(TAG, "Network Error");
error_flag = 1;
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e(TAG, " **** error **** " + error_flag);
if (error_flag == 1) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_internet.setVisibility(View.VISIBLE);
} else if (error_flag == 2) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_server_error.setVisibility(View.VISIBLE);
txtError.setVisibility(View.VISIBLE);
txtError.setText(message);
} else if (error_flag == 3) {
gridView.setVisibility(View.GONE);
error_layout.setVisibility(View.VISIBLE);
img_no_results.setVisibility(View.VISIBLE);
}
gridAdapter = new GridAdapter(getActivity(), gridListData);
gridView.setAdapter(gridAdapter);
if ((progressDialog != null) && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
I also wanted to cancel my AsyncTask when the user cancels the ProgressDialog
You are checking isCancelled() only once in your AsyncTask - in the onPreExecute() method. At the time you call cancel() on your task instance, this check has already been evaluated and this is why the async task is still completing and updating the UI.
To deal with the issue, I suggest you include more checks for cancellation, using the isCancelled() method. One obvious place to include such a check is in the onPostExecute() method, right before you update the UI. You could also include a check before making the actual request to the server, after receiving the response, etc.
I am using Parse in order to store my data. During the user 's registration, I create an AsyncTask to set the result in the calling activity if the user's email exists or not. Here is the code to trigger the validation
View.OnClickListener btnNextClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etEmail == null) {
return;
}
final String email = etEmail.getText().toString();
if (email == null || email.length() == 0) {
etEmail.setError(getResources().getString(
R.string.error_email_is_null)
);
etEmail.requestFocus();
valid = false;
} else {
if (!Common.isValidEmailAddress(email)) {
etEmail.setError(getResources().getString(R.string.error_email_not_valid));
etEmail.requestFocus();
valid = false;
} else {
// validate Email from back end
new CheckEmailAsyncTask(CreateAccountActivity.this, email).execute();
if (emailValid == false) {
etEmail.setError(getResources().getString(R.string.error_email_existed));
etEmail.requestFocus();
valid = false;
}
}
}
if (valid) {
// if valid then going to the next step
Intent intent = new Intent(CreateAccountActivity.this, UpdateUserActivity.class);
intent.putExtra(AppConstant.PARAM_EMAIL, email);
startActivity(intent);
}
}
boolean emailValid;
public void setEmailValid (boolean emailValid) {
this.emailValid = emailValid;
}
};
and this is the code for CheckEmailAysncTask
public class CheckEmailAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
Context context;
CreateAccountActivity createAccountActivity;
String email;
public CheckEmailAsyncTask(CreateAccountActivity createAccountActivity, String email){
this.createAccountActivity = createAccountActivity;
this.context = createAccountActivity;
this.email = email;
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
this.progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
UserDAO userDAO = new UserDAO(context);
try {
int count = userDAO.isUserExists(email);
if (count > 0) {
createAccountActivity.setEmailValid(false);
} else {
createAccountActivity.setEmailValid(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
and in UserDAO
public int isUserExists(String email) throws ParseException {
ParseQuery query = new ParseQuery("User");
query.whereEqualTo("email", email);
return query.count();
}
However, in my setup, the code below the AsyncTask will be executed first before the result are returned back to from Parse. How can I just let the rest of the code wait for future return and then continue ? One of the solution that I come up with is to keep looping the calling to the AsyncTask and sleep for while until the result is back
Try this:
if (email == null || email.length() == 0) {
...
}
else if (email != null & email.length() != 0) {
...
}
One solution that I just came up with is sending a callback to the DAO layer function so when the done action is triggered, it will trigger back the callback to move on.
public interface NavCallback {
public void finish();
}
public class MainActivity {
// inside click listener
NavCallback navCallbackError = new NavCallback() {
#Override
public void finish() {
setError();
}
.....
}
and the DAO function will take the callback as the parameters
public void checkExists(String email, NavCallback callback) {
.....
if (callback != null) callback.finish();
}