How do you show a loading screen while creating database? - android

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadData();
setContentView(R.layout.preload);
Thread thread = new Thread()
{
#Override
public void run() {
setUpDB();
setContentView(R.layout.main);
}
};
thread.start();
}
So I want it to show the preload view while the database is setting up (setUpDB) and then switch to the main view when the setup is complete change to the main view. I had it almost working; showing the loader until about 80% and then crashing, but now I can't even get it to show the loader... if I have setUpDB() in the thread it crashes, if I have it outside the thread it shows a blank screen until fully loaded. I can't remember the code I had before... any ideas?

Try this using assynctask..
private class LoadAssync extends AsyncTask<String, Void, Void> { // Assync task
protected void onPreExecute() {
ProgressDialog dialog=ProgressDialog.show(this,"","Loading");
}
protected Void doInBackground(final String... args) {
setUpDB();
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
to execute assynctask
LoadAssync mAsyync1;
mAsyync1 = new LoadAssync();
mAsyync1.execute(null);

Declare a Handler and call it to update your UI like this,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressDialog pd=ProgressDialog.show(this,"","Please Wait...");
Handler handler =new Handler()
{
public void handleMessage(Message msg)
{
if(msg.what==0)
{
pd.dismiss();
setContentView(R.layout.main);
}
}
};
Thread thread = new Thread()
{
#Override
public void run() {
loadData();
setUpDB();
handler.sendEmptyMEssage(0);
}
};
thread.start();
}

setUpDB();
splashHandler.sendEmptyMessageDelayed(STOP_SPLASH, STOP_SPLASH_DELAY);
private Handler splashHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case STOP_SPLASH:
progressbar.dismiss();
startActivity(new Intent(getApplicationContext(),
HomeScreenActivity.class));
finish();
break;
}
};
};

Related

Android ProgressDialog doesn't show in onCreate using Thread

I want to load some contacts when an activity is created. Because this is a long running operation I want to notify the user through a ProgressDialog. A request for this app is to not use AsyncTasks so I'm using threads but the progress is not showing. This is my onCreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
handler = new Handler();
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
progress = new ProgressDialog(this);
progress.setMessage("Loading Contacts ");
progress.setIndeterminate(true);
progress.show();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
contacts = ContactsUtils.getContacts(getContentResolver());
handler.post(new Runnable() {
public void run() {
progress.dismiss();
// UpdateDisplay();
};
});
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
Log.e("Interrupted Exception:", e.getLocalizedMessage());
}
// other methods
}
Am I missing something? Thanks
SOLVED: The rest of the code from onCreate, after the join, should be moved to a Handler, and join should be removed
You are missig
progress.show()
plus why you are using threads don't you think async tasks will do this task with beauty?
The issue you don't see your progress dialog is because
try {
t.join();
} catch (InterruptedException e) {
Log.e("Interrupted Exception:", e.getLocalizedMessage());
}
this hold main thread till your task is done, just comment it
Try This Code:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launching);
final ProgressDialog myPd_ring=ProgressDialog.show(Launching.this, "", "Loading please wait..", true);
myPd_ring.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Thread.sleep(2000);
}catch(Exception e){}
Intent intt=new Intent();
intt.setClass(Launching.this, MainController.class);
startActivity(intt);
finish();
myPd_ring.dismiss();
}
}).start();
}
Whenever you're trying to do something with the UI from a background thread, either use a Handler or call it within runOnUiThread(Runnable())
try something like this:
private ProgressDialog pDialog; // global
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
color_list = (ListView) this.findViewById(R.id.color_list);
imageView1 = (ImageView)findViewById(R.id.icon);
pDialog = new ProgressDialog(Launcher.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showProgressDialog();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
contacts = ContactsUtils.getContacts(getContentResolver());
handler.post(new Runnable() {
public void run() {
hideProgressDialog();
};
});
}
});
}
private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}

Show progressDialog in Android

I want to show a progressDialog on my page when the user clicks on the button.On click of button i am sorting my results that is a List.Now how can we show a progressDialog on click of a button.Please suggest me
This function i am using to sort that data :
public void sortByDate(View v) {
Collections.sort(tripParseData.getDetails());
setData(tripParseData);
}
After #Monica Suggestion
public void sortByDate(View v) {
new LoadData().execute();
}
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Collections.sort(tripParseData.getCoroprateBookingDetails());
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setApprovalDetailsData(tripParseData);
}
}
you have to call progressdiolog.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.
here you can see an example:
the progressdialog is created and displayed and a thread is called to run a heavy calculation:
Override
public void onClick(View v) {
pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
Search search = new Search( ... );
SearchThread searchThread = new SearchThread(search);
searchThread.start();
}
and here the thread:
private class SearchThread extends Thread {
private Search search;
public SearchThread(Search search) {
this.search = search;
}
#Override
public void run() {
search.search();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
displaySearchResults(search);
pd.dismiss();
}
};
}
Don't forget to vote me up :)
Paste This Class in ur activity and call new LoadData().execute to start the prgress dialog :
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pg=new ProgressDialog(ChartsActivity.this);
pg=pg.show(ChartsActivity.this, "Loding", "Plz Wait...");
}
#Override
protected Void doInBackground(Void... params) {
sortByDate();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pg.dismiss();
}
}
I have not tested it but I think it can help you.
Declare these two objects in your class and member variables.
Thread thread = null;
ProgressDialog bar = null;
Use this logic on your button click listener it can work in your case. I have not tested it but It will give you Idea how things should work. you can also use handlemessage in place of runonuithread
if (thread == null
|| (thread != null && !thread.isAlive())) {
thread = new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//DISPLAY YOUR PROGRESS BAR HERE.
bar = ProgressDialog.show(getApplicationContext(), "LOADING..", "PLEASE WAIT..");
}
});
// SORT COLLECTION HERE
runOnUiThread(new Runnable() {
#Override
public void run() {
//CLOSE YOUR PROGRESS BAR HERE.
bar.dismiss();
}
});
}
});
thread.start();
}
Hope this will help you.
try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Sample code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show UI
//Start your progress bar
showProgress();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your sorting process
return null;
}
#Override
protected void onPostExecute(Void result) {
//Show UI
//dismiss your progress bar
hideProgress();
}
};
task.execute((Void[])null);
Show and hide progress code
public void showProgress() {
progressDialog = ProgressDialog.show(this, "",
"Loading. Please wait...");
progressDialog.setCancelable(false);
}
public void hideProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

How to execute an instruction/method immediately after ProgressDialog dismisses?

I am trying to execute the method doSomeWork(); after the ProgressDialog dismisses in my method printing();which seems to be overlapped by the other method and the dialog is not showed up. If I comment method doSomeWork(); the dialog is displayed correctly until the thread is finished.
Here is my method printing();
public void printing()
{
final ProgressDialog printingDialog = ProgressDialog.show(this, "Printing...", "Please wait", true, false);
new Thread(new Runnable() {
#Override
public void run()
{
//something big executing here
}
}).start();
}
He is my method doSomework():
public void doSomeWork(){
Thread receiptPrint = new Thread(new Runnable() {
#Override
public void run() {
//something here
runOnUiThread(new Runnable() {
#Override
public void run() {
//another dialog here
}
});
}
});
}
Here you can see the how I am calling those two methods:
private OnClickListener onClickPrint = new OnClickListener() {
public void onClick(final View v) {
Log.d("Button","Clicked on Print Order Button");
printing();
doSomeWork();
Does anyone know how could I execute doSomeWork() only when printing(); will be completely finished?
This is one of the purposes of an AsyncTask. It would look similar to this:
public void onClick(final View v) {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show your progress dialog in here
super.onPreExecute();
}
#Override
protected Void doInBackground( Void... params ) {
printing();
return null;
}
#Override
protected void onPostExecute( Void result ) {
//Dismiss your progress dialog here
doSomeWork();
}
}.execute();
}
Instead of using thread you can use asynchronous task. Show the progress dialog in the preexecute method call the printing method inside the background method after completing printing operation call the doSomeWork() inside the postexecute method.
You can use Handler for that in android. for example consider the following piece of code. you can dismiss the dialogs inside handlers. may it work for you.
private void printing(){
Thread receiptPrint = new Thread(new Runnable() {
#Override
public void run() {
retrieveEmails();
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
//here your code executes
//after code executes do following:
uiHandler.sendEmptyMessage(0);
}catch(Exception ex){
errorHandler.sendEmptyMessage(0);
}
}
});
}
});
receiptPrint.start();
}
final Handler uiHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//here execute doSomeWork()
}
};
final Handler errorHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//do other stuff
}
};

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.

Problem with a ProgressDialog

I don't understand the following error:
Activity [myActivity] has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView#4050c3f8 that was
originally added here
Here is my code:
private ProgressDialog progression;
private Handler handler;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Conteneur général
ui = new RelativeLayout(this);
progression = ProgressDialog.show(this, "SwissParl", "Init", true);
handler = new Handler() {
public void handleMessage(Message msg) {
progression.dismiss();
}
};
thread = new Thread() {
public void run() {
firstMethod();
SecondOne();
andTheLast();
handler.sendEmptyMessage(0);
}
};
thread.start();
setContentView(ui);
}
Apparently, the problem is on the line where I instanciate my ProgressDialog...
Any idea?
That happens normally when the activity is destroyed when showing a dialog, for example rotation or finishing activities while showing dialogs.
Try adding a dismiss dialog onPause of activity.
I'm not sure what the problem is, but i suggest you use an AsyncTask
Something like this
private class MyBackgroundTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(ParentActivity.this);
#Override
protected Void doInBackground(Void... param) {
firstMethod();
SecondOne();
andTheLast();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(dialog.isShowing())
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.setCancelable(false); //depending...
dialog.setMessage("Please Wait...");
dialog.show();
}
}
To execute it, call new MyBackgroundTask().execute() inside onCreate()
It's far cleaner than using a handler,thread combination...
private ProgressDialog progression;
private Handler handler;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Conteneur général
ui = new RelativeLayout(this);
setContentView(ui);
progression = ProgressDialog.show(this, "SwissParl", "Init", true);
handler = new Handler() {
public void handleMessage(Message msg) {
progression.dismiss();
}
};
thread = new Thread() {
public void run() {
firstMethod();
SecondOne();
andTheLast();
handler.sendEmptyMessage(0);
}
};
thread.start();
}
You are trying to show a ProgressDialog before adding the main view to the activity.Use the setContentView before you start the ProgressDialog

Categories

Resources