I have two Activitys (mainActivity & downloadActivity) and I have 2 AsyncTasks in downloadActivity
In downloadActivity first it execute getFileAsyncTask for reading a JSON file for adding some images and create a ListView from images, if user clicks on an image, the downloadAsyncTask was called and it starts to download something from the internet.
My problem is here: when the second AsyncTask is running I go back to mainActivity and comeback again to downloadActivity the first AsyncTask wasn't called until the downloadAsyncTask completed.
public class downloadActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
new getFileAsyncTask().execute();
...
}
private class getFileAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//fetch a json file from internet and add images in ListView
return null;
}
}
//there is a Base Adapter class
//if user clicks on an image it calls this downloadAsyncTask.execute()
private class downloadAsyncTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
//download the file
}
}
#Override
protected Void doInBackground(Void... unused) {
//download the file
}
}
note: I want to write something like shopping apps. For example, user can download file and surf into shop to see products .
If you want to run multiple AsyncTasks in parallel, you can call executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) instead of execute() on your task. By default, AsyncTasks run in serial, first come first serve.
Be careful that the two threads do not interact on the same data, this can cause some strange and hard to trace errors.
you can make it in one asynk class that have two methodes first fetch json file wait response in doInBackground ... if it is ok call download file methode. Those methodes will return an httpResponse object
You can override onBackPressed function in activity and finish the current activity before go to previous activity. When again you come to downloadActivity it call it's oncreate method and call first AsynctTask.
Make one class task like:
Declare progress bar globally in main thread.
Now what you have to do is start one async task in main thread like:
public class myactivity extends Activity {
private ProgressDialog _dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_screen);
new abc().execute();
}
class abc extends AsyncTask(String,String,String) {
#Override
protected void onPreExecute() {
_dialog = new ProgressDialog(_ctx);
_dialog.setCancelable(false);
_dialog.setMessage("Loading");
_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
#Override
protected void onPostExecute(String result) {
// in post execute of this class you can run a new thread of your downaloder thread. and in post execute of last thread you have to dismiss the progess bar.
new download activity.execute();
}
}
}
}
}
Related
I want to show some message and a progress bar while my app initializes.
I need to insert some dictionaries of words into a SQLite database the first time my app is run. To do this I have an AsyncTask which opens my SQLiteOpenHelper and closes it again, just so the database initialization is done once.
private class AsyncDbInit extends AsyncTask<Void, Void, Void> {
private Context context;
private Intent intent;
public AsyncDbInit(Context context, Intent intent){
this.context = context;
this.intent = intent;
}
#Override
protected Void doInBackground(Void... params) {
DatabaseHandler db = new DatabaseHandler(this.context);
db.close();
return null;
}
#Override
protected void onPostExecute(Void param) {
context.startActivity(this.intent);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... params) {}
}
This AsyncTask is called in my onCreate() method, but I've also tried to run it from onStart() and onResume() without succes.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dispatcher);
... //some code finding the right intent
new AsyncDbInit(this, nextIntent).execute();
}
Somehow this last line, which calls the AsyncTask, stops my UI from showing up; the screen just stays blank until the AsyncTask is completed and the new activity is started.
When I comment that line out, the UI shows up just fine.
The only thing I can come up with is that the SQLiteOpenHelper somehow blocks the UiThread, but I couldn't find anything about that either.
In the AsyncTask we have some methods. Just like in doInBackground() we do the things we wants to be done in the background and there are two methods also whch are onPreExecute() and onPostExecute(). Create and progress dialog and show the dialog in onPreExecute() method and dismiss it in onPostExecute() method.
Try using AsynTask.executeOnExecutor() with the thread pool executor. If this works, it means something involved with loading your UI is also using an AsyncTask. AsyncTasks by default run sequentially on a single work thread and this can introduce contention. This serial execution is often what you want, but not always.
Does you UI use any libraries to load strings or other content? Can you provide your layout XML?
By the time android apps onStart(),it would execute HttpRequestTask. I have done this part and it works fine.
After the apps open and display data,needs to click on a submit button to POST some data to spring rest web service.In my mind,I think I might need to write another extends AsyncTask ,doInBackground and onPostExecute
What should I code so that system could differentiate extends AsyncTask ,doInBackground and onPostExecute within same Activity?
protected void onStart(){
super.onStart();
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ArrayList<Item>> {
#Override
protected ArrayList<Item> doInBackground(Void... params) {
//....some code
}
#Override
protected void onPostExecute(ArrayList<PickerItemDetail> pickerList) {
//.....come code and logic
}
}
I have 3 activities:
MainActivity
Activity A
Activity B
The user can start a process in Activity B. I show a notification helper % completed, and I go back to MainActivity.
But I don't want to user to be able to do anything with the app until the process had completed, so basically - there is a button on MainActivity that I want to be disabled until the process has completed.
Anyway to check if the notificationbar is still there when they click a button, or anyway to check if the async task is still running?
Thanks
private class DownloadStuff extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
// DO STUFF in Background
return null;
}
protected Void onPostExecute() {
// Disable Button
}
}
More info: http://developer.android.com/reference/android/os/AsyncTask.html
ok use this in asynctask
on preExecute()
button1.setEnabled(false);
on postExecute()
button1.setEnabled(true);
By Use of Async Task u can solve that
Think to use something like :
MainActivity.java
MainActivity implements LoadingTaskFinishedListener
#Override
public void onTaskFinished() {
myButton.setEnabled(true);
}
..
public class Task extends AsyncTask<String, Integer, Integer> {
Actualite[] pages;
int i=0;
public interface LoadingTaskFinishedListener {
void onTaskFinished();
}
In my app, I am trying to run multiple photos through a photo editor (one at a time). I have it set up in a for-loop at the moment, but I feel like it is overloading the photo editor and not actually waiting until the current edit session is over, so I wanted to put a control statement in my for-loop to check if the session was still active.
Is this possible?
Easier to tell when the current is over than polling to see if it is still active. If you start it with startActivityForResult, your calling activity will be notified when the invoked activity ends.
Have a look at Starting Activities and Getting Results in the Activity docs for an example.
You might also want to consider running this in an async task. This will pull your heavy processing away from the UI thread. Async task let's you do progress updates as well.
http://developer.android.com/reference/android/os/AsyncTask.html
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo_page);
// Call async task.
my_async as = new my_async(this);
as.execute();
}
--
my_async:
public class my_async extends AsyncTask<Object, Integer, String> {
private parentClass activity;
public my_async (parentClass activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Object... arg0) {
// Do stuff
return "MyString";
}
protected void onPostExecute(String contents) {
activity.contents = contents;
}
This maybe a stupid idea, but does anyone know is it possible to access one activity's object form other places?
To be specific, lets say if you have an activity A (with a textView t) and you create a normal java class B.
At onCreate, you start to run B for some calculation like below,
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.outputtext);
Somejava B = new Somejava();
B.run();
}
}
Is there a way for B to update the textView?
I know the simple way (maybe the correct way) is to return the result from B class and use t.setText(result) in MyActivity, but I'm just want to know is it possible to update the textview in B?
Use Intent or public static variables
can simply pass activity refernce to b in constructor and create the method in your acitivty to update textview. if you using another thread not forgot to use handler or other ways to update UI thread.
Yes, it is possible if the Activity's field is public and post the UI changes in a public Handler created on the first Activity but in facts, it's really ugly to do that...
You can use startActivityForResult(...) to notify an other activity how the process has passed with some serialiezable data in the Bundle extras of the Intent and catch the result in the overrided method onActivityResult(...)...
For a "normal java class" B I would work with interfaces
public interface SomejavaListener{
void onSomejavaFinish(Object result);
}
public class MyActivity implements SomejaveFinish extends Activity {
TextView t;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.outputtext);
Somejava B = new Somejava();
B.run(MyActivity.this); //notice the extra argument!
}
public void onSomejavaFinish(Object result){
t.setText("updated! ^,^");
}
}
public class Somejava {
//...
public void run(SomejavaListener callback){
//working working
callback.onSomejavaFinish( new Object() );
}
}
However in respect to the android environment the question is sitting in I got the feeling maybe an AsyncTask would be the right thing for you. It has an doInBackground method to do work and not spoiling your UI Thread (resulting in ANR Errors.)
Another advantage is the onPreExecute and onPostExecute methods are running in the UI Thread itself again, so it just takes a blink to update your TextView
public class MyActivity extends Activity {
TextView t;
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... void) {
//do your stuff
return null
}
protected void onPostExecute(Void void) {
MyActivity.this.t.setText("updated ^^v");
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView) findViewById(R.id.outputtext);
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
}
}