我有下面的代码片段将参数从一个类(活动)传递到另一个类。为此,使用过sharedPreferences
,但我尝试在我的第二类中获取保存在主要活动中的值,我得到 java.lang.Nullpointer 异常。我在这里做错了什么?
public class Secondclass extends Activity {
//other functions....
private void get_file_name() {
final main m=new main();
String myvalue=m.set_paramater();
//I want to access FOLDER_NAME here
Log.e("TAG","the value "+myvalue);
}
}
public class main extends Activity{
String FOLDER_NAME;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FOLDER_NAME="a_name";
Save_file_name("APP_NAME",FOLDER_NAME);
}
private void Save_file_name(String key,String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String set_paramater(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSaveddata = sharedPreferences.getString("APP_NAME", "");
return strSaveddata;
}
}
}
这是跟踪文件:
E/AndroidRuntime(10622): FATAL EXCEPTION: main
E/AndroidRuntime(10622): java.lang.NullPointerException
E/AndroidRuntime(10622): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
E/AndroidRuntime(10622): at android.app.Activity.getLocalClassName(Activity.java:3488)
E/AndroidRuntime(10622): at android.app.Activity.getPreferences(Activity.java:3522)