Search code examples
androidandroid-sharedpreferences

Android: SharedPreferences Issue


Hi guys please check this out

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;
                }
            }
        });
    }

I am trying to pass the string(term) to second activity. for example I pressed the 1st Item in ListView which is (Prelim) then the shared preferences will pass the string in the second activity.

And the problem is when I pressed the 2nd(Midterm), 3rd(Final) item etc. etc. the string that stored in shared preferences is still (Prelim).


Solution

  • I think you forgott something like

    preferences.edit().putString("term", TERM).commit();