简体   繁体   中英

Android best way to get small external data

I have to get some external data. Long story short - it's a string array for a autocomplete field. I did it with a AsyncTask in my Activity . Everything works fine, I just get file from external server, put it into a String array and attach to my autocomplete field:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    SearchActivity.this, android.R.layout.select_dialog_item,
    result);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.editCity);
textView.setAdapter(adapter);

The problem is I do it every time I go to the specific Activity . Every time the AsyncTask is launched, and it sometimes slows my app a little bit. What is a better way to get that data only once and then keep it for entire app lifecycle?

You can always use a static reference for your data, that way you will ensure it will stay there as long as the VM is running.

you can create a class and call it something like DataStorage and inside that class add a static ArrayAdapter object

public class DataStorage{
  public static ArrayAdapter<String> sharedData;
}

and from anywhere in your code whenever you want to load that adapter:

if (DataStorage.sharedData == null){
     // write code to set sharedData
}

This is called Singleton pattern , you can read more about it here : Singleton Wiki

You can get this data once and then store it in your Application class of your app. so the next time you turn on this Activity check first if the array in your application class is not empty and dont run the AsyncTask .

To add an Application class to your application do this:

1. create a class that extends Application like this:

public class YourApplicationClass extends Application
{   
    ....
}

2. and in your manifast define it as your application class like this:

<application
    android:allowBackup="true"
    android:name=".YourApplicationClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
    ....    

This class is accessible for all the other Activity class in your application.

Documentation: http://developer.android.com/reference/android/app/Application.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM