Display the rotating progress before display the data - android

I'm displaying some data by using SQLite. When I click on one button data come from database. It takes some time. At that time the screen is black. At that time I want to display the rotating spinner before the data dispay. Any ideas?

Android provides a ProgressDialog for accomplishing what you want.

First i would like to suggest to have a look at AsyncTask page, so that you will come to know about the AsyncTask exactly.
Now, Implement AsyncTask as given below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new performBackgroundTask().execute();
}
private class performBackgroundTask extends AsyncTask <Void, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(main.this);
protected void onPreExecute()
{
Dialog.setMessage(getString("Please wait..."));
Dialog.show();
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
// displaying all the fetched data
}
#Override
protected Void doInBackground(Void... params)
{
// implement long-running task here i.e. select query/fetch data from table
// fetch data from SQLite table/database
return null;
}
}
Enjoy !!!

You should not execute long running tasks in UI thread as this blocks the UI redraw and makes app look unresponsive.
Use AsyncTask to execute long running tasks in background, while still updating the screen.

You can look at the standard music picker as one example of how to do this:
https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MusicPicker.java
In addition to the whole "queries must be done off the main UI thread," this shows an indeterminant progress while first loading its data, fading to the list once the data is available. The function to start the query is here:
https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MusicPicker.java#581
And to do the switch is here:
https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MusicPicker.java#569
The layout has the list view put in a frame layout with another container holding the progress indicator and label. The visibility of these is changed to control whether the list or progress indicator are shown:
https://android.googlesource.com/platform/packages/apps/Music/+/master/res/layout/music_picker.xml

Related

how to show progress dialog on switching tabs in Tab layout

I have read many solutions here to show a progress dialog on switching tabs as some of the tabs fetching data from server takes time in between that period i need to show progress dialog, do suggest where to put the code to accomplish my task
Initiate an Async which does the fetching data in the background and manages the progress dialog (or even progress layout which might be better) in the onprogressupdate method. If you subclass this it will be fairly easy to implement. Here's a link.
Add this
private class myAsyncTaskClass extends AsyncTask{
#Override
protected void onProgressUpdate(Object... values) {
// TODO Add updates to your progress dialog here.
super.onProgressUpdate(values);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Add your fetching data here
//Use publish progress to call the onProgress update passing whatever you want.
publishProgress(values);
return null;
}}

Setting AsyncTask progress for SQLite - cannot get progress percentage

I have created a splash screen for my app to hide the periodic insertion (after publishing updates) of a large number of records into the different tables of my app's SQLite database. I have been implementing an AsyncTask to handle the insertion off of the UI thread.
I need to create a ProgressDialog (with progress bar, not the simple spinning wheel) to inform the user of the current progress percentage for the insertion operations.
In most examples for setting the dialog's progress bar, the counter variable for the for loop representing the lengthy operation, or the percentage of file download is used to set this progress for the dialog. However, since insertions into different tables may take different amounts of time (depending on number of columns, etc), this approach appears to fail. The closest solution I could see would be to write a publishProgress(some_percentage) line after every record insertion in my doInBackground() method, using the % of records inserted as the parameter for publishProgress(), but this seems like a terribly inelegant and inefficient practice.
The current code for my AsyncTask implementation is below. Any suggestions for the best practice of determining the current progress percentage would be greatly appreciated. Thanks!
private class InsertionAction extends AsyncTask<Void,Integer,Void> {
Context context;
private ProgressDialog dialog;
private ForwardAction(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Initializing Database. Please Wait...");
this.dialog.show();
this.dialog.getWindow().setGravity(Gravity.BOTTOM);
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.setCancelable(false);
}
#Override
protected Void doInBackground(Void... params) {
// Large block of record insertions
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// Forward to the main activity
if (dialog.isShowing()) {
dialog.dismiss();
}
animatedTransition(SPLASH_DISPLAY_TIME/2);
}
#Override
protected void onProgressUpdate(Integer... values) {
}
}
Unfortunately there is no way to programmatically count your lines of code, calculate how much time they need to execute and generate an accurate time-proportionate progress.
I suggest updating the progress bar after a certain interval of lines, e.g. every 90 inserts (10%).
Or update according to what you are doing and modify the progress message (try to be creative), e.g. "Adding users", "Generating death rays", "Creating the universe", "Just a little longer", etc.

Android: How to solve slow response after clicking TabWidget

I have four Tab at the top of my apps
The content of the fourth tab is that it will get data from sql server and then display in listview
since the amount of data retrieved is quite big, it takes 2-3 sec
The problem is that:
After I click the fourth tab, it has no response, then after 2-3sec, it displays the content
As I know it is loading the data from database, I will not continue to click
However, when users click it and no response, he may click and click and click
How to show something to user so that they know it is loading data??
You should use a CrusorLoader. This will display a loading circle while still making the UI active. Note that even if you're using lower versions of the android API, you can still access the CursorLoader class via the Android Support Package. For more information on loaders, checkout
new SomeTask(0).execute(); // write this line in your 4th tab onCreate()
/** Inner class for implementing progress bar before fetching data **/
private class SomeTask extends AsyncTask<Void, Void, Integer>
{
private ProgressDialog Dialog = new ProgressDialog(yourActivityClass.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("loading...");
Dialog.show();
}
#Override
protected Integer doInBackground(Void... params)
{
//Task for doing something
// get data from sql server and then display in listview
return 0;
}
#Override
protected void onPostExecute(Integer result)
{
if(result==0)
{
//do some thing if your list completed
}
// after completed finished the progressbar
Dialog.dismiss();
}
}
When a long-running process is started, you'll want to indicate that something is happening so the user knows to wait. You want a progress dialog.
Here is an example:
http://www.androidpeople.com/android-progress-dialog-example

Android : how to initialize an activity in background before displaying it

I have an activity in which I display an image that is stored on a website.
I am using the following code to get it from its url and display the activity :
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.ad_screen);
AsyncTask<String, Void, Integer> task = new AsyncTask<String, Void, Integer>()
{
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
#Override
protected Integer doInBackground(String... urls)
{
fetchAd();
return 0;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
#Override
protected void onPostExecute(Integer result)
{
displayAd();
}
};
task.execute("");
}
That works very fine, but the behaviour is not the one I want : in this case, the activity is pushed on the screen (with a right to left animation) and then the AsyncTask begins. So the image is displayed on screen after a delay (which is normal).
But I would like to perform the request before the activity is pushed, so that the screen is displayed directly with its image without any delay.
Is there a way to have this behaviour ?
Thanks in advance.
You can download the image in the previous activity, create a bitmap, then pass it as an extra in the intent that launches this activity.
Use AsyncTask to load images in previous activity, and display the images in the current activity.
You could in the "parent" activity, the one that starts the new activity, do the fetching of the content, store it either in memory or some sort of fast access persistence, and after that start the activity.
Same principle could be to introduce a "loader" activity which would show a loader, and prefetch the data, when all data received it would start the activity that should display the data.

Android ASync task ProgressDialog isn't showing until background thread finishes

I've got an Android activity which grabs an RSS feed from a URL, and uses the SAX parser to stick each item from the XML into an array. This all works fine but, as expected, takes a bit of time, so I want to use AsyncActivity to do it in the background. My code is as follows:
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}
Which I call in onCreate() with
new AddTask().execute();
The line items = parser.getItems() works fine - items being the arraylist containing each item from the XML. The problem I'm facing is that on starting the activity, the ProgressDialog which i create in onPreExecute() isn't displayed until after the doInBackground() method has finished. i.e. I get a black screen, a long pause, then a completely populated list with the items in. Why is this happening? Why isn't the UI drawing, the ProgressDialog showing, the parser getting the items and incrementally adding them to the list, then the ProgressDialog dismissing?
I suspect something is blocking your UI thread after you execute the task. For example, I have seen folks do things like this:
MyTask myTask = new MyTask();
TaskParams params = new TaskParams();
myTask.execute(params);
myTask.get(5000, TimeUnit.MILLISECONDS);
The get invocation here is going to block the UI thread (which presumably is spinning off the task here...) which will prevent any UI related stuff in your task's onPreExecute() method until the task actually completes. Whoops! Hope this helps.
This works for me
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(viewContacts.this);
dialog.setMessage(getString(R.string.please_wait_while_loading));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
It is because you used AsyncTask.get() that blocks the UI thread "Waits if necessary for the computation to complete, and then retrieves its result.".
The right way to do it is to pass Activity instance to your AsyncTask by constructor, and finish whatever you want to do in AsyncTask.onPostExecution().
If you subclass the AsyncTask in your actual Activity, you can use the onPostExecute method to assign the result of the background work to a member of your calling class.
The result is passed as a parameter in this method, if specified as the third generic type.
This way, your UI Thread won't be blocked as mentioned above. You have to take care of any subsequent usage of the result outside the subclass though, as the background thread could still be running and your member wouldn't have the new value.

Categories

Resources