Search code examples
javaandroidandroid-studiotextview

How to dynamically store a permanent value to a TextView


I'm making an Android bank app with Java , this is the withdrawal function that i had problems with it. Main page

The withdrawal page

When i choose 100 or any option the value is deducted from the balance the problem here is that the balance is a TextView i am using setText() to update the balance but when the page is refreshed or goes from activity to activity it doesn't stored permanently, it's not dynamically saved so what's the solution?


Solution

  • You can use Shared Preferences to save value permanently
    create a SharedPreference like this

    SharedPreferences sharedPref = getActivity().getSharedPreferences(
            "amount_key", Context.MODE_PRIVATE);
    

    Write your value to it on your button onClicks or whatever way change the value like this

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    //This will put value to sharedpreference with id amount_key
    // like this new value can be 100 less than previous one
    editor.putInt("amount_key", newValueToPutThereInText);
    editor.apply();
    

    This will save the newValueToPutThereInText to SharedPreference permanently.

    and to access that value use this

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    int amount = sharedPref.getInt("amount_key", anyDefaultValueToUse);
    // and use it in your balance textview
    Textview balance = findViewById(R.id.your_id);
    balance.setText(amount);
    
    

    See Here