所以在一个 Activity 中,我试图将一个文件放入共享首选项中,然后在另一个 Activity 中,我试图烘烤该字符串,但由于某种原因,android 正在烘烤默认值而不是我从共享中输入的值偏好。
这是 MainActivity:
public void onPreviewFrame(byte[] data, Camera camera) {
// By default preview data is in NV21 format, if needed it must be converted
try {
Camera.Size previewSize = camera.getParameters().getPreviewSize();
int height = previewSize.height;
int width = previewSize.width;
ColorModelConverter converter = new ColorModelConverter(height, width);
int[] pixels = converter.convert(data, this.colorFormat);
int color = pickColor(pixels, height, width);
updateColorData(color);
storeColorInSharedPreferences(color);
Log.i("FRAME PREVIEW", "Color updated");
} catch (RuntimeException oops) {
// Do nothing, exception is thrown because onPreviewFrame is called after camera is released
Log.i("FRAME PREVIEW", "RuntimeException thrown into onPreviewFrame");
}
}
public void storeColorInSharedPreferences(int color) {
SharedPreferences sharedprefernces = getSharedPreferences("Mydata",Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedprefernces.edit();
String first_control = String.valueOf(color);
editor.putString("first_control", first_control);
editor.commit();
这是第二个 Activity :
public class regressionlinecalculator extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regressionlinecalculator);
}
SharedPreferences sharedPreferences = getSharedPreferences("MyData",Context.MODE_PRIVATE);
String first_control = sharedPreferences.getString("first_control", "");
public void test(View view) {
Toast display_final_value = Toast.makeText(getApplicationContext(), new String(first_control), Toast.LENGTH_SHORT);
display_final_value.show();
}
}
测试就是当我单击我在 xml 文件中定义的按钮时发生的情况。所以我的问题是,为什么 android 会一直保持默认值,即“”而不是颜色,这是我在其他 Activity 中输入到共享首选项中的值?
最佳答案
So my question is why does android keep toasting the default value, which is "" instead of color, the value which I inputted into shared preferences in the other activity?
这是因为您正在为 Toast
使用 getApplicationContext()
。直接使用 Activity 的 Context
。
Toast display_final_value = Toast.makeText(this,first_control, Toast.LENGTH_SHORT);
另一方面,您在检索 SharedPreference 对象时出现错字。使用常量来避免此类问题。此外,它的初始化应该移到回调方法中。例如。 onCreate
SharedPreferences sharedPreferences;
String first_control;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regressionlinecalculator);
sharedPreferences = getSharedPreferences("Mydata",Context.MODE_PRIVATE);
first_control = sharedPreferences.getString("first_control", "");
}
关于java - 从共享首选项中检索值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34535894/