0

我已经查看了我能找到的所有线程,但没有一个真正解释了为什么找不到文件,所以我再次尝试使用代码。我在调试器中的 LG Spectrum 上运行了它。一切正常,除了没有创建我可以找到的文件,而且我无法读取我编写的名称/值对。

package com.example.locdir;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.SharedPreferences;
import android.content.Context;

public class MainActivity extends Activity {

int testint = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setup();
    readback();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private void setup() {
    SharedPreferences sharedPref = getSharedPreferences(
            getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("testint", 475);
    editor.commit();        
}

private void readback() {
    SharedPreferences sharedPref = getSharedPreferences(
            getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    int testint = sharedPref.getInt("testint", 0);
}
}

根据调试器的行为,它运行良好。sharedPref.mFile.path 的值为“/data/data/com.example.locdir/shared_prefs/locdir_pref.xml”

运行后,该路径上没有该名称的文件。

当调用 readback 方法并发生 getInt 时, testint 仍然为 0。

我看不到任何日志投诉。

哦,我也试过 sharedPref.apply() 。一样。

4

2 回答 2

1

int testint = 0您在课程开始时声明变量。删除该行,一切都应该正常工作。

public class MainActivity extends Activity {

int testint = 0; // REMOVE THIS LINE
于 2013-06-11T01:55:16.110 回答
0

你在哪里监控testint。如果它在 onCreate() 方法中,是的,无论如何你都会有 0,因为你已经将 testint 定义为全局变量并将其初始化为 0。
如下更改代码。

private void readback() {
    SharedPreferences sharedPref = getSharedPreferences(
            getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    testint = sharedPref.getInt("testint", 0); // remove int
}
}
于 2013-06-11T02:45:22.163 回答