Search code examples
javaandroid

Saving view state Android while app restarted


I am currently new to Android and am working on a note taker application. Inside the menu, I implemented an option whereby the user can change view if desired (List or Grid).

 LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
        mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
        mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
case R.id.changeView:
                final AlertDialog alertbox = new AlertDialog.Builder(this).create();
                alertbox.setCancelable(true);
                alertbox.setView(customTitleView);
                alertbox.show();
                mListViewSelect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mListNotes.setVisibility(View.VISIBLE);
                        mGridNotes.setVisibility(View.GONE);
                        alertbox.dismiss();
                    }
                });
        mGridViewSelect.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mListNotes.setVisibility(View.GONE);
        mGridNotes.setVisibility(View.VISIBLE);
        alertbox.dismiss();
    }
});
        }
        return super.onOptionsItemSelected(item);
    }

This works perfectly. However, I want the app to open in the selected view initially selected by user. For example, if the user had closed the app while in gridview, the app should open in gridview while restarted.

I understand I need to save data persistently with shared preferences or something. But I need to know exactly what I need to do.


Solution

  • If you want to save your data in Shared Preference, here is a way to do it.

    First you need to create an instance of SharedPreferences and SharedPreferences.Editor:

    private SharedPreferences settings = context.getSharedPreferences("*Desired preferences file", Context.MODE_PRIVATE);
    

    *Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

     private SharedPreferences.Editor editor = settings.edit();
    

    If you need to save a String:

     editor.putString(key, val).commit()
    

    Don't forget to do the .commit();

    To get The String from SharedPreferences:

    String str = settings.getString(key, "");
    

    Saving Int:

    just use:

    editor.putInt(key, val).commit();

    and so on.