0

我是 OOP 和 Android 的新手,我面临一个让我非常沮丧的小问题。我正在创建一个使用永久存储的应用程序。最初,我创建了访问所有混合到 MainActivity 中的已保存首选项的代码,该代码有效,然后我想将该代码移动到一个单独的类文件中。问题是由于某种原因它不能在单独的类文件中工作,经过尝试和尝试,我发现我可以在 MainActivity 类中创建一个内部类,并且它可以这样工作。我相信这与这样一个事实有关,如果我将它创建为内部类,我不需要使内部类扩展 Activity(再次)。在为永久存储处理创建外部类时,我需要在该类上扩展 Activity ,我认为这是问题所在,但我不确定。有人可以向我解释为什么会这样,并可能提出正确的方法吗?下面我包含了一个有效的代码片段,但我的目标是能够在单独的类文件中创建类 PermanentStorageHelper。提前致谢!

public class MainActivity extends Activity {

public static MainActivity _mainActivity;
private TextView textView1;

// OnCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Persistent preferences
    PermanentStorageHelper ps = new PermanentStorageHelper();


    // UI Initialization
    textView1 = (TextView) findViewById(R.id.textView1);

    String uId = ps.getuId();
    UiHelper.displayOnTextView(this, R.id.textView1, uId);

}



// =============================================
// This is the class I'm talking about, I'm unable to move this to
// a separated class (.java) file.
// It seems to be related to the fact that, if making this a separated
// class file, I need to extend Activity again and that is what
// seems to be the problem
// =============================================
public class PermanentStorageHelper /*extends Activity*/{

    // CONSTANTS
    public static final String USERUNIQUEID="userUniqueID";             // Saved setting 1
    public static final String FILENAME="mtcPreferences";               // Filename for persisting storage file
    // Fields
    public SharedPreferences shp;                                       // SharedPreferences field (1)
    public String uId;


    public PermanentStorageHelper(){

        // Preferences initialization (2)
        shp = getSharedPreferences(FILENAME, MODE_PRIVATE);

        // Read Preferences (3)
        uId = shp.getString(USERUNIQUEID, null);
    }

    // Getters and Setters
    public String getuId() {
        return uId;
    }
    public void setuId(String uId) {
        this.uId = uId;
    }

}
4

2 回答 2

2

将上下文传递给您的新类:

    public PermanentStorageHelper(Context context){

    // Preferences initialization (2)
    shp = context.getSharedPreferences(FILENAME, MODE_PRIVATE);

}

然后你可以创建你的类,如:

new PermanentStorageHelper(MainActivity.this)
于 2013-07-14T17:08:17.690 回答
0

因为getSharedPreferences您需要访问activityapplicationContext

您可以将上下文添加到构造函数并使用它来调用getSharedPreferences

 public PermanentStorageHelper(Context context){

        // Preferences initialization (2)
        shp = context.getSharedPreferences(FILENAME, MODE_PRIVATE);

        // Read Preferences (3)
        uId = shp.getString(USERUNIQUEID, null);
 }

在这种情况下,您需要在创建对象实例时传递它:

PermanentStorageHelper ps = new PermanentStorageHelper(getApplicationContext());

或者

PermanentStorageHelper ps = new PermanentStorageHelper(MainActivity.this);
于 2013-07-14T17:10:20.763 回答