I want to update the UI with some information of data during a particular interval, so can anyone help me out to do so using AsyncTask?
use onProgressUpdate() method of AsyncTask. It is performed on UI thread.
Try Asynctask as shown here:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code of UI operation
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}
Also refer to this link:
Fetch data from server and refresh UI when data is fetched?
Related
I am using a progress spinner on pre execute method of Async task to show it on UI and the data starts fetching in the background from Api using volley library.The problem is when it starts fetching the data,the loader stops spinning and its like the UI is not responding.
need help,Thanks in advance..
`
ProgressDialog dialog;
public void open() {
dialog = new ProgressDialog(BuzoongaContacts.this);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
dialog.setContentView(R.layout.progress_layout);
dialog.setCanceledOnTouchOutside(false);
}
public void stopLoading() {
Log.d("res", "stopLoading ");
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}`
Async Task:
class BuzoongaContactsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread( new Runnable() {
public void run() {
open();
}
});
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ContactsDataTableOperations conDataTab = new ContactsDataTableOperations(BuzoongaContacts.this);
conDataTab.open();
JSONParsingForContactsB.count = 0;
count = 0;
if (fromRefresh)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !",getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else
{
if (getContactsExistence() == 0) {
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else if (Constants.buzoongaContactsAdded)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else {
stopLoading();
}
}
arr_list = conDataTab.getAllRecords();
conDataTab.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
cb_select_all.setChecked(false);
iv_quick_launch.setBackgroundResource(R.drawable.quick_lounch_icon_disable);
Constants.selected_buzoonga_contacts = 0;
rl_delete.setAlpha(0.5f);
rl_delete.setClickable(false);
rl_show_contacts.setVisibility(View.INVISIBLE);
mAdapter.notifyDataSetChanged();
}
}
Basically, you can't touch your UI elements in background threads, which means that all your calls to startAnimation() or stopLoading should be wrapped with runOnUiThread.
But I can see your UI code is so bound up with your background code. Maybe you could consider using Thread & Handler instead of AsyncTask.
I am showing some animation and making network request at the same time. Both are working fine independently. But when I try to place a progress dialog in asynctask the animation is not started until progress dialog until the onPostExecute(). My guess is that as the animation and progressdialog both run on the UI thread so only one can run at a time. Is there a way to show progress dialog and run animation at the same time both on the UI thread?
Here's my code:
public class DailyTarrotActivity extends FragmentActivity {
ImageView imageViewAnimation;
AnimationDrawable spinAnimation;
AnimatorSet set = new AnimatorSet();
FlipImageView imageViewCard;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_tarrot);
imageViewAnimation = (ImageView) findViewById(R.id.imageViewAnimation);
imageViewAnimation.setBackgroundResource(R.drawable.spin_animation);
imageViewCard = (FlipImageView) findViewById(R.id.imageViewCard);
spinAnimation = (AnimationDrawable) imageViewAnimation.getBackground();
new DailyTarrotAsyncTask().execute();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
Log.d("start", "focuschange");
if (hasFocus) {
spinAnimation.start();
}
}
public class DailyTarrotAsyncTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(DailyTarrotActivity.this);
pd.setCancelable(false);
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Thread thread = new Thread();
try {//just to mimic downloading behaviour
thread.sleep(10000);//animation starts only after 10 secs
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
Toast.makeText(DailyTarrotActivity.this, "async task finished",
Toast.LENGTH_SHORT).show();
}
}
}
I am trying to make a simple AsynTask sample. I can't make it run. When I click the Button, ProgressDialog is supposed to be displayed. But nothing happens. I don't get any Exceptions. Probably I'm missing out a few things.
ProgressDialog dialog=null;
Button btnstart;
MyAsynTask mytask;
static final int SLEEP_TIME=(15*1000)/100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=(Button)findViewById(R.id.button1);
btnstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mytask=new MyAsynTask();
mytask.execute();
}
});
}
public class MyAsynTask extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
if(isCancelled()){
break;
}
else {
publishProgress(i);
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
You are doing it right.
Use Logs in onPreExecute(),doInBackBackground() to see what's happening actually.
Add one more method to Asynctask class
onPostExcute()
{
dialog.dismiss();
}
OnPost method in the asynctask excutes after doinbackgournd method there you need to dismiss the dialog
I want to use progress bar while downloading from server,Actually i was using progressDialog but it will be good look if i use progressBar instead of progressDialog.I have following code for Progress dialog .
public class FeaturedData extends AsyncTask<Void, Void, Void> {
Home home;
ProgressDialog dialog = null;
public FeaturedData(Home home) {
// TODO Auto-generated constructor stub
this.home = home;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//calling here method
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(home, "", "", true);
}
As per your below comment:
Actually i want to do it programatically don't want to declare in xml.
=> i would suggest you to take it inside the XMl layout.
Inside the onPreExecute(), make it visible using progressBar.setVisibility(View.VISIBLE)
and inside the onPostExecute(), make it GONE by using progressBar.setVisibility(View.GONE)
As I created a Progress bar using below code in a on click method of button. but after clicking button it takes 2-3 seconds to display progress bar.how to reduce that delay to start progress bar.
public void getProgressBar() {
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
progressBarStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = doSomeTasks();////I am loading service
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100 ) {
progressBar.dismiss();
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
}
}).start();
}
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myProgress = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
Use an AsyncTask instead. The example code in the link gives a good introduction on how to do it. In essence you do the job in doInBackground(), publish your progress using onProgressUpdate() and start your activiy in onPostExecute().