I have a button, and when I clicked on it, I load other Activity, onCreate of this I call a method that fills a spinner with data from a Web Service.
Well, When I click at this button the screen stay "frozen" and then shows the Activity. So, I thought that it could be a good thing shows a progress dialog for user, and after gets the return of the Web Service, ends the progress dialog.
I tried use Handler, and now I'm trying to use AsyncTask, but, geting NullPointerException, because my program is filling spinner before web service get called.
private void fillSpinner(){
//runWebService();
new CallWebServiceAsyncTask().execute(null);
mAdapter = new PlanesAdapter(this, allPlanes);
mList.setAdapter(mAdapter);
}
class CallWebServiceAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(PlanesActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... v) {
runWebService();
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
because my program is filling spinner before web service get called.
you should fill data after getting data in onPostExecute Method
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
mAdapter = new PlanesAdapter(this, allPlanes);
mList.setAdapter(mAdapter);
}
What #SamirMangroliya suggested is correct but you even need to know where you are going wrong. When you call an AsyncTask you are asking the application to do some actions in the background which will take place in the non-UI thread. Now when you call execute() on your AsyncTask object the application code written in the function doInBackground(Void... v) runs in background and your control returns to the next statement following the call to execute() [new CallWebServiceAsyncTask().execute(null)], which in your case is the action of filling the adapter values. These values are yet to be received from the webservice. The only place where you can be sure that your background action is completed is the function onPostExecute(Void result) where as suggested you can create your adapter.
Related
There's a "download" button in each listview item. While the button is clicked, it will start a worker thread to down files. And at the same time, the button changed to progressbar and showing the progress rate.
So please show me some proper ways.
Use an AsyncTask since it has special methods for communicating with the main (UI) thread despite being asynchronous.
Here is an example:
http://android-er.blogspot.com/2010/11/progressbar-running-in-asynctask.html
Something like this:
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
protected void onPreExecute() {
ProgressDialog() progress = new ProgressDialog(context);
progress.setMessage("Loading ...");
progress.show();
}
protected Boolean doInBackground(Void... arg0) {
// Do work
return true;
}
protected void onPostExecute(Boolean result) {
progress.dismiss();
}
}
This should be nested in your activity class and executed like this:
new DownloadTask().execute();
You will likely need to adjust the asynctask to fit your needs but this will get you started.
my data is load from the internet, so I use the AsynTask(). execute() method to open a progressDialog first, then load the data in the background. it works, however, sometimes it takes too long to load the data so I want to cancel loading, and here is the problem: when I click back button the dialog dismiss but after it finish loading at the background, it start to do whatever it supposed to do after loading, e.g. start a new intent.
is there any way I can cancel the loading properly???
new GridViewAsyncTask().execute();
public class GridViewAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog myDialog;
#Override
protected void onPreExecute() {
// show your dialog here
myDialog = ProgressDialog.show(ScrollingTab.this, "Checking data",
"Please wait...", true, true);
}
#Override
protected Void doInBackground(Void... params) {
// update your DB - it will run in a different thread
loadingData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// hide your dialog here
myDialog.dismiss();
}
Call mAsycntask.cancel(); when you want to stop the task.
Then
#Override
protected Void doInBackground(Void... params) {
// update your DB - it will run in a different thread
/* load data */
....
if (isCancelled())
return;
/* continue loading data. */
return null;
}
Documentation:
http://developer.android.com/reference/android/os/AsyncTask.html#isCancelled()
Declare your AsyncTask like asyncTask = new GridViewAsyncTask();
Then execute it as you did it before (asyncTask.execute();) and to cancel it:
asyncTask.cancel();
Add the onCanceled method to your AsyncTask class and override it. Perhaps to show a Log or something else!
#Override
protected Void onCancelled () {
// Your Log here. Will be triggered when you hit cancell.
}
I need to make a transition screen, ou just put a dialog, because the app give a black screen when is creating the database.
I have google, and find some solutions for this. One of then, is just put a progress dialog when the database is been created.
My problem, and newbie question is, where do i put the progress dialog.
A -> BlackScreen -> B where A is the inicial menu, and B the other screen. I have tried to put the dialog on A and/or in B and dont work. So where can i put the code of the progress dialog, so it shows in the BlackScreen ?
Make use of Asyntask . put your database operation of creating database in asyntask in pre execute start dialog post execute cancel dialog in background perform database operation
http://developer.android.com/reference/android/os/AsyncTask.html
For that You have to use Async task :
class DownloadAsyncTask extends AsyncTask<String, String, Void>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Login.this, "", "Please Wait ...");
}
#Override
protected Void doInBackground(String... arg0) {
//Do your Task
}
#Override
protected void onProgressUpdate(String...values){
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
progressDialog.dismiss();
}
}
//Create the Object
DownloadAsyncTask downloadAsyncTask = new DownloadAsyncTask();
downloadAsyncTask.execute();
now till your work get's completed it shows progress dialog inside the doInbackground write your logic and onPostExecute dismiss the dialog and call Intent of other Activity.
I am using a TabActivity with 4 separate Activities - one for each tab.
One of the Activities is a ListView that has a custom ArrayAdapter.
The issue is that when I press the Tab to change to this view, the Activity loads the content in before the view changes, this appears as though nothing happens for a couple of seconds until the xml is loaded and parsed etc.
I have looked for an example but this is my first Android appllication and I am having difficulty in understanding the flow.
Can anyone point me to some code that will allow me to instantly change the view (I can inform user content is loading) while loading the content in the background thread
thank you
EDIT - I am porting code over from an existing iOS app - I wasn't able to better articulate the problem as I didn't realise how the UI thread could be blocked in this situation, and due to the complexity of the existing code and deadline I didn't want to change the structure too much.
I narrowed down the issue before I saw your code Jennifer but it is the solution I used so Ill mark yours as right.
here is what I used if it helps anyone else, I had to put the function I called to trigger the data load onto a background thread and then display the content when that thread had done its work
This class was declared within my
public class TableView extends ListActivity
Which was hard for me to get my head around having not done this before ;)
public class GetContentTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog pdialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdialog = new ProgressDialog(TableView.this);
pdialog.setTitle(progressDialogTitle);
pdialog.setMessage(progressDialogMessage);
pdialog.show();
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
setUpAndLoadList(); // the function to display the list and fill it with content
pdialog.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
doInitialLoad(); // The function to load any xml data from server
return null;
}
}
You can use a progress Dialog (can inform user content is loading)
ProgressDialog dialog;
private class XMLOperation extends AsyncTask<String, Void, String> {
/*
* (non-Javadoc)
*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
System.out.println("onPreExecute");
dialog= ProgressDialog.show(mContext, "", "Loading Content....");
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... urls) {
//do your Background task
}
protected void onPostExecute(String result) { //dismiss dialog
try {
if(dialog.isShowing()){
dialog.dismiss();
}
} catch (Exception exception) {
dialog.dismiss();
}
}
Use AsyncTask, or (possibly) a separate thread.
http://developer.android.com/reference/android/os/AsyncTask.html
I would also throw in my 2 cents and say don't use TabActivity. Just have your own buttons that look like tabs, but that's not really critical to this topic.
I have a ListActivity which launches another Activity based on the list selection. This second Activity needs to load a fair bit of data from the internet and as such there is a noticeable delay between when the user clicks on an item and when the Activity displays.
This is a problem because I currently have no way to indicate to the user that their click is being processed (even just changing the colour of the selected list item would be sufficient but I can't find a good way to do that). Ideally I'd be able to display an indeterminate ProgressDialog while the second Activity is loading.
I've tried a few different approaches for this but nothing seems to work as desired.
I've tried the following:
Retrieving the serializable data (not all of it but some part) in an AsyncTask in the first Activity and passing it as an extra to the second. This didn't really work well as a ProgressDialog I created in onPreExecute() didn't display immediately (it seems delayed by the processing done in doInBackground() for some reason.)
Here is the code for that:
AsyncTask<String, Void, String> read = new AsyncTask<String, Void, String>() {
Dialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(SearchActivity.this,
"Loading data", "Please wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
DatasetReader reader = new DatasetReader();
reader.setFundID(params[0]);
reader.addDatsets(FundProfile.datasets);
reader.populate();
return reader.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progress.dismiss();
}
};
read.execute(selectedItem.getUniqueID());
try {
action = new Intent(SearchActivity.this, FundProfile.class);
action.putExtra("data", read.get());
} catch(Exception ex) {
ex.printStackTrace();
}
In the second Activity's onCreate() method (this does not work at all):
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarVisibility(true);
Here is the onCreate() method for the second approach:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setTitleColor(Color.WHITE);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarVisibility(true);
try {
setContentView(R.layout.fund_profile);
// init some data
setProgressBarVisibility(false);
} catch(Exception ex) {
FundProfile.this.finish();
}
}
If you have long operations you should not be doing them in onCreate in any case as this will freeze the UI (whether or not the activity is displayed). The UI set by onCreate will not appear and the UI will be unresponsive until after the onCreate call finishes.
It seems you can start your second activity and display a progress bar (or requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);), then start an ASyncTask which will be responsible for updating your UI once data has been retrieved.
Adam,
It sounds like you are looking for the Indeterminate Progress bar: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ProgressBar2.html
You can display this while you are loading your second Activity then set the visibility to false once the second Activity has loaded its data.
Move creating the Intent -- and really anything you need to do after the AsyncTask completes -- into onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progress.dismiss();
Intent action = new Intent(SearchActivity.this, FundProfile.class);
action.putExtra("data", result);
// ... do more here
}
The problem is that AsyncTask.get() blocks until the task is completed. So in the code above, the UI thread is blocked and the ProgressDialog is never given a chance to appear until the task completes.