Android Calling Multiple methods 1 by 1 - android

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

Related

View not updated from callback method

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);
}

Syncronous API calls

I'm working on an Android app by adding a new functionality that fetch and save data with API calls.
These calls are made in a Fragment. There is a call made in an AsyncTask, and I don't want to create an AsyncTask for every call, so I just try send parameters to my controlles in some function, but when I debug every time I try to make a call without using an AsyncTask, I got an IOException "Cancelled". Is there a way to do this without using AsyncTasks in the same Fragment?
This is the AsyncTask:
private void validateUnit(#NonNull String unitCode, final int routeId, final boolean goodCondition) {
mUnitDetails = new UnitDetails();
if (mFindUnitAysncTask != null) {
mFindUnitAysncTask.cancel(true);
}
mFindUnitAysncTask = new AsyncTask<String, Void, FindUnitResponse>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog();
}
#Override
protected FindUnitResponse doInBackground(String... params) {
FindUnitResponse unitResponse = mUnitController.findUnit(params[0], routeId);
FindUnitDetailsResponse unitDetailsResponse = mUnitController.getUnitDetails(
unitResponse.getUnits().get(0), mUser);
if(unitDetailsResponse.isSuccess()) {
mUnitDetails.setBranchCode(unitDetailsResponse.getBranchCode());
mUnitDetails.setBranchName(unitDetailsResponse.getBranchName());
mUnitDetails.setCompanyId(unitDetailsResponse.getCompanyId());
mUnitDetails.setEconomicNumber(unitDetailsResponse.getEconomicNumber());
mUnitDetails.setFuelType(unitDetailsResponse.getFuelType());
mUnitDetails.setFuelTypeId(unitDetailsResponse.getFuelTypeId());
mUnitDetails.setFuelPrice(unitDetailsResponse.getFuelPrice());
mUnitDetails.setModel(unitDetailsResponse.getModel());
mUnitDetails.setBrand(unitDetailsResponse.getBrand());
mUnitDetails.setUnitType(unitDetailsResponse.getUnitType());
mUnitDetails.setRouteCode(unitDetailsResponse.getRouteCode());
mUnitDetails.setRealTrips(unitDetailsResponse.getRealTrips());
mUnitDetails.setMaximumMileageRange(unitDetailsResponse.getMaximumMileageRange());
}
else {
showMessage(unitDetailsResponse.getMessage());
}
return unitResponse;
}
#Override
protected void onPostExecute(FindUnitResponse response) {
super.onPostExecute(response);
dismissProgressDialog();
if (response != null && response.isSuccess()) {
//Unit unit = response.getUnits().get(0);
unit = response.getUnits().get(0);
finishChecklist(unit, goodCondition);
} else {
showMessage(response.getMessage());
saveChecklist();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
dismissProgressDialog();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, unitCode);
}
With that I fetch the details of a vehicle. Then I have a method called validateMileage.
private void validateMileage(#NonNull Unit unit, #NonNull User user, #NonNull int mileage, int travels,
final boolean dayFinished) {
List<Incident> incidents = mIncidentController.getIncidentList();
Incident suspiciousMileageIncident = mIncidents.get(2);
List<Manager> managers = mManagersController.findByIncidentId(suspiciousMileageIncident.getId());
.....
}
If I just try to make calls like .getIncidentsList or .findByIncidentId I got an IOException when I wait for the response. But if I make the call in an AsyncTask, there is not errors.

How to call a asyncTask several times inside a loop- one after another

Actually what i am trying to do is that call an asyncTask several times inside a loop. So, first time the asyncTask will start immediately and from second time onwards, it will check whether the AsyncTask has been finished-if finished than again call it with different values.
Below is my code for the activity:
In onCreate()
btnUpload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
count_response = 0;
newUploadWithSeparate();
}
});
The newUploadWithSeparate() method:
private void newUploadWithSeparate()
{
responseString_concat = "";
if(filePath.length > 0)
{
for(int i=0;i<filePath.length;i++)
{
count_response = i;
if(i == 0)
{
uploadAsync.execute(filePath[0]);
mHandler = new Handler() {
#Override public void handleMessage(Message msg) {
String s=(String)msg.obj;
Log.d("logIMEI","\n Response from Asynctask: " + s);
str_response_fromAsync = s;
}
};
}
else
{
uploadAsync.getStatus();
while(uploadAsync.getStatus() == AsyncTask.Status.RUNNING) // this while loop is just to keep the loop value waitining for finishing the asyncTask
{
int rx = 0;
}
if(uploadAsync.getStatus() != AsyncTask.Status.RUNNING)
{
if(uploadAsync.getStatus() == AsyncTask.Status.FINISHED)
{
if(str_response_fromAsync != "" || !str_response_fromAsync.equals("") || !str_response_fromAsync.isEmpty())
{
uploadAsync.execute(filePath[i]);
x = i;
mHandler = new Handler() {
#Override public void handleMessage(Message msg)
{
String s=(String)msg.obj;
Log.d("logIMEI","\n Response from Asynctask_" + x + ": " + s);
str_response_fromAsync = s;
}
};
}
}
}
}
}
}
}
And the asyncTask:
private class UploadFileToServer extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... params)
{
return uploadFile(params[0]);
}
private String uploadFile(String pr)
{
//inside here calling webservice and getting a response string as result.
MyWebsrvcClass mycls = new MyWebsrvcClass();
return responseString_concat = mycls.Call(xxx,yyy) ;
}
#Override
protected void onPostExecute(String result)
{
Log.d("logIMEI" , "\n count_response : "+ count_response + " fileprath_len : " + filePath.length);
Message msg=new Message();
msg.obj=result.toString();
mHandler.sendMessage(msg);
super.onPostExecute(result);
}
}
Now the problem is that its not working as expected. The first time when value of i is equals 0 than the AsyncTask gets called and after that its not getting called anymore.
Plus, when first time AsyncTask is called- its still not directly entering to onPostExecute(). When the loop ends totally and newUploadWithSeparate() method ends then the onPostExecute() is working.
Any solutions for this or any other way to do this job done for using AsyncTask inside loop?
You cannot call execute() on the same object more than once. So create a new instance of UploadFileToServer for each iteration of the loop.

Android - Async validation from Parse

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();
}

Splash screen with background task

I have a splash screen that loads URLs from the Internal Storage and downloads their content from the Web (with an AsynkTask). It puts the downloaded data into an ArrayList, calls the main Activity and finishes. The main activity adapter manages the ArrayList and sets a ListView containing its data.
While I'm in the main Activity, if I press the back button the application exits (I set the android:nohistory="true" for the splash screen activity), but when I return to the app, the splash screen gets loaded and downloads the data again, "doubling" the list view.
How can I prevent the splash screen to be loaded when I return to the app?
Splash screen code:
Context mContext;
ProgressBar progress = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_launcher);
progress = (ProgressBar)findViewById(R.id.progress);
progress.setIndeterminate(true);
if(canWriteOnExternalStorage()) {
try {
setupStorage();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
//dialog appears
}
AsynkTask code:
private class LoadGames extends
AsyncTask<String, Integer, Boolean> {
private ProgressDialog mProgressDialog = null;
private String remoteUrl = null;
#Override
protected void onCancelled() {
Log.e(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: onCancelled !");
super.onCancelled();
}
#Override
protected void onPreExecute() {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: onPreExecute !");
}
#Override
protected Boolean doInBackground(String... params) {
if (params.length == 0)
return false;
else
for (int k = 0; k < (params.length)/2; ++k)
{
this.remoteUrl = params[k*2];
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: doInBackground ! ("
+ this.remoteUrl + ")");
// HTTP Request to retrieve the videogames list in JSON format
try {
// Creates the remote request
Log.d(com.example.ludos2_0.MainActivity.TAG,
this.remoteUrl);
RESTRequest request = new RESTRequest(this.remoteUrl);
request.isMethodGET(true);
// Executes the request and print the received response
String response = RESTRequestExecutor.execute(request);
// Custom/Manual parsing using GSON
JsonParser parser = new JsonParser();
if (response != null && response.length() > 0) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Response: "
+ response);
JsonObject jsonObject = (JsonObject) parser.parse(response);
JsonObject itemObj = jsonObject.getAsJsonObject("results");
String id = null;
String title = null;
String thumbnail = null;
String description = null;
String image = null;
String platform = null;
id = itemObj.get("id").getAsString();
title = itemObj.get("name").getAsString();
if (!(itemObj.get("image").isJsonNull()))
{
thumbnail = ((JsonObject)itemObj.get("image")).get("tiny_url").getAsString();
image = ((JsonObject)itemObj.get("image")).get("small_url").getAsString();
}
else
{
thumbnail = "http://www.persicetometeo.com/images/not_available.jpg";
image = "http://www.persicetometeo.com/images/not_available.jpg";
}
description = itemObj.get("deck").getAsString();
platform = params[k*2 + 1];
Log.d(com.example.ludos2_0.MainActivity.TAG,
title);
ListsManager.getInstance().addVideogame(new Videogame(id, title, thumbnail, image, description, platform));
} else {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"Error getting response ...");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(com.example.ludos2_0.MainActivity.TAG,
"Exception: " + e.getLocalizedMessage());
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: onPostExecute !");
progress.setVisibility(View.GONE);
if (result == false) {
Log.e(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: Error Downloading Data !");
} else {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: Data Correctly Downloaded !");
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
}
super.onPostExecute(result);
}
}
The setupStorage() method loads the file from the Storage and executes the AsynkTask.
Maybe could the overriding of the onRestart() method be a solution?
Or should I prevent the AsyncTask from loading the data already downloaded?
Thanks!
It would be better to prevent AsynkTask to download it again. Or better to clear your listview data. Means if use ArrayList with your List adapter then just clear it before storing putting new data.

Categories

Resources