display loadingscreen while async task - android

I have this async task that call an web service and parse an xml
#Override
protected void onPreExecute(){
super.onPreExecute();
time = System.currentTimeMillis();
}
protected Boolean doInBackground(Integer... params) {
//code
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
}
while async task is executing I want to display an loading screen,but the loading screen finishes before async task finish if I am doing like this
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
final CallWebService callTarif = new CallWebService(6,sett.getDeviceId());
callTarif.execute();
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
}
}
},callTarif.difftime);

Actually postDelayed is called before completing the AsyncTask.
Just put these code lines
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
in opPostExecute() of AsyncTask.
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
}
And remove Handler new Handler().postDelayed(new Runnable(){

start your loading screen onPreExecute method and kill it onPostExecute method of the async task

No need to use Handler for showing loading when accessing webservice using async task . use onPreExecute() method of AsyncTask to Show loading Screen and finish it inside onPostExecute because this method called when doInBackground execution complete . change code code as :
#Override
protected void onPreExecute() {
// show loading bar here
}
#Override
protected String doInBackground(String... params) {
// do network operation here
return null;
}
#Override
protected void onPostExecute(String result) {
// dismiss loading bar here
}

Related

Asynchronous Task Method Calling is Very Slow in android

I've an Asynchronous task method, that calls background process. when i call this summaryCalc method, preexecute method runs when this method calls but doInBackground method takes more than 20 seconds to start. it takes a long time. is there any other way to improve the speed of calling doInBackground method or any other fastest way to execute thread? Thank you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary_date_select);
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
summaryCalc();
}
});
}
/**
* method to create asynchronous task to realign summary data
*/
public void summaryCalc() {
new AsyncTask<Void, Void, String>() {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(SummaryDateSelectActivity.this);
dialog.setTitle(getResources().getString(R.string.app_name));
dialog.setMessage(getResources().getString(R.string.please_wait));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
ExtraSettingsDS settingsDS = new ExtraSettingsDS(getApplicationContext());
ExtraSettingsDO settingsDO = settingsDS.getExtraSettingsValues();
WeeklySummaryRecovery summaryRecovery = new WeeklySummaryRecovery(getApplicationContext());
/*Insert missing account order data*/
summaryRecovery.insertMissingAccOrderData();
if (settingsDO.getAccManage() == 0) {
summaryRecovery.summaryInsertForSeparateAccManage();
} else {
summaryRecovery.summaryInsertForJoinAccManage();
}
settingsDS.updateWeeklyFinishedDate();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();
intent = new Intent(getApplicationContext(), SummaryDetailsShowActivity.class);
intent.putExtra(KandhaConstants.IE_NEXT_ACTIVITY, accCheck);
intent.putExtra(KandhaConstants.IE_DAY_OF_LINE, currentDay);
intent.putExtra(KandhaConstants.IE_START_DATE, date);
startActivity(intent);
finish();
}
}.execute(null, null, null);
}
It is possible you have a lot of async tasks running. Calling .execute() will execute them one by one. Try calling .executeOnExecutor() instead.
http://developer.android.com/reference/android/os/AsyncTask.html

How to use intent in Asynctask class?

Please share how to use intent in doinbackground() or onpostexecute() methods Asynctask class.When I tried to use these codes it shows error.
Intent intent = new Intent(asynctask.this, home.class);
startActivity(intent);
finish();
private Class<Home> clazz;
public asynctask(Class<Home> clazz){
this.clazz = clazz;
}
Asynctask doInBackground() method:
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, clazz);
startActivity(intent);
finish();
Toast.makeText(cxt, "welcome", Toast.LENGTH_SHORT).show();
return null;
}
Try this way,hope this will help you to solve your problem.
How to asynctask class :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyCustomAsyncTask(this).execute();
}
MyCustomAsyncTask.java
public class MyCustomAsyncTask extends AsyncTask<Void,Void,Void> {
private Context context;
public MyCustomAsyncTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
// write show progress Dialog code here
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// write service code here
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(context, "welcome", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, home.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
Move this Intent part in onPostExecute(...) method of AsynckTask
doInBackground(Void... arg0) should do only background task
you should put other code in onPostExecute(...) method. so that when background task is over move to other activity.
** Don't try to touch UI from doInBackground(....) your app may crash.
You cann't interact with UI in doInBackground(....). you can only interact with UI in onPostExecute(...). Just like thread you cann't interact with UI in Thread for UI we use Handler.
Always put intent in onPostExecute. This will ensure that your UI thread is in sync.
For example if your want to show that on receiving right credentials the user should move to next activity or else should be shown a message "Invalid credentials" in case they're wrong. Your onPostExecute should look like this:
protected void onPostExecute(final Boolean success) {
if(success){
Intent intent = new Intent(<CurrentActivity>.this, <NextActivity>.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}

Show ProgressBar for a certain time in Android

I have to wait some seconds in my Android App and I want to show a progress bar during this time, how can I do this?
I tried for example this code:
public boolean WaitTask() {
pDialog = ProgressDialog.show(context,null, "Lädt..",true);
new Thread() {
public void run() {
try{
// just doing some long operation
sleep(2000);
} catch (Exception e) { }
pDialog.dismiss();
}
}.start();
return true;
}
But the progressbar closes immediately without waiting the two seconds. Where is my problem?
The progressbar should look like the activity circle showing in this site from Android Developers.
UPDATE
The AsyncTask
private class WaitTime extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.show();
}
protected void onPostExecute() {
mDialog.dismiss();
}
#Override
protected void onCancelled() {
mDialog.dismiss();
super.onCancelled();
}
#Override
protected Void doInBackground(Void... params) {
long delayInMillis = 2000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mDialog.dismiss();
}
}, delayInMillis);
return null;
}
}
I call it like this:
mDialog = new ProgressDialog(CreateProject.this);
mDialog = ProgressDialog.show(context,null, "Lädt..",true);
WaitTime wait = new WaitTime();
wait.execute();
I reccomend you to use AsyncTask, then you can do something like this:
AsyncTask<Void, Void, Void> updateTask = new AsyncTask<Void, Void, Void>(){
ProgressDialog dialog = new ProgressDialog(MyActivity.this);
#Override
protected void onPreExecute() {
// what to do before background task
dialog.setTitle("Loading...");
dialog.setMessage("Please wait.");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// do your background operation here
return null;
}
#Override
protected void onPostExecute(Void result) {
// what to do when background task is completed
dialog.dismiss();
};
#Override
protected void onCancelled() {
dialog.dismiss();
super.onCancelled();
}
};
updateTask.execute((Void[])null);
and if you want to wait for some specific time, maybe you would like to use Timer:
final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
dialog.setTitle("Loading...");
dialog.setMessage("Please wait.");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
long delayInMillis = 5000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
dialog.dismiss();
}
}, delayInMillis);
mistake: calling pDialog.dismiss(); should be done from the UI thread instead of called from your new thread.
so your code should change to:
pDialog = ProgressDialog.show(context,null, "Lädt..",true);
new Thread() {
public void run() {
try{
// just doing some long operation
Thread.sleep(2000);
} catch (Exception e) { }
// handle the exception somehow, or do nothing
}
// run code on the UI thread
mYourActivityContext.runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.dismiss();
}
});
}.start();
generally - there are much better approaches performing background tasks (waiting and do nothing for two seconds is also background task) and performing something in the main UI thread when they finished. you can use AsyncTask class for example. it's better use this android built in mechanism, and not "primitive" thread creation, although it will work too - only if you will handle right your application and activity life-cycle. remember there is a chance that in the two seconds you are waiting - the user can navigate away from your application. in that case the dismiss(); method would be call on a destroyed context...
I suggest you read more in - http://developer.android.com/reference/android/os/AsyncTask.html

Progress bar doesn't update

I created a Progress bar but I can't see the loading animation. It's frozen. I want to display a progress bar when I click on the item and then see the bar working and not frozen. Here is my code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (((TextView) view).getText().equals("Zman-New (rus)")){
progDailog = ProgressDialog.show(testLoading.this, "Getting data", "Loading...",true,true);
new GetDataTask("stringurl.xml").execute();
}
Here is the getdata
private class GetDataTask extends AsyncTask<Void, Void, Integer> {
String url;
GetDataTask(String url){
this.url=url;
}
#Override
protected Integer doInBackground(Void... params) {
//do all your backgroundtasks
intent = new Intent(rusNewsP.testLoading.this, rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
return 1;
}
#Override
protected void onPostExecute(Integer result) {
//finish up ( or close the progressbar )
//do something with the result
progDailog.dismiss();
super.onPostExecute(result);
}
}
If you just want to test Progress try this:
private class Initialize extends AsyncTask<Short, Short, Short> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(yourlass.this);
pd.setMessage("test");
pd.show();
super.onPreExecute();
}
#Override
protected Short doInBackground(Short... params) {
try {
synchronized (this) {
wait(2000);
}
} catch (InterruptedException ex) {
}
return null;
}
#Override
protected void onPostExecute(Short result) {
pd.dismiss();
super.onPostExecute(result);
}
}
And don't call startActivity in the doInBackground-Method. Call it in OnPostExecute instead. GUI Operations should not be done in doInBackground.
Try to start the Activity Direct from the UI thread as that will be fast.
Still,if you want this way then try to start it from the onPostExecute Method.
Not from the doInBackground.
protected void onPostExecute(Integer result)
{
//do something with the result
progDailog.dismiss();
intent=new Intent(rusNewsP.testLoading.this,rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
}
And...don't call super.onPostExecute(result); after dismissing the progressDialog..after completing the doInBackground(Short... params),It will return directly to onPostExecute Method where it will dismiss the ProgressDialog first time and then execute the Constructor which will try again to dismiss the ProgressDialog which is already dismissed resulting into uncaught exception.

Android Async task porgress bar doesn't comes until background process is completed

I am building a project in which i use async task to show progress bar.
I am using get() method to wait the main thread so we can do the other task before .
but progress bar is showing after completion of doInBackground thered.
I Want to show the loading bar when the loading starts.
It will dismiss when onPostExecute calls.
public class TempConverterActivity extends Activity {
pojo p;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
try {
new LoadData().execute().get();
} catch (Exception e) {
Log.e("async brix--", e.getMessage());
}
runned();
}
private void runned() {
ArrayList<String> al = p.getData();
for (String str : al){
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(TempConverterActivity.this);
protected void onPreExecute() {
dialog.setMessage("Loading data...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params) {
p = new pojo();
new SoapParser(p);
return null;
}
}}
Please help . Thanks in advance.
You can try following code,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
Edited: In my previous answer I suggested using a Handler; however, AsyncTask eliminates the need to do this which I didn't spot.
Why do you feel the need to call AsyncTask.get()? This is a blocking call, and you call this from the UI thread, thus it is ultimately a race condition as to whether it or onPreExecute() is run first.
I see no reason why you should call get() in this context. You want to call runned() after the AsyncTask completes, but you could do this by launching a new thread from onPostExecute(). Alternatively you could do as you do now, using get(), but call that from a new thread instead of the UI thread.

Categories

Resources