Search code examples
androidcheckboxtextbox

Save input text and use same text as checkbox label in another activity


In my android app, I want to provide a text box to input a name and save it. Later I want to retrieve the text as checkbox label in other activity. So.. how can I do it? Like multiple names will generate multiple checkbox in next activity..

Thank you in advance..


Solution

  • You can store such data in SharedPreferences, see this guide:

    https://developer.android.com/training/data-storage/shared-preferences.html

    So in your case:

    1) Get data from EditText:

    EditText etTextInput = findViewById(R.id.my_edittext);
    String text = etTextInput.getText().toString();
    

    2) Write to Shared Preferences:

    Context context = getActivity();
    SharedPreferences sharedPref = context.getSharedPreferences(
            "preference_file_key", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("key_my_text", text);
    editor.commit();
    

    3) Retrieve from Shared Preferences in another Activity:

    SharedPreferences sharedPref = context.getSharedPreferences(
                "preference_file_key", Context.MODE_PRIVATE);
    String text = sharedPref.getString("key_my_text", "default_value");
    

    4) Set text to your CheckBox:

    CheckBox checkbox = findViewById(R.id.my_ checkbox);
    checkbox.setText(text);
    

    Note this is very simplified, you can i.e. create a Shared Preferences helper class as per this question and answers: SharedPreferences helper class