开发者

Best way to load my Sqlite Tables after creating tables on startup

开发者 https://www.devze.com 2023-02-11 17:46 出处:网络
I have two static tables with about 500 records each which provide lookup material for some ListViews in my app. When the app first starts and the tables are created I run a process to populate the ta

I have two static tables with about 500 records each which provide lookup material for some ListViews in my app. When the app first starts and the tables are created I run a process to populate the tables which takes less than a minute but I've been looking to run the process in background using Async Task with a progress dialog letting the user know what is happening. My concern is that while the process is running and the data is being added and the开发者_如何学Gon the user tilts the phone the process will cancel. What would be the state of my database then? Is Async Task the best solution for this or should I use Threading?


So when you rotate or change the orientation of the phone, the activity is the only thing destroyed. You don't necessarily have to get rid of the async task. In fact it will live on. Just don't let another task come in and work on it ad-hocly.

So if you want to have your activity act as if upon rotating that you can start right back up, where you left off, there is a method called onRetainNonConfigurationInstance(). It's basically the method that stashes objects which can't be parceled like in saveInstanceState()

So the idea being:

public void onCreate(Bundle a) {

   ...
   AsyncTask myTask = getNonConfigurationInstance();
   if (myTask == null) {
     myTask = new AsyncTask();
     myTask.execute();
   }
   ...
}

public Object onRetainNonConfigurationInstance() {
   return myTask;
}

This will keep the async task running, and when you get your onCreate called after the rotation you just pick it back up and do what needs to be done.

One thing to be conscious of is the progressView. It will have to be destroyed and reinitialized to the new state. Also the overall dismissing of it and showing it in the first place should be done outside the AsyncTask. But nothing is to say that the AsyncTask can't call some callback that you always set in your onCreate() so that it will notify to tell to update the UI or play a sound of completion, etc.


You could also decide to handle the configuration changes on your own through the use of the android:configChanges in your manifest.

You then implement the onConfigurationChanged method and perform any actions inside.

See the developer doc.

When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.

0

精彩评论

暂无评论...
验证码 换一张
取 消