How to show splash screen when using SQLiteAssetHelper library? - android

I use this library SQLiteAssetHelper for my precreated database. At first run, my app shows white screen only. I guess the library is copying my database(about 10 sec) to the appropriate location. And the splash screen only shown after the white screen. I want to show splash screen also while copying. How do I do that?
Here is my SplashActivity btw.
public class SplashActivity extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String COPIED = "copied";
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (prefs.getBoolean(COPIED, true)) {
new DatabaseCopier().execute(this);
prefs.edit().putBoolean(COPIED, false).commit();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
splashEnd();
}
}, 500);
}
}
private void splashEnd() {
Intent openListActivity = new Intent(this, MainListActivity.class);
startActivity(openListActivity);
}
#Override
protected void onPause() {
super.onPause();
finish();
}
private class DatabaseCopier extends AsyncTask<Context, Void, Void> {
#Override
protected Void doInBackground(Context... params) {
Log.i("suddenly here", "suddenly here 0");
BookDatabaseHelper.getInstance(params[0]); //I thought it start copy from here but not
DatabaseHelper.getInstance(params[0]);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
splashEnd();
}
}
}

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) {}
}
}

how to make a asynctasc work and dismiss after sometime?

I have a asynctask and I want to make it to be canceled after some time, 60 sec for example.
I think I have to it inside a while statemant, but I dont know how to count the time.
Here is my idea:
public class ThreadWithAutoCancel extends AsyncTask<Void, Void, Void> {
public ThreadWithAutoCancel(int timeOut) {
WatchDog watchDog = new WatchDog(this);
watchDog.execute(timeOut);
}
#Override
protected Void doInBackground(Void... params) {
// Do the job
return null;
}
class WatchDog extends AsyncTask<Integer,Void,Void>{
private long startTime;
private AsyncTask task;
public WatchDog(AsyncTask taskToStop){
task = taskToStop;
}
#Override
protected void onPreExecute(){
startTime = System.currentTimeMillis()/1000;
}
#Override
protected Void doInBackground(Integer... params) {
while(System.currentTimeMillis()/1000 < startTime+params[0]){
}
task.cancel(true);
return null;
}
}
}
After starting the AsyncTask, hold a reference to it and call cancel on it 60 seconds later, perhaps on a UI Thread Handler. Inside your doInBackground method you will have to make sure you return if isCancelled returns true. I hope the following snippet will help:
public class MyActivity extends Activity {
private Handler mHandler;
private AsyncTask<?, ?, ?> mTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
}
#Override
protected void onPostResume() {
super.onPostResume();
mTask = new MyCustomTask();
mTask.execute(1, 2, 3);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mTask.cancel();
}, 60L);
}
}
And inside your custom task:
public class MyCustomTask extends AsyncTask<Integer, Float, String> {
#Override
protected String doInBackground(Integer... params) {
String output = "";
for (Integer i : params) {
// Check status for each param
if (isCancelled()) {
return output;
}
...
}
}
#Override
protected void onCancelled(String result) {
// This bit runs on the UI thread
...
}
You can do this using handler. For example this code will show "Completed" on TextView with R.id.mytext after asynctask will execute for 60 seconds:
final int FINISH = 1;
Thread waitingThread;
MyAsyncTask myAsyncTask;
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == FINISH)
{
myAsyncTask.cancel(true);
((TextView) findViewById(R.id.mytext)).setText("Completed");
}
};
};
// ...
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
waitingThread = new Thread(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(60);
mHandler.sendEmptyMessage(FINISH);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
waitingThread.start();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
while (true) {
// do something
}
}
}

Pointing to wrong UI from posted Runnable after screen orintation changes

This is my little test program. My problem is that from run() method I access to fields of wrong (old) Activity, which was destroyed after screen orientation changed. What's the way to handle this situation?
And, by the way, I must have my activity been recreated, because in real application I have different layouts for portrait and landscape modes!
public class MainActivity extends Activity {
private EditText edit;
private Button button;
private ProgressDialog progressDialog;
private boolean isLoginInProgress = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit_timer);
button = (Button) findViewById(R.id.btn_start);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (edit.getText().toString().length() == 0) throw new Exception();
long dTime = Long.parseLong(edit.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MainActivity.this.isLoginInProgress = false;
progressDialog.dismiss();
}
}, dTime);
progressDialog.show();
isLoginInProgress = true;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "bad time value", Toast.LENGTH_SHORT).show();
}
}
});
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading");
if (savedInstanceState != null) { // activity is restarted
isLoginInProgress = savedInstanceState.getBoolean("fl_login");
edit.setText(savedInstanceState.getString("edit"));
}
if (isLoginInProgress) { // Show dialog again
progressDialog.show();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("fl_login", isLoginInProgress);
outState.putString("edit", edit.getText().toString());
}
#Override
public void onDestroy(){
super.onDestroy();
progressDialog.dismiss();
}
}
You Can Use Database(SQLITE) for Storing Your Values..

My Dialog.show() not work

I am making a loading effect when calling MainActivity. I have no idea why my Dialog.show is not working in the AsyncTask. All i just see the just the instant when it dismiss, but the dialog never appear before that.
Thank you.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new LoadViewTask().execute();
setContentView(R.layout.activity_main);
....}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,"Loading...","Loading application View, please wait...", false, false);
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(1000);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
You should use FragmentDialogs for using dialogs in Android.
Here it is well explained:
http://developer.android.com/intl/es/reference/android/app/DialogFragment.html
Try to set the content view before starting your async task:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content view first
setContentView(R.layout.activity_main);
new LoadViewTask().execute();
....}

How to restore when activity is destroyed or paused?

Okay so im having a hard time saving the state of my activity so that when the activity is destroyed it can restore where the user last left off. Here is my source code. If anyone could look at it and tell me how i would save and restore is please it will be greatly appreciated.
Here is my code...
public class DorothyTalk extends Activity{
Handler handler = new Handler();
int typeBar;
TextView text1;
EditText edit;
Button respond;
private String name;
private ProgressDialog progDialog;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.dorothydialog);
text1 = (TextView)findViewById(com.fttech.da.R.id.dialog);
edit = (EditText)findViewById(com.fttech.da.R.id.repsond);
respond = (Button)findViewById(com.fttech.da.R.id.button01);
Talk();
}
protected Dialog onCreateDialog(int id) {
switch(id) {
case 0: // Spinner
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDialog.setMessage("Loading...");
progDialog.setProgress(100);
return progDialog;
}
return progDialog;
}
public void Talk(){
text1.setText("Welcome what is your name?");
respond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = edit.getText().toString();
new AsyncTask<Void, Integer, Void>(){
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
text1.setText("Nice to meet you "+name);
dismissDialog(typeBar);
}
#Override
protected void onPreExecute() {
typeBar = 0;
showDialog(typeBar);
}
}.execute((Void)null);
}
});
}
public void onBackPressed()
{
int i = Log.d("CDA", "onBackPressed Called");
Context localContext = getApplicationContext();
Intent localIntent = new Intent(localContext, mainMenu.class);
startActivityForResult(localIntent, 0);
return;
}
How can i save and restore when activity is destroyed?
You have to save your data before your activity is destroyed. You can test if it is going to be destroyed by using the isFinishing()
protected void onPause(){
if(isFinishing()){
saveData();
}
}
then you neeed to reload your data onCreate()
You can try overiding
public Object onRetainNonConfigurationInstance() {
//object returned here can always be recovered in getLaststNonConfigurationInstance()
return something;
}
and use getLastNonConfigurationInstance() to get the state back.

Categories

Resources