大家好,请查看
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade_viewer);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myListView = (ListView) findViewById(R.id.list);
String records[] = {"Prelim","Midterm","Final", "Final Grade"};
myAdapter = new ArrayAdapter<String>(this, R.layout.list_rec, R.id.tvRec, records);
myListView.setAdapter(myAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String TERM = ((TextView) (view.findViewById(R.id.tvRec))).getText().toString();
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
preferences.edit().putString("term", TERM);
switch (position){
case 0:
Intent intent = new Intent(GradeViewer.this, PrelimGrade.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(GradeViewer.this, MidtermGrade.class);
startActivity(intent1);
break;
case 2:
Intent intent2 = new Intent(GradeViewer.this, TentativeFinalGrade.class);
startActivity(intent2);
break;
case 3:
Intent intent3 = new Intent(GradeViewer.this, FinalGrade.class);
startActivity(intent3);
break;
}
}
});
}
我正在尝试将字符串(term)传递给第二个活动。 例如,我在ListView中按下第一个项目(Prelim),然后共享首选项将在第二个活动中传递字符串。
问题是当我按下第二个(中期),第三个(最终)项目等时,存储在共享首选项中的字符串仍然是(Prelim)。
答案 0 :(得分:3)
我认为你原谅像
这样的东西preferences.edit().putString("term", TERM).commit();
答案 1 :(得分:0)
您忘记将更改应用或保存到共享偏好设置:
String TERM = ((TextView) (view.findViewById(R.id.tvRec))).getText().toString();
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
// here you should apply or commit your changes:
preferences.edit().putString("term", TERM).apply();
switch (position){
case 0:
Intent intent = new Intent(GradeViewer.this, PrelimGrade.class);
// if you only need your "TERM" in the next activity, it would be a cleaner
// approach to send it via your intent:
intent.putExtra(TERM, "term");
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(GradeViewer.this, MidtermGrade.class);
startActivity(intent1);
break;
case 2:
Intent intent2 = new Intent(GradeViewer.this, TentativeFinalGrade.class);
startActivity(intent2);
break;
case 3:
Intent intent3 = new Intent(GradeViewer.this, FinalGrade.class);
startActivity(intent3);
break;
}