我有两个班级Settings
和MainActivity
. 我正在尝试Settings
从班级访问在班级创建的微调器MainActivity
。
这通常有效
public static Settings getlang = new Settings();
问题是,如果我尝试在不先打开 Settings 活动并直接进入 MainActivity 的情况下执行此操作,我会在这一行得到 NullPointerException
getlang.getLang1().setSelection(getlang.getLang());
但是,如果我先打开Settings
活动然后转到MainActivity
一切正常。
我怎样才能解决这个问题?
这里是Settings
活动
public class Settings extends Activity {
public SharedPreferences prefsSet;
public String prefNameSet = "MyPrefSet";
public static final String PREFS_NAME_SET = "SAVEDATASET";
private static final String SPINNER1_STATE = "spinner1_state";
public int language;
public int userChoice;
private static Spinner spinner1;
private Button savesett;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
savesett = (Button) findViewById(R.id.bSaveSett);
spinner1 = (Spinner) findViewById(R.id.spinner1);
SharedPreferences sharedPref = getSharedPreferences("FileName",
MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner", -1);
if (spinnerValue != -1)
// set the value of the spinner
spinner1.setSelection(spinnerValue);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
userChoice = spinner1.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",
0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner", userChoice);
prefEditor.commit();
Toast.makeText(
parent.getContext(),
"Chosen Language: "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
savesett.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ourIntent = new Intent(Settings.this, MainActivity.class);
startActivity(ourIntent);
}
});
}
public int getLang() {
return userChoice;}
public Spinner getLang1() {
return Settings.spinner1;
}
}