Asynchronous Task Method Calling is Very Slow in android - 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

Related

Android: Progress Dialog with AsyncTask

Since the game requires TTS, and need quite a long time to load, I would like to implement Progress Dialog (PD), as either in the following ways:
Implement AsyncTask in Game Index Page:
This will show the PD, but the PD is freezed, i.e. the looping circle inside the PD is not looping.
buttonC.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
new initialize_game().execute();
}
});
private class initialize_game extends AsyncTask<String,Integer,String>
{
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(Index_game.this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading!\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
buttonC.setBackgroundColor(getResources().getColor(R.color.tran_black));
Intent intent = new Intent(Index_game.this, Game_star_intro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivityForResult(intent, 0);
overridePendingTransition(0, 0); // 0 for no animation
Index_game.this.finish();
return "Done!";
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
Log.i("result","" +result);
if(result!=null)
{
dialog.dismiss();
}
}
}
AsyncTask for TTS:
Once clicked from the Game Index Page, no PD is shown until the Game is loaded fully, and at that time then the PD pops up and off for a millisecond, i.e. even worse than that above.
private class MainFrameTask extends AsyncTask<String,Integer,String> implements OnInitListener, OnUtteranceCompletedListener
{
private Index_game_card_intro mainFrame = null;
public MainFrameTask(Index_game_card_intro mainFrame)
{
this.mainFrame = mainFrame;
}
#Override
protected void onCancelled()
{
stopProgressDialog();
super.onCancelled();
}
#Override
protected void onPreExecute()
{
startProgressDialog();
}
#Override
protected String doInBackground(String... params)
{
// setup TTS part 1.1
mTts = new TextToSpeech(Index_game_card_intro.this, this); // TextToSpeech.OnInitListener
return "Done!";
}
protected void onPostExecute(String result)
{
stopProgressDialog();
}
// setup TTS part 2
#Override
public void onUtteranceCompleted(String utteranceId)
{
Log.v(TAG, "Get completed message for the utteranceId " + utteranceId);
lastUtterance = Integer.parseInt(utteranceId);
}
// setup TTS part 3
#Override
public void onInit(int status)
{
if(status == TextToSpeech.SUCCESS)
{
int result = mTts.setLanguage(Locale.US); // <====== set speech location
mTts.setSpeechRate((float) 0.8);
mTts.setPitch(1.0f);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
{
// button_header.setEnabled(false);
}
else
{
// button_header.setEnabled(true);
mTts.setOnUtteranceCompletedListener(this);
}
}
}
}
// setup TTS part 4
private void speakText()
{
lastUtterance++;
if(lastUtterance >= loveArray.length)
{
lastUtterance = 0;
}
Log.v(TAG, "the begin utterance is " + lastUtterance);
for(int i = lastUtterance; i < loveArray.length; i++)
{
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, String.valueOf(i));
mTts.speak(loveArray[i], TextToSpeech.QUEUE_ADD, params);
mTts.playSilence(ttsilience, TextToSpeech.QUEUE_ADD, null);
}
}
Question:
I found that the Progress Dialog does not show out when Button C in the game index is pressed. However, when the Game_star_intro is finally loaded, the progress dialog pops up for a very very short time and then gone.
I would like to show the ProgressDialog when it is loading up the game, not after the game is loaded then the dialog pops for a millisecond.
In this way, I have also tried to put the load TTS in AsyncTask inside Game_star_intro, yet the result is the same: the dialog just pops up for a millisecond.
Actually how should the AsyncTask be coded?? I have followed some website like this http://karanbalkar.com/2012/10/tutorial-5-custom-progressdialog-with-asynctask/
Thanks for your time!
You shouldn't start your activity in background thread. Start it, for example, in your onClick() method. You should put only your expensive code in doInBackground(), separating it from the framework lifecycle stuff. I guess you should implement AsyncTask inside Game_star_intro class for this.
ProgressDialog is not showing probably because UI thread is freezed until the work is done.
Also, naming conventions in Java suggest name classes without underscores, i.e. GameStarIntro :)
If I understood correctly from your question, loading of the Game_star_intro activity takes a lot of time because you use TTS in creation of this activity. The code you use is wrong. ProgressDialog from Index_game won't be shown when another activity is running (or is being created). You should use AsyncTask in Game_star_intro activity and use TTS there. In Index_game just start Game_star_intro:
buttonC.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(Index_game.this, Game_star_intro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivityForResult(intent, 0);
}
});
And in Game_star_intro something like this
public void onCreate() {
...
new TTLTask().execute();
}
private class TTLTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(Index_game.this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading!\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
//... TTS code
return null;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
Log.i("result","" +result);
if(dialog.isShown())
{
dialog.dismiss();
}
}
}

display loadingscreen while async task

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
}

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

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.

How to display progressbar in android while loading the data from remote database?

How to display progressbar i'm calling intent from class A to class B.
In which class B lloads the data from the using parsing mean while
this happens i'm getting blank screen in this time i'd like to show
progressbar how can i do that.
Right now i'm writing the code as follows..
class A extends Activity{
oncreate(){
...
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new performBackgroundtask().execute();
}
}
class performBackgroundtask extends AsyncTask<Void, Void, Void> {
//
ProgressDialog progressDialog = new ProgressDialog(Main.this);
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Main.this,"", "Please wait...");
super.onPreExecute();
/*
* progressDialog.setMessage("Please wait while loading ...");
* progressDialog.show(); progressDialog.setCancelable(true);
*/
}
#Override
protected Void doInBackground(Void... params) {
Intent in = new Intent(A.this, B.class);
startActivity(in);
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
}
class B { ...
/*
* In which this class has another view which has to get the data from
* URL using SAXPArsing.
*
* ... for this where i need to write progress bar code.
*/
}
I've done something similar using a handler. When the handler recieves it's response from a thread, you can dismiss your progressdialog.
Some code to help you understand:
final Handler handler = new Handler()
{
#Override
public void handleMessage( Message message )
{
progressBar.setVisibility( View.GONE );
// My irrelevant code here
}
};
new Thread( new Runnable()
{
public void run()
{
// Do your stuff here
Message message = handler.obtainMessage( 1, text );
handler.sendMessage( message );
}
}).start();
Instead of calling another Activity class to do your downloading, move this functionality into another class that each Activity can use.

Categories

Resources