【问题标题】:Android best way to get small external dataAndroid获取少量外部数据的最佳方式
【发布时间】:2013-03-18 23:22:12
【问题描述】:

我必须获取一些外部数据。长话短说 - 它是一个用于自动完成字段的字符串数组。我在我的Activity 中使用了AsyncTask。一切正常,我只是从外部服务器获取文件,将其放入字符串数组并附加到我的自动完成字段:

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);

问题是我每次去特定的Activity时都会这样做。每次启动 AsyncTask 时,它有时会降低我的应用程序的速度。有什么更好的方法可以只获取一次数据,然后在整个应用生命周期中保留它?

【问题讨论】:

    标签: android performance android-asynctask


    【解决方案1】:

    您始终可以对数据使用静态引用,这样您就可以确保只要 VM 正在运行,它就会一直保留在那里。

    您可以创建一个类并将其命名为 DataStorage 之类的名称,然后在该类中添加一个静态 ArrayAdapter 对象

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

    只要您想加载该适配器,就可以从代码中的任何位置:

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

    这称为单例模式,您可以在此处阅读更多信息:Singleton Wiki

    【讨论】:

      【解决方案2】:

      您可以获取此数据一次,然后将其存储在您应用的 Application 类中。 所以下次你打开这个Activity时首先检查你的应用程序中的数组是否 类不为空,不要运行AsyncTask

      要将 Application 类添加到您的应用程序,请执行以下操作:

      1. 像这样创建一个扩展 Application 的类:

      public class YourApplicationClass extends Application
      {   
          ....
      }
      

      2. 并在您的 manifast 中将其定义为您的应用程序类,如下所示:

      <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" >
          ....    
      

      您的应用程序中的所有其他 Activity 类都可以访问此类。

      文档: http://developer.android.com/reference/android/app/Application.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-17
        • 1970-01-01
        • 2015-03-01
        • 2011-11-10
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多