Adding ProgressDialog as Async Task is slowing down the performance - android

This is my code for Login.
public void Login_Click(View view) {
HashMap<String, String> op_Config = XMLParser
.parse(LoginActivity.this);
}
It takes around 4 Sec to finish executing. So I added progress dialog like this.
public void Login_Click(View view) {
new IsLogedIn().execute();
}
class IsLogedIn extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... value) {
try
{
HashMap<String,String> op_Config = XMLParser.parse(LoginActivity.this);
finish();
Intent intent=new Intent(LoginActivity.this,MainMenuActivity.class);
startActivity(intent);
}
catch (Exception e) {
}
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}
}
But now it is taking more than 1 min to finish.

Try doing like this
class IsLogedIn extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... value) {
try
{
HashMap<String,String> op_Config = XMLParser.parse(LoginActivity.this);
}
catch (Exception e) {
}
}
#Override
protected void onPostExecute(String file_url) {
if(dilog.isShowing()){
dismissDialog(progress_bar_type);
}
finish();
startActivity(new Intent(LoginActivity.this,MainMenuActivity.class));
}
}

Related

AsyncTask Thread with Intent

I run loading screen which should show current status "scanning packages, etc" . So that my activity wouldn't freeze I must use thread, but then I can't update status (TextField). I tried using AsyncTask but that didn't helped me at all, still after running I see text field unchanged.
public class LoadingScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadingscreen_layout);
try {
startLoadingScreen();
}catch (Exception e){
Log.e("Scanner","Scanner",e);
}
}
public void startLoadingScreen(){
try{
new Thread(new Runnable() {
#Override
public void run() {
new ScanningOperation().execute("Scanning");
//loadingScreen.setStatus("Scanning");
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
//changeIntent();
//finish();
}
});
} catch (Exception e){
Log.e("Thread","Thread");
}
}
private class ScanningOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return params[0];
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView txt = findViewById(R.id.statusView);
txt.setText(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}

AlertDialog not showing in AsyncTask

I have an activity with a button that starts an AsyncTask:
public void search(View view) {
if (searchTask != null) {
return;
}
searchTask = new SearchTask(this);
searchTask.execute((Void)null);
}
And this is the task:
public class SearchTask extends AsyncTask<Void, Void, Boolean> {
private final Activity activity;
private final ProgressDialog dialog;
public SearchTask(Activity activity) {
this.activity = activity;
this.dialog = new ProgressDialog(activity);
}
#Override
protected Boolean doInBackground(Void... params) {
try {
wait(3000);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPreExecute() {
dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing())
dialog.dismiss();
}
}
I'm not calling get() so I shouldn't be blocking the UI thread. The problem is that the progress dialog is not being shown.
Is this not the correct way to show a dialog within an AsynTask?
wait() causes IllegelMonitorException. to apply a delay in the task Thread.sleep() should be used.
try after removing return; from below code-
public void search(View view) {
if (searchTask != null) {
return;
}
searchTask = new SearchTask(this);
searchTask.execute((Void)null);
}

Android - Progress Dialog crashes when changing message

I'm new to Android and I'm practicing creating a progress dialog. I want to change the message in the dialog every couple of seconds, but my application crashes when I change the message. Any ideas what I may be doing wrong?
private void progressDialogTest(final ArrayList<String> messages)
{
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>()
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Progress Dialog");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
for(int i=0; i<messages.size(); i++)
{
/******** APPLICATION SEEMS TO CRASH AT LINE BELOW ********/
progressDialog.setMessage(messages.get(i));
Thread.sleep(3000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
};
task.execute((Void[])null);
}
Move the code to onProgressUpdate instead, eg:
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
progressDialog.setMessage(messages.get(progress[0]));
}
#Override
protected void doInBackground(Void... arg0) {
/* ... */
//progressDialog.setMessage(messages.get(i)); Change this line to
publishProgress(i);
/* ... */
}

Json Element returns null in AsyncTask

When I call only wpCategories = JsonToElement.getllAllCategory(); in the buttons onClick methood it works fine. (wpCategories get filled with data). But when I put this in a asynctask, wpCategories returns null. (is the doInBackground not being called?)
Here is my buttons on click methood:
public void onImageGridClick(View view) {
new GetJsonElementTask().execute();
Intent intent = new Intent(this, CategoryGridActivity.class);
intent.putParcelableArrayListExtra(Extra.IMAGES, wpCategories);
startActivity(intent);
}
And the asyncTask:
private class GetJsonElementTask extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(HomeActivity.this, "",
"Loading...");
}
#Override
protected String doInBackground(Void... arg0) {
wpCategories = JsonToElement.getllAllCategory();
return null;
}
#Override
protected void onPostExecute(String value) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("DEBUG_LOG", "In onProgressUpdate");
}
}
Start your Activity inside onPostExecute because this method execute after doInBackground execution complete :
#Override
protected String doInBackground(Void... arg0) {
wpCategories = JsonToElement.getllAllCategory();
return wpCategories; //<<< return value from here
}
#Override
protected void onPostExecute(String value) {
progressDialog.dismiss();
Intent intent = new Intent(this, CategoryGridActivity.class);
intent.putParcelableArrayListExtra(Extra.IMAGES, value);
startActivity(intent);
}
Try following
public void onImageGridClick(View view) {
new GetJsonElementTask().execute();
}
public void startCategoryGridActivity(){
Intent intent = new Intent(this, CategoryGridActivity.class);
intent.putParcelableArrayListExtra(Extra.IMAGES, wpCategories);
startActivity(intent);
}
And the asyncTask:
private class GetJsonElementTask extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(HomeActivity.this, "",
"Loading...");
}
#Override
protected String doInBackground(Void... arg0) {
wpCategories = JsonToElement.getllAllCategory();
return null;
}
#Override
protected void onPostExecute(String value) {
progressDialog.dismiss();
startCategoryGridActivity();
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("DEBUG_LOG", "In onProgressUpdate");
}
}

Android splash screen and server communication

I am developing an application in android, where i need to display a splash screen and at the same time there will be server communication. The problem here is when i launch the app, first application is communicating with the server and then it is displaying the splash screen. I want to both server communication and splash screen at the same time.
The following is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
Thread thread = new Thread(this);
thread.start();
thread.join();
//Attractions
CommonMethods.getSystemOutput("Response Json Array String Attractions:::"+jArrayMobileAttractions);
attractionsDate = JsonParsing.getLatestDate(jArrayMobileAttractions);
attractionsDate = getDate(attractionsDate);
CommonMethods.getSystemOutput("Attractions Date:::::"+attractionsDate);
//Categories
CommonMethods.getSystemOutput("Response Json Array String Categories:::"+jArrayCategories);
categoryDate = JsonParsing.getLatestDate(jArrayCategories);
categoryDate = getDate(categoryDate);
CommonMethods.getSystemOutput("Category date:::"+categoryDate);
//Contacts
CommonMethods.getSystemOutput("Response Json Array String Contacts:::"+jArrayContacts);
contactsDate = JsonParsing.getLatestDate(jArrayContacts);
contactsDate = getDate(contactsDate);
CommonMethods.getSystemOutput("Contacts Date:::"+contactsDate);
} catch (Exception e) {
CommonMethods.getSystemOutput("Exception in Splash screen thread:::"+e);
}
}
public void run() {
// if (attractionsDate == null) {
jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL);
jArrayCategories = RequestHandler.getJSONfromURL(Constants.CATEGORY_URL);
jArrayContacts = RequestHandler.getJSONfromURL(Constants.CONTACTS_URL);
// } else {
// jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL+"?lastupdateddate="+attractionsDate);
// }
}
You can use the AsynchTask Manager in which it has a method
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Do Server Interaction Here
return response;
}
#Override
protected void onPreExecute(String result) {
//Show your Splash Screen
}
#Override
protected void onPostExecute(String result) {
//Gone the Splash Screen view
}
}
For this purpose it will be better start from "SplashActivity" - in onCreate() start new Thread for communication with server, and when all communication finished - call startActivityForResult(mainActivityIntent). For correct behavior back button finish splash activity on finish main activity. Approximate code:
public class SplashActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setup view for activity
new Thread(new Runnable() {
public void run() {
// do here some long operation
startActivityForResult(new Intent(SplashActivity.this, MainActivity.class), 0);
}
}).start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
finish();
}
}
I had the same thing to do and I did it this way and it works just fine. I had to show the splashscreen and download some file from the server, unzip it, move files insto proper directories and then start the apps main screen. Here is the code, I used AsyncTask.
So, you have three AsyncTask classes, one for each task and in the onPostExecute() I call the next AsyncTask. I can't say if this is the best way but it works for me.
I removed unneccessary code but for clarity I left a call to a dialog where I ask a user ih he wants to proceed with downloading as it may take a while. Also I check if FIRST_RUN is true just so I know if I should download the package since for my app I need to do it only the first time, so if it is true I do the spashscreen activities and if it is false I proceed to MAINAPP activity.
Hope it helps.
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
boolean firstRun = settings.getBoolean("FIRST_RUN", true);
if (firstRun) {
showDialog(INITIAL_DLG);
} else {
startActivity(new Intent(appContext, MAINAPP.class));
}
}
/***
* First entry after YES on Dialog!
*/
protected void initialize() {
messageTV.setVisibility(TextView.VISIBLE);
progressBar.setVisibility(ProgressBar.VISIBLE);
downloadThread = new DownloadFiles();
downloadThread.execute();
}
protected void rollback() {
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
switch (id) {
case INITIAL_DLG:
builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.app_setup)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
initialize();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDlg = builder.create();
return alertDlg;
default:
return null;
}
}
protected class DownloadFiles extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//file download
} catch (Exception e) {
result = false;
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
unzipThread = new DecompressZipFile();
unzipThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 1/4:Downloading data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class DecompressZipFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//unzip files
return true;
} catch(Exception e) {
return false;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0]<0) progressBar.setMax(values[0]*-1);
else progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
moveDBThread = new MoveDBFile();
moveDBThread.execute();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
messageTV.setText("Step 2/4:Decompressing data...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
}
protected class MoveDBFile extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
//moving files
return true;
} catch (Exception e) {
globalE = e;
finish();
return false;
}
}
#Override
protected void onPreExecute() {
messageTV.setText("Step 3/4:Shufflin'...");
progressBar.setProgress(0);
progressBar.setMax(100);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
getSharedPreferences(PREFS_NAME,0).edit().putBoolean("FIRST_RUN", false).commit();
startActivity(new Intent(appContext, MAINAPP.class));
} else {
rollback();
}
}
}
}

Categories

Resources