ProgressDialog won't show, even in onPreExecute of AsyncTask - android

In my class, Main extends Activity, I've this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ...
case CREDENTIAL_VIEW:
new SetStatusProgressBar(this).execute();
And there is this nested class:
private class SetStatusProgressBar extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Main ctx;
public SetStatusProgressBar(Main ctx) {
this.ctx = ctx;
dialog = new ProgressDialog(ctx);
}
// progress dialog to show user that contacting server.
protected void onPreExecute() {
this.dialog = ProgressDialog.show(ctx, null,
"Refreshing data from server...", true, false);
}
#Override
protected void onPostExecute(final Boolean success) {
//...
//statements that refresh UI
//...
if (dialog.isShowing()) {
dialog.dismiss();
timerProgressBarStop();
}
}
protected Boolean doInBackground(final String... args) {
//...
//statements to download data from server
//...
return true;
}
}
In the Main class I open a second Activity, in this way:
Intent myIntent = new Intent(Main.this, Credentials.class);
startActivityForResult(myIntent, CREDENTIAL_VIEW);
That second Activity returns to the Main activity in this way:
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
I don't understand why when I navigate from the second Activity to the Main, the ProgressDialog will show ONLY AFTER that the UI refreshes... In this way the Progress Dialog stays on the screen only for half second... and then hides! :( I'd like to see the ProgressDialog on top during all the download time!
Help, please.
Thank you all

Ok, first of all use getApplicationContext() instead of ctx variable. Using 'this' is not for good memory citizens.
Try updating progressDialog in onProgressUpdate(...) method.

Related

Progress dialog inside async task not working

The progress dialog does not show up when the file is downloading in background. After uploading the file to the database the activity remains as it is as if nothing is happening! A progress dialog is necessary while the file is uploading.
public class MainActivity extends AppCompatActivity {
ProgressDialog pd;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICKFILE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
pd=new ProgressDialog(this);
Common common=new Common();
MyTask myTask=common.new MyTask(pd);
myTask.execute();
}
}
Asynctask:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
public MyTask(ProgressDialog pd) {
this.pd = pd;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Uploading . . .");
pd.show();
pd.setCancelable(false);
}
#Override
protected Void doInBackground(Void... voids) {
//download file
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.dismiss();
}
}
I searched all the answer of stack overflow but nothing helped me! Any help is appreciated.
Progress Dialog is deprecated anyway, may be you can use progress bar in your xml with visibility:gone, and when you are about to start download change its visilbility to visible and when it is finished set again it go gone

How to post http after oncreate complete?

I have a MainActivity that has onCreate method in it. In that class, it should load the layout and post data to server. As long as the activity started, it becomes blank and only go to the next activity SignUpActivity. what I need is the MainActivity layout will show first and then execute the httpPost.
Here are my code
public class MainActivity extends Activity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
context = this;
new MainAsyncTask().execute(""); // where should i put this code? here??
}
private class MainAsyncTask extends AsyncTask<Object, Integer, String> {
#Override
protected String doInBackground(Object... params) {
String result = null;
String url = "some url";
Log.i("Post", "Post HTTP");
HttpPostHelper.postData(url); // method to post the http. i made myself
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
return result;
}
}
}
i just want that the MainAsyncTask.execute("") is executed after the layout is fully shown on the device.
SOLVED
I move the new MainAsyncTask().execute(""); and add it here, and it works fine:
#Override
protected void onStart() {
super.onStart();
new MainAsyncTask().execute("");
}
Try in onStart() method of activity
calling on AsynTask seems ok but you shouldn't call your intent in doInBackground()
call it in onPostExecute() method
protected void onPostExecute(String result){
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
}
You can try a Thread.sleep before startActivity to give the main layout some time to load and show. You should also call the startActivity in onPostExecute.
as per your code it should be like this. Take care of # doinbackground() as here it is not correct.
public class MainActivity extends Activity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
context = this;
new MainAsyncTask().execute(""); // where should i put this code? here??
}
private class MainAsyncTask extends AsyncTask<Object, Integer, String> {
protected void onPreExecute( ){
//start Progressbar
progressBar.show();
}
#Override
protected String doInBackground(Object... params) {
String result = null;
String url = "some url";
Log.i("Post", "Post HTTP");
HttpPostHelper.postData(url); // method to post the http. i made myself
return result;
}
protected void onPostExecute(String result){
//stuff u want in main thread
progressBar.cancell();
intent = new Intent(context, SignUpActivity.class);
startActivity(intent);
}
}
}

How to start another activity after all views shown

I have a stub activity with progress bar and two labels, and another activity, that may do heavy task (initialize sqlite db from xml resources at first start).
I need start second activity after progress bar and labels are shown.
I'm trying
stubLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (progress.getHeight() <= 0 || progress.getWidth() <= 0) return;
if (label1.getHeight() <= 0 || label1.getWidth() <= 0) return;
if (label2.getHeight() <= 0 || label2.getWidth() <= 0) return;
stubLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SongListActivity.class);
startActivity(intent);
}
});
But I see empty screen while heavy activity is starting.
What am I doing wrong?
I've already found solution myself.
I've found that system create db not on get instance of db helper, but on first query.
The solution is to init db in AsyncTask and start the second activity on post execute:
AsyncTask<Void, Void, Void> initDbTask = new AsyncTask<Void, Void, Void>(){
SongDBHelper helper;
String[] artists;
#Override
protected Void doInBackground(Void... params) {
helper = SongDBHelper.getInstance(getApplicationContext(), getResources());
artists = helper.getArtistList();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SongListActivity.class);
startActivity(intent);
}
};
initDbTask.execute(null, null, null);
I may call your activity with progress bar SplashActivity that shows on start up. In this activity you should do your heavy task (sql initialize) in an AsyncTask. When the AsyncTask is done, just call your other activity to show.
Some stuff of code:
SplashActivity
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_activity);
new AsyncTask<Params, Progress, Result>(){
#Override
protected Param doInBackground(Params... params) {
// DO YOUR SQL STUFF HERE
return null;
}
#Override
protected void onPostExecute(Param aParam) {
super.onPostExecute(aVoid);
// DO YOUR NEXT STEP HERE AFTER SQL TASK DONE
}
}.execute(..some parameters..);
}
Try the following:
#Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus ){
// start your new activity
}
}
This method is called when window receives focus and this is after all the views are shown.

Activity not starting

I can get the progress dialog to stop, but the TabbedView activity never starts, just goes to a black screen. Any ideas?
class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(MainScreen.this);
#Override
protected void onPreExecute() {
dialog.setMessage("Gathering data for\n"+selectedSportName+".\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
updateMaps();
return response;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
startTabbedViewActivity();
}
}
private void startTabbedViewActivity(){
Intent intent = new Intent(this, TabbedView.class);
intent.putExtra(SPORT_NAME_EXTRA, selectedSportName);
intent.putExtra(HEADLINES_FOR_SPORT_EXTRA, existingSportHeadlines.get(selectedSportName));
intent.putExtra(SCORES_FOR_SPORT_EXTRA, existingSportScores.get(selectedSportName));
intent.putExtra(SCHEDULE_FOR_SPORT_EXTRA, existingSportSchedule.get(selectedSportName));
startActivity(intent);
}
I have looked over the Manifest file, and I'm not seeing anything weird looking. Can't figure this one out.
Is the layout of the activity orientated correctly
android:orientation="vertical"
You forgot to add #Override above 'onPostExecute' method so it is not executed at all.

Asynk task android

I have a tabgroup having multiple activities. In one of the tabs i have two activities between whom i want to place a progress dialog.For this i am using Asynk Task. Following is my AsynkTask class which i have made an inner class for AboutUs activity:
private class TheTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
progDialog = ProgressDialog.show(AboutUs.this.getParent(), "Loading... ",
"please wait....", true);
}
#Override
protected Void doInBackground(Void... params) {
final Intent aboutusIntent = new Intent(getParent(), Departments.class);
final TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("Departments", aboutusIntent);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(progDialog.isShowing())
{
progDialog.dismiss();
}
}
}
I am calling this class in my AboutUs activity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutus);
.
.
.
.
/* Button for going to Departments */
Button ourdepbtn = (Button) findViewById(R.id.departmentsbutton);
ourdepbtn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
//ourDepartments();
new TheTask().execute();
return false;
}
});
}
However this does'nt start a new activity i.e. Departments. The progress dialog appears and then disappears but activity never loads.
Any suggestions..??
First, you cannot start an activity from a non GUI thread (which Async doInBackground() is). Just start directly inside your Button.onClick() (why you use onTouch?) listener.
If you want to show up a ProgressDialog for the new Activity as soon as possible, you need to create it in the new (child) Activity onCreate(), as your ProgressDialog is connected to the new (child) activity (is it?). Take care about the order of creating layouts (create the ProgressDialog after calling setContentView()).
I am not very sure why you want to show that ProgressDialog. Is there something which delays the display of the childActivity? You loading some data? Then, the Dialog should be related to that loading task (Async I guess).
private class TheTask extends AsyncTask{
Context con;
Intent aboutusIntent;
TabGroupActivity parentActivity;
private TheTask(Context context)
{
this.con=context;
}
#Override
protected void onPreExecute() {
progDialog = ProgressDialog.show(con, "Loading... ",
"please wait....", true);
}
#Override
protected Void doInBackground(Void... params) {
aboutusIntent = new Intent(con, Departments.class);
parentActivity = (TabGroupActivity)getParent();
return null;
}
#Override
protected void onPostExecute(Void result) {
if(progDialog.isShowing())
{
progDialog.dismiss();
}
parentActivity.startChildActivity("Departments", aboutusIntent);
}
}
Thanks for your suggestions Oliver :)

Categories

Resources