English 中文(简体)
一组公用事业职能静态变量的初始化
原标题:Initialization of static variables in a class of utility functions
  • 时间:2012-05-21 21:58:40
  •  标签:
  • android

对于我的Android 应用程序,我写了一个由应用程序中各种活动需要的实用功能组成的类。 在这个类中, 我需要一个上下文变量( 用于与文件一起工作) 和一个偏好管理者和偏好编辑的例子。 另外, 需要一个长长的整数折叠式的当前日期作为时间戳 :

private static long today;
private static Context myContext;
private static SharedPreferences sharedPrefs;
private static Editor editor;

这是初始化这些变量的正确方法。我尝试过通过下文所示的私人建筑师这样做,但是我正在寻找错误者。

private NetworkController()
{
    //Getting the Unix timestamp for today
    GregorianCalendar aDate = new GregorianCalendar();
    GregorianCalendar tDate = new  
    GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),  
    aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    today = (tDate.getTimeInMillis())/1000; 
     //The preferences manager for reading in the preferences
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(myContext);
    //The preferences editor for modifying the preferences values
    editor = sharedPrefs.edit();
}

一种办法是,在使用过这种类别但我不想这样做的每一项活动中,都建立这种类别的例子。 任何其他办法都可能吗?

问题回答

@Greg 是对的, 只是不要使用任何静态的东西来做您想要做的事情。 您没有理由不想在这里有普通对象。 将上下文作为参数传递, 当您需要它们来为您服务时, 请按时显示对象 :

private long today;
private Context myContext;
private SharedPreferences sharedPrefs;
private Editor editor;

public NetworkController( Context context )
{
    this.context = context;
    //Getting the Unix timestamp for today
    GregorianCalendar aDate = new GregorianCalendar();
    GregorianCalendar tDate = new  
    GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),  
    aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    today = (tDate.getTimeInMillis())/1000; 
     //The preferences manager for reading in the preferences
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    //The preferences editor for modifying the preferences values
    editor = sharedPrefs.edit();
}

单子是编程的坏方式,它使得事情很难测试。 即使你还没有使用测试,也没有使用单子,当事情变得更加复杂时,它会导致质量极差的代码和真正的泥团。

在这里你可以做到这一点:

public class NetworkController {

     SharedPreferences settings;
     SharedPreferences.Editor editor;


     public NetworkController(Context context){
        settings = PreferenceManager.getDefaultSharedPreferences(context);
        editor = settings.edit();
     }

     public void saveName(String name){
          editor.putString("name", name).commit();
     }

     public String getName(){
          return settings.getString("name");
     }

     public static long getTimeStamp(){
          return System.currentTimeMillis();
     } 

}

您可以使用下面的类 :

 NetworkController prefs = new NetworkController(context); // Context being an Activity or Application
 prefs.saveName("blundell");
 System.out.println(prefs.getName()); // Prints  blundell ;
 System.out.println(NetworkController.getTimeStamp()); // Prints 1294931209000

如果您不想在每类中创建实例, 您可以在应用程序中创建实例, 并总是引用 :

public class MyApplication extends Application {

     private NetworkController myPrefs;

     public NetworkController getPrefs(){
          if(myPrefs == null){ // This is called lazy initialization
             myPrefs = new NetworkController(this); // This uses the Application as the context, so you don t have issues when Activitys are closed or destroyed
          }
          return myPrefs;
     }

}

您需要将 MyApplication 添加到您的列表中 :

<application 
    android:name="com.your.package.MyApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">

要使用此单一实例, 您可以这样做 :

public class MyActivity extends Activity {


     public void onCreate(Bundle savedInstanceState){
          super(savedInstanceState);

          NetworkController prefs = ((NetworkController) getApplicationContext()).getPrefs();

          // use this object just like shown above
          prefs.saveName("blundell"); // etc
     }

}

这里已经张贴了一大堆好的建议, 但我想另一种方法, 就是简单地通过您需要的逻辑参数。 在您的情况中, 而不是试图在本地的 < code> Context 引用中使逻辑工作, 您可以简单地通过 :

public static void NetworkController(Context context) {
    //Getting the Unix timestamp for today
    GregorianCalendar aDate = new GregorianCalendar();
    GregorianCalendar tDate = new  
    GregorianCalendar(aDate.get(Calendar.YEAR),aDate.get(Calendar.MONTH),  
    aDate.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
    long today = (tDate.getTimeInMillis())/1000; 
    //The preferences editor for modifying the preferences values
    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
    ...
}

您可以在苍蝇上计算/ 生成的其他变量。 它可能意味着更多的垃圾收集, 但是在存储管理方面应该相对安全 。





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签