How to implement rotate animation ProgressDialog with asynctask - android

I show my rotate animation inside progressdialog before execute asynctask with this code
ProgressDialog pDialog = ProgressDialog.show(getActivity(), null, null, true, false);
pDialog.setContentView(R.layout.loading);
this is R.layout.loading xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ln_loadingcontainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00000000">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/Widget.ProgressBar.Large"
android:layout_gravity="center"/>
<TextView
android:id="#+id/tv_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading..."
android:textSize="24dp"
android:textColor="#ffffff"
android:layout_marginTop="5dp"
android:layout_gravity="center"/>
</LinearLayout>
Then i excute my asynctask. The problem when asynctask doInbackground my ProgressDialog is not display animation.
After asynctask onPostExecute my ProgressDialog is start animation.
Why on doInbackground my ProgressDialog not display animation?
How to solve it?
I want to display rotate animation inside dialog before excute asynctask and hide dialog after asynctask excute finish.
EDIT
1.global variable of ProgressDialog
private ProgressDialog pDiaalog;
2.in oncreate of activity
gv_table.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
progressDialog = ProgressDialog.show(getActivity(), null, null, true, true);
progressDialog.setContentView(R.layout.loading);
MyTask t = new MyTask();
t.execute();
}
});
3.MyTask
private class MyTaskextends AsyncTask<String, Void, String>{
public MyTask(){
}
#Override
protected String doInBackground(String... params) {
RunExecute();
return null;
}
#Override
protected void onPostExecute(String result) {
if (pDialog != null) {
if (pDialog.isShowing())
pDialog.hide();
}
}
#Override
protected void onPreExecute() {
if(IsShowProgress) {
if (pDialog != null)
pDialog.show();
}
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
When MyTask doInBackground the progressdialog not spinning (doInBackground usage time about 5 sec).
But after onPostExecute finish It's start spinning again.
I test it's by ban "pDialog.hide();" in onPostExcute;

ProgressDialog pDialog;
onPreExecure()
pDialog = ProgressDialog.show(MainActivity.this, null, null, true, false);
pDialog.setContentView(R.layout.loading);
onPostExecute()
if(pDialog.isShowing())
{
pDialog.dismiss();
}

Related

AsyncTask sometimes work and sometimes not

Trying to implement AsyncTask for the first time. When I launch the app for the first time, it works and the loading message dialog appears (although the spinner not!), but many other times when I launch the activity, the app freezes for seconds (loading in background) with no apparent ProgressDialog or the called activity which means AsyncTask is not working. Here is my code
private class PrepareFragments extends AsyncTask<Void, Void, ArrayList<Cursor>> {
ProgressDialog pd;
ArrayList<Cursor> cursors;
#Override
protected void onPreExecute() {
Log.d("onPre : ", "true");
pd = new ProgressDialog(CategoryDrugs.this);
pd.show();
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.setMax(100);
}
#Override
protected ArrayList<Cursor> doInBackground(Void ... arg) {
Log.d("doInBG : ", "true");
// my custom code here
}
#Override
protected void onProgressUpdate(Void... values) {
pd.incrementProgressBy(1);
}
#Override
protected void onPostExecute(ArrayList<Cursor> cursor) {
Log.d("onPost : ", "true");
if (pd.isShowing()) {
pd.dismiss();
}
}
}
If your doInBackground executes very fast it may possible that dialog will not display or just blink.
+Call Show at last
pd = new ProgressDialog(CategoryDrugs.this);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.setMax(100);
pd.show();
Try using executor
new PrepareFragments().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

ProgressBar Spinner for Async Task doesn't work

My problem is that when i click button "Click" to call my API it should show my progressBar(spinner) while I'm calling API. Instead my application freeze for less than a second and then when it's done calling it shows my loading spinner for a brief time (it just flash)
Here is my code
private ProgressBar spinner;
public View onCreateView(...)
{
spinner = (ProgressBar) view.findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
...
}
private class MyTask extends AsyncTask<String, Void, Void> {
String pageContent = "";
DataOutputStream wr;
#Override
protected void onPreExecute() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public Void doInBackground(String... params) {
requestResult.setSuccess(false);
HttpURLConnection connection;
try {
String url = "myURL";
//I only call my Api here. I delete rest so this won't bother you
requestResult.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
JsonParser parser = new JsonParser();
//Same here i delete nonimportant
MyResponse = new Gson().fromJson(jsonContent, MyResponse.class);
done();
spinner.setVisibility(View.GONE);
}
}
I've tried hounder different things it always freeze for a second and then my loading spinner flash and my content from API is shown.
Can you help me with that one, please?
My xml file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll_view_send"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/buttonSend"
android:visibility="gone"/>
</RelativeLayout>
</ScrollView>
Try the below snippet. It does not require spinner to be declared in layout file.
AsyncTask<String, String, String> asyncObject =
new AsyncTask<String, String, String>() {
ProgressDialog progDailog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog =
new ProgressDialog(Activity.this);
progDailog.setMessage("Loading");
progDailog.setCancelable(false);
progDailog.show();
}
#Override
protected String doInBackground(String... urls) {
//Do background stuff here
return null;
}
#Override
protected void onPostExecute(String result) {
progDailog.cancel();
//Do post background stuff here.
}
};
asyncObject.execute(null, null, null);
Please try this working sample, pass the spinner to your MyTask like this:
private class MyTask extends AsyncTask<String, Void, Void> {
String pageContent = "";
DataOutputStream wr;
private final ProgressBar progress;
public MyTask(final ProgressBar progress) {
this.progress = progress;
}
#Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
}
...
#Override
protected void onPostExecute(Void result) {
JsonParser parser = new JsonParser();
//Same here i delete nonimportant
MyResponse = new Gson().fromJson(jsonContent, MyResponse.class);
done();
progress.setVisibility(View.GONE);
}
}
Then call new MyTask(progress).execute();
EDIT: In your question you refer that your phone is freezing while calling the MyTask...
Please check this step to avoid freezing your UI in AsyncTask:
Do not call MyTask using new MyTask().get()
Try moving to doInBackground this part MyResponse = new Gson().fromJson(jsonContent, MyResponse.class); done(); this could be expensive.
Hope its helps!!

How to change the ProgressDialog Message font size in android programmatically? [duplicate]

This question already has answers here:
ProgressDialog: change text size
(3 answers)
Closed 5 months ago.
I have used progressDialog in my android application and i have used code as
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Please wait to get contacts");
progressDialog.setProgress(0);
progressDialog.show();
I want to change the message font size and want to add some color to the message is it possible?
private ProgressDialog Dialog = new ProgressDialog(currentfile.this);
Dialog.setMessage(Html.fromHtml("<font color='white' ><big>"
+ "Downloading ..." + "</big></font>"));
Dialog.show();
Make custom progress dialog like below:
custom_progress_dialog.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#null"
>
<TextView
android:id="#+id/animation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string"
android:size="30dp" />
</LinearLayout>
MyCustomProgressDialog.java
public class MyCustomProgressDialog extends ProgressDialog {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_progress_dialog);
...
}
public static MyCustomProgressDialog ctor(Context context) {
MyCustomProgressDialog dialog = new MyCustomProgressDialog(context);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
return dialog;
}
#Override
public void show() {
super.show();
}
#Override
public void dismiss() {
super.dismiss();
}
}
and then use progress dialog class in asynctask like below:
class DemoAsyncTask extends AsyncTask<Void, Void, Void> {
private final MyCustomProgressDialog progressDialog;
public DemoAsyncTask(Context ctx) {
progressDialog = MyCustomProgressDialog.ctor(ctx);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
textView.setVisibility(View.INVISIBLE);
progressDialog.show();
}

Android. ProgressBar doesn't work?

I loading some data from a database and I'd like to display a circle animation during this, because it's take time. The circle appears but only after loadContent() which load data.
The code:
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
ProgressBar p = (ProgressBar) findViewById(R.id.imgProgress);
p.setEnabled(true);
if (settings.getBoolean("my_first_time", true)) {
// the app is being launched for first time, do something
Log.d("Launched:", "first time");
loadContent();
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
p.setEnabled(false);
In XML:
<ProgressBar
android:id="#+id/imgProgress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content" />
Why not just do this ?
public class SomeTask extends AsyncTask<Void, String, Void>{
ProgressDialog dialogue;
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialogue.dismiss();
//If Using some adapter; someadapteradapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
dialogue = new ProgressDialog(ProgressBar.this);
dialogue.setTitle("Loading items..");
dialogue.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//Your task!!
return null;
}
}
What can be more simple than this..:)
I don't know what is loadContent method but I'd suggest you to do an AsyncTask (if it's not the case). You will be able to show/hide your ProgressBar as follows:
// loadContent method
public class loadContent extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// set your progress bar to visible
((ProgressBar) findViewById(R.id.imgProgress)).setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
// do some stuff: load datas from sql, load images.. whatever
// and return a string value for onPostExecute (string = "Loaded"
return string;
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Loaded") {
// the loading is finish, display your datas
// set your progress bar to gone
((ProgressBar) findViewById(R.id.imgProgress)).setVisibility(View.GONE);
}
}
}
Here and here, you will see a good example of an AsyncTask method. Then, you just have to add the visibility attribute to your view as:
<ProgressBar
android:id="#+id/imgProgress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
android:indeterminate="true"
android:visibility="gone" />
Hope this helps.

Updating TextView from Async Task which use custom program dialog

In one of my app, I have a scenario where I need to do some background task. For doing that I am using Async Task. Also I am using custom progress dialog. Below is the layout of the custom progress dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<ProgressBar
android:layout_width="60dp"
android:layout_height="60dp"
android:indeterminateDrawable="#drawable/progressloader"
android:layout_gravity="center"/>
<TextView
android:id="#+id/progressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="18sp"
android:text="Please wait...." />
</LinearLayout>
Everything works fine but when I try to set text to TextView then I am getting java NullPointerException.
AsyncTask code
private class InitialSetup extends AsyncTask<String, Integer, Long> {
ProgressDialog dialog = new ProgressDialog(getParent(),R.style.progressdialog);
#Override
protected void onPreExecute() {
dialog.show();
dialog.setContentView(R.layout.progressbar);
}
#Override
protected Long doInBackground(String... urls) {
// txtView.setText("Testing"); here I am getting the error
fetchDetails();
return 0;
}
#Override
protected void onPostExecute(Long result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
populateUI(getApplicationContext());
}
}
MainActivity
public class SummaryActivity extends Activity {
final TextView txtView = (TextView)findbyid(R.id.progressMessage);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accountsummary);
new InitialSetup().execute("");
}
}
If I understand correctly, your TextView of which you want to set the text can be found in the xml file progressbar.xml (i.e. R.layout.progressbar). This TextView can be obtained once the content view has been set (using setContentView()). In your code you set it before this call is been and the code of mussharapp, he is calling it to early. Namely, he calls it after the setContentView(R.layout.accountsummary) call which does not contain the TextView. Consequently, the variable txtView will be NULL and you will get a NullPointerException.
What you should do is the following:
Set the variable txtView in onPreExecute, after setContentView is called.
Based on Paresh Mayani's explanation: Use the runOnUiThread method.
For the code look down below:
private class InitialSetup extends AsyncTask<String, Integer, Long> {
ProgressDialog dialog = new ProgressDialog(getParent(),R.style.progressdialog);
// The variable is moved here, we only need it here while displaying the
// progress dialog.
TextView txtView;
#Override
protected void onPreExecute() {
dialog.show();
dialog.setContentView(R.layout.progressbar);
// Set the variable txtView here, after setContentView on the dialog
// has been called! use dialog.findViewById().
txtView = dialog.findViewById(R.id.progressMessage);
}
#Override
protected Long doInBackground(String... urls) {
// Already suggested by Paresh Mayani:
// Use the runOnUiThread method.
// See his explanation.
runOnUiThread(new Runnable() {
#Override
public void run() {
txtView.setText("Testing");
}
});
fetchDetails();
return 0;
}
#Override
protected void onPostExecute(Long result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
populateUI(getApplicationContext());
}
}
Yes, because you are trying to set the TextView inside the doInBackground() method, and this is not allowed,
Why not allowed? Because There is a only one Thread running which is UI Main Thread, and it doesn't allowed to update UI from thread process. read more info here: Painless Threading
So there is a solution if you want to set the TextView inside the doInBackground() method, do the UI updating operations inside the runOnUiThread method.
Otherwise, suggestion is to do all the UI display/update related operations inside the onPostExecute() method instead of doInBackground() method of your AsyncTask class.
(TextView)findViewByid(R.id.progressMessage);
should only be executed after the command setContentView().
TextView txtView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accountsummary);
**txtView = (TextView)findbyid(R.id.progressMessage);**
new InitialSetup().execute("");
}
Also you can only change UI elements in the main UI thread. doInBackground() is not in the main UI thread. Make UI changes in onPostExecute
public class InitialSetup extends AsyncTask<String, Integer, Long> {
private Activity activity;
ProgressDialog progressDialog;
public InitialSetup(Activity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Starting task....");
progressDialog.show();
}
#Override
protected Long doInBackground(String... urls) {
// do something
//
return 0;
}
#Override
protected void onPostExecute(Long result) {
progressDialog.dismiss();
//Perform all UI changes here
**textView.setText("Text#2");**
}
}
The explanations are correct: You are not to make UI changes in any thread except the thread which create the UI. But AsyncTask has a method called
onProgressUpdate()
which always will run in the UI Thread. So based on the modifications by dennisg your code should look like this:
private class InitialSetup extends AsyncTask<String, String, Long> {
ProgressDialog dialog = new ProgressDialog(getParent(),R.style.progressdialog);
// The variable is moved here, we only need it here while displaying the
// progress dialog.
TextView txtView;
#Override
protected void onPreExecute() {
dialog.show();
dialog.setContentView(R.layout.progressbar);
// Set the variable txtView here, after setContentView on the dialog
// has been called! use dialog.findViewById().
txtView = dialog.findViewById(R.id.progressMessage);
}
#Override
protected Long doInBackground(String... urls) {
publishProgress("Testing");
fetchDetails();
return 0;
}
#Override
protected void onPostExecute(Long result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
populateUI(getApplicationContext());
}
#Override
protected void onProgressUpdate(String... update) {
if (update.length > 0)
txtView.setText(update[0]);
}
}
Note that the type of the parameter of onProgressUpdate is the second type given in AsyncTask!
Extra: To make your code more robust you should check if the progress dialog still exists before setting the text.

Categories

Resources