How to get value from result of asynctask to use in MainActivity - android-asynctask

I want to get the value of a and set to b,how can i do that?
public class MainActivity extends AppCompatActivity {
int a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Task task=new Task();
task.execute(5,6);
b=a;
}
public class Task extends AsyncTask<Integer,Void,Integer>{
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
a=integer;
}
#Override
protected Integer doInBackground(Integer... integers) {
return integers[0]+integers[1];
}
}
}

in line b=a; run on time running other thread
best result is in method onPostExecute write b = a;
so b before than a be set

In your question you are already having the answer.
After executing this statement.
Task task=new Task();
task.execute(5,6);
After executing task.execute first doInBackground will be called and then it will return to onPostExecute then sum of a and b and your are assigning to a.
just write b=a in onPostExecute and it will work as your want.

Related

Recyclerview not populating in asynctask android

I have two methods which I need to run asynchronously in android.First I want to run getContactsList() and then populateList().I tried to use Asynctask but it skips the recyclerview populating code and then prints the next line in the log while it works well in onCreate.Please help me
private class TaskOne extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.i("do in background", "running");
getContactList();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.cancel();
Log.i("onPostExecute", "running");
populateList();
isContacts_fetched();
Log.i("populateList", "finished");
}
}
calling in onCreate() methods
new TaskOne().execute();
populateList() code
public void populateList() {
Log.i("Populate List","Entered");
// Toast.makeText(this,String.valueOf(Common.selectedContactNos.size()),Toast.LENGTH_LONG).show();
displayRecyclerAdapter = new DisplayRecyclerAdapter(DisplayContacts.this);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
recyclerView_contacts.setAdapter(displayRecyclerAdapter);
recyclerView_contacts.setLayoutManager(mLinearLayoutManager);
displayRecyclerAdapter.notifyDataSetChanged();
}

Return value from AsyncTask

I have a class AsyncTask as an inner class to a fragment.
public class MyAsyncTask extends AsyncTask<String,double[],double[]> {
double posScoreb = 0.0;
double negScoreb= 0.0;
public AsyncResponse delegate = null;
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);}
#Override
protected double[] doInBackground(String... params) {
s = new SentiCalc(getActivity().getAssets());
s.setInput(String.valueOf(params[0]));
double[] set = new double[]{};
try {
set = s.getSenti();
} catch (IOException e) {
e.printStackTrace();
}
posScoreb = set[1];
negScoreb = set[2];
return new double[]{posScoreb,negScoreb};
}
#Override
protected void onPostExecute(double[] result) {
progressBar.setVisibility(View.GONE);
result[0] = posScoreb;
result[1] = negScoreb;
delegate.processFinish(result);
Toast.makeText(getActivity(), "Done",Toast.LENGTH_LONG).show();
}
}
I am calling it from a method saveNote() inside the same fragment.`
asyncTask = new MyAsyncTask() ;
asyncTask.delegate =this;
asyncTask.execute(content);
I want AsyncTask class to return values inside a result(double array) to saveNote method. As shown in this, How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?.
I created an interface and made my fragment class to implement it.
public interface AsyncResponse {
void processFinish(double[] output);}
As a result of which I am able to get the result inside a method processFinish
within the same fragment.
#Override
public void processFinish(double[] output) {
double posScore,negScore;
posScore = output[0];
negScore = output[1];
Toast.makeText(getActivity(),String.valueOf(posScore),Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), String.valueOf(negScore), Toast.LENGTH_LONG).show();
}
How can I get this result inside a saveNote method from which I am calling AsyncTask class?

Parse Local Datastore e Message "no results found for query"

I am trying to finish this program and i am stuck. This is my first program and now it wont work. I keep getting this error when i add query.fromLocalDatastore(); The code runs fine until i try to get it from the local storage. This is telling me there is nothing there for it to retrieve and i don't know why. When i added my test data it worked fine but when i try to pull data from another table i get the error above. Apparently when i added the test data the server synced with the local datastore. Now it is not. Can someone tell me what I did wrong?
public class DataHolder extends Application {
int age;
#Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(getApplicationContext());
Parse.initialize(this,key, key);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
ParseACL.setDefaultACL(defaultACL, true);
}
public class MainActivity extends ActionBarActivity implements Disclaimer.DisclaimerListener {
protected void continueToRun() {
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter, View v, int x, long lng) {
final ParseQuery<ParseObject> query = ParseQuery.getQuery("Phone_Numbers");
query.fromLocalDatastore();
if (x == 1) {
final Intent intent = new Intent(getBaseContext(), Protocol_Template.class);
query.fromLocalDatastore();
query.whereEqualTo("objectId", "uGANULyrdL");
startActivity(intent);
}
}
public class Protocol_Template extends Activity {
DataHolder global;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_protocol__template);
final TextView protocol = (TextView) findViewById(R.id.txt02);
findViewById(R.id.btn2timesUpperLeft);
final ParseQuery<ParseObject> query = ParseQuery.getQuery("Phone_Numbers");
query.fromLocalDatastore();
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
final String protocols = object.get("PhoneNumber").toString();
protocol.setText(protocols);
} else {
protocol.setText(e.getMessage());
}
}
});
}

How to use asynctask to display a progress bar that counts down?

In my application i want the user to press a button and then wait 5 mins. i know this sounds terrible but just go with it. The time remaining in the 5 min wait period should be displayed in the progress bar.
I was using a CountDownTimer with a text view to countdown but my boss wants something that looks better. hence the reasoning for a progress bar.
You can do something like this..
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
This should solve your purpose and it wont even block UI tread..

Gridview onScroll method gets called always, without user scroll

I have a customized gridview where i'm checking onScroll method to find the end of the list. If the scroll reaches the end of the list, it will again add few elements in to the list.
gridview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
}
#Override
public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && (!loadingMore))
{
new LoadDataTask().execute();
}
}
});
And this is my Asynchronous task class..
private class LoadDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
loadingMore = true;
for (int i = 0; i < mNames.length; i++)
mListItems.add(mNames[i]);
return null;
}
#Override
protected void onPostExecute(Void result) {
mListItems.add("Added after load more");
loadingMore=false;
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
}
}
Now the issue is that the onScroll method keep on calling. It doesn't stop even when the user not scrolling. Can anyone have a solution ?
Please check the answer for this question: onScroll gets called when I set listView.onScrollListener(this), but without any touch .
The same is true for the GridView, since it has AbsListView as superclass just as ListView does.

Resources