Hi it's my first question in stackoverflow sorry if i do something wrong.
My problem is that when i start the app for very first time i need to write the SQL data in the database. If i do that in onCreate() while it's writing the sql it's not showing the View so it's like freezing. And if i make loader there it's not showed because first of all ti want's to finish all the oncreate and after that to show the View. Then i made AlertDialog to run if SQL is empty to inform the user that in needs "instalation" and after confirm i wanted to make loading box while it's running inserting the SQL...
So my question is : How to make loading onCreate... at running of the activity... can u give me some good idea... here is the code i made:
private DatabaseHandler db = new DatabaseHandler(this);
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
if(db.getWordsCount() == 0)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Instalation needed");
builder.setMessage("Database need to be installed");
builder.setPositiveButton("Ok", dialogClickListener);
builder.setNegativeButton("Close", dialogClickListener);
builder.show();
}
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
ProgressDialog progress = new ProgressDialog(context);
progress.setTitle("Instalation");
progress.setMessage("Please wait...");
progress.show();
db.insertWords(db);
progress.cancel();
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
}
}
};
There is a lots of example for same :
http://ashwinrayaprolu.wordpress.com/2011/03/15/android-database-example-database-usage-asynctask-database-export/
private class InsertDataTask extends AsyncTask {
private final ProgressDialog dialog = new ProgressDialog(
DatabaseActivity.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Inserting data...");
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(final String... args) {
DatabaseActivity.this.application.getDataHelper().insert(args[0]);
return null;
}
// can use UI thread here
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
// reset the output view by retrieving the new data
// (note, this is a naive example, in the real world it might make sense
// to have a cache of the data and just append to what is already there, or such
// in order to cut down on expensive database operations)
new SelectDataTask().execute();
}
}
Related
I'm having the following problem while trying to restore a ProgressDialog from a configuration change. This is my code:
server is a class that does some networking in a thread and after it finishes, it calls the callback on the handler that made the initial call.
public class MainActivity extends FragmentActivity {
private boolean hasAuthDialog = false;
ProgressDialog progressDialog;
// login fragment
public void doLogin(View b) {
boolean ok = true;
if(ok) {
progressDialog = new ProgressDialog(this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Autenticando");
progressDialog.setCancelable(false);
progressDialog.show();
hasAuthDialog = true;
try {
server.doLogin(cedula.getText().toString(), pass.getText().toString(), new ServerBridgeResponse_CallBack() {
#Override
public void run(Boolean success, Object... args) {
// login finalizado
if(success) {
Toast.makeText(me, "Login success", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(me, "Login error", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
hasAuthDialog = false;
}
});
} catch (ServerBridgeNotReadyException e) {
}
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("hasAuthDialog", hasAuthDialog);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
hasAuthDialog = savedInstanceState.getBoolean("hasAuthDialog");
if(hasAuthDialog) {
progressDialog = new ProgressDialog(this);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Autenticando restored");
progressDialog.setCancelable(false);
progressDialog.show();
hasAuthDialog = true;
}
}
The thing is that after an orientation change, when debugging, progressDialog in the doLogin method still refers to the old dialog and not the new one that I created in onRestoreInstance (I know this because of the message. It still says 'Autenticando' instead of 'Autenticando Restored'). What am I doing wrong?
Thanks in advance!
Have you tried making progressDialog static? That way the set variable will be dismissed by the run method, and not the reference to the old progressDialog.
I get it now. The thing is that when there's an orientation change, Android creates an entirely new instance of the activity. Because of this behavior, the keyword this in the callback refers to the previous instance.
One way we could fix this problem is by making the progressDialog static as suggested by Bassiuz, but one different (and IMO more flexible) solution would be to create an static MainActivity me variable and assigning it this at the end of onCreate. After that, in doLogin callback, use me.progressDialog and it should have the reference to the new dialog.
Thanks to Bassiuz!
I have a huge database (40MB) on an SDCard. I need fetch data, with LIKE in query, which is very slow.
DB request takes about 5 seconds. Therefore, I need to do it asynchronously and with ProgressDialog.
I tried it with AsyncTask, but problem is with ProgressDialog. It was implemented this way:
private class GetDataFromLangDB extends AsyncTask<String, String, String> {
private final ProgressDialog dialog = new ProgressDialog(TranslAndActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
urDBCursor.close();
curDBCursor = null;
scaAdapter = null;
this.dialog.setMessage("Loading data...");
this.dialog.show();
}
#Override
protected String doInBackground(String... whatSearch) {
String result = "";
if (myDatabaseAdapter != null) {
curDBCursor = myDatabaseAdapter.fetchAll(whatSearch[0]);
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
prepareListView();
}
}
The problem is that ProgressDialog is not shown during the DB request.
After finished database query, it flash on screen for a short time. When user tries
to tap on screen during database request, UI is freezed, and after DB request
message about 'not responding' is shown.
I tried it with a thread this way:
public void startProgress(View view, final String aWhatSearch) {
final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
if (curDBCursor != null){
curDBCursor.close();
curDBCursor = null;
}
dialog.setMessage("Loading data...");
dialog.show();
Runnable runnable = new Runnable() {
public void run() {
curDBCursor = myDatabaseAdapter.fetchAll(aWhatSearch);
// dirty trick
try {
Thread.sleep(250); // it must be here to show progress
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
}
prepareListView();
}
});
}
};
new Thread(runnable).start();
}
The result was the same, but when I used the trick with Thread.sleep(250);
ProgressDialog was shown during the database request. But it is not spinning,
it looks freezed during the DB request.
DB stuff is called this way (after tap on search button):
btnSearchAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// AsyncTask
new GetDataFromLangDB().execute(edtTextToSearch.getText().toString());
// or Thread
//startProgress(null, edtTextToSearch.getText().toString());
}
});
I found a lot of problems like this in SO, but nothing was useful for me.
Could it be that DB is on SD Card?
I put the definition of the dialog into the AsyncTask Class and it works fine for me.
Take a look at this exampel (You have to change NAMEOFCLASS in the name of your CLASS:
private class doInBackground extends AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(NAMEOFCLASS.this) {
#Override
protected void onPreExecute() {
dialog.setCancelable(false);
dialog.setTitle(getString(R.string.daten_wait_titel));
dialog.setIcon(R.drawable.icon);
dialog.setMessage(getString(R.string.dse_dialog_speichern));
dialog.show();
}
#Override
protected void onCancelled() {
dialog.cancel();
}
....
#Override
protected void onProgressUpdate(Integer... values) {
// DO YOUR UPDATE HERE
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
Maybe this SO answer could help you. It looks like similar problem. Try to use AsyncQueryHandler for querying your database
declare you Dialog box on Class (Activity) level like this
private ProgressDialog dialog = null;
show the progress dialog and call the AsyncTask class when you want to start you Busy work..like onButton click or any
dialog = ProgressDialog.show(this,"Sending Email to your account please! wait...", true);
SendingEmailTask task = new SendingEmailTask();
String s = "";
task.execute(s);
create your inner class like
private class SendingEmailTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
//do your work here..
// like fetching the Data from DB or any
return null;
}
#Override
protected void onPostExecute(String str) {
//hide progress dialog here
dialog.dismiss();
}
}
let me know if this help!!
So I have an AsyncTask that runs the Login procedure. Before running, I open a transaction and commit a DialogFragment to display a progress dialog to the user with a ok button in it.
I would like to make it disabled, only enabling it when/if the Login fails for some reason and the user can click on it and dismiss (actually popping out the dialogfragment from the stack).
I can only access the button in order to disable it in the part of the code bellow after the workaround comment.
I tried to put that code inside overrided onAttach() and inside onStart() from DialogFragment but its always returning NullPointerException.
Here is my code:
class LoginTask extends AsyncTask<String, Integer, String> {
private DialogFragment df;
#Override
protected void onPreExecute() {
df = new DialogFragment() {
public Dialog onCreateDialog(Bundle savedInstanceState) {
ProgressDialog pd = new ProgressDialog(LoginActivity.this, ProgressDialog.THEME_HOLO_LIGHT);
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.setMessage(getString(R.string.login_message));
pd.setTitle(getString(R.string.login_title));
pd.setButton(ProgressDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getFragmentManager().popBackStack();
}
});
return pd;
};
};
getFragmentManager().beginTransaction().add(df, "LOGIN_DLG_FRAG").commit();
}
#Override
protected String doInBackground(String... params) {
// WORKAROUND
runOnUiThread(new Runnable() {
#Override
public void run() {
((ProgressDialog)df.getDialog()).getButton(ProgressDialog.BUTTON_POSITIVE).setEnabled(false);
}
});
...
}
}
I know the FragmentTransaction.commit() schedule the operations, so I would like to know how can access the view components of the fragment the correct way.
Thanks in advance.
I have an AlertDialog in and it's got a button, which, if selected, will initiate a file upload to a remote server like this:
builder.setMessage(text)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
uploadFile();
}})
This works fine, the only problem is that uploadFile() can potentially take a long time (30 seconds to 2 minutes). I would like to replace the AlertDialog with a progress dialog (even an indeterminate one), but I can't see how to launch one dialog from another?
Can anyone offer some advice for a how I could accomplish this.
Thanks,
Jarabek
You can use AsyncTask here, keep your ProgressDialog on the PreExecute() and call the method in the doingInBackground() and dismiss the ProgressDialog in the PostExecute().
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(ActivityName.this, "Loading...", "Data is Loading...");
}
#Override
protected Void doInBackground(Void... params) {
uploadFile();
return null;
}
}
Then just call the MyAsyncTask using new MyAsyncTask().execute();
The best way to do this - using AsyncTask. There you can provide progress and do your long action
The next version of my app needs to upgrade the database and this takes quite a bit of time. I'd like to show a progressDialog to update the user on the progress. Problem is, I can't quite figure out how and where to create the dialog.
My basic setup is that I have an activity which is essentially a splashscreen. It's on this screen I would like to show the progress. I have a separate DbAdapter.java file where a DatabaseHelper class extends SQLiteOpenHelper, where I override onUpgrade (the upgrade part is working fine).
I've tried a few different places to implement the progress dialog, but I don't seem to find the right spot. I tried passing context from my splashscreen activity to onUpgrade, but when onUpgrade runs it seems to be getting the context from my ContentProvider instead.
Does anyone have a good example of how to display a progress dialog when upgrading a database?
You need to implement an AsyncTask. Example:
class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
//show your dialog here
progressDialog = ProgressDialog.show(this, "title", "message", true, false)
}
#Override
protected Void doInBackground(Void... params) {
//update your DB - it will run in a different thread
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide your dialog here
progressDialog.dismiss();
}
}
Then you just have to call
new YourAsyncTask().execute();
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
ProgressDialog myProgressDialog = null;
public void DownloadFiles() {
myProgressDialog = ProgressDialog.show(this, "Please wait !",
"Updating...", true);
new Thread() {
public void run() {
try {
//Your upgrade method !
YourUpdateFunction();
} catch (Exception e) {
Log.v(TAG, "Error");
}
myProgressDialog.dismiss();
}
}.start();
}