javaandroidsettext

Trying to permanently setText using java Android Studio


I am trying to setText using the following code, the code works fine however when I change activity and then revert back to the activity, the setText seems to reset. Is there another method to resolve this?

       public void onClick(View v) {
            String Note = editTextNote.getText().toString();
            String Email = mAuth.getCurrentUser().getEmail();
            String Status = ("IN");
            
            
            tvClockingStatus.setText("You are clocked: IN");

Solution

  • Activities in Android are created and destroyed at various times in the normal application lifecycle (e.g. when you rotate the screen, or navigate away). If you want data to persist longer than the lifecycle of an Activity you need to store it somewhere more permanent.

    One common place to store small amounts of data is SharedPreferences, which writes key-value pairs to disk so the data is saved even if the app is stopped and restarted or if the activity is destroyed and recreated.

    Here is a simple example of how you could save a "clocked in" status string using SharedPreferences. In the onResume call the data is loaded from the saved preferences and applied to the TextView.

    public class MainActivity extends AppCompatActivity {
    
        private SharedPreferences prefs;
        private TextView status;
        private static final String statusKey = "CLOCKED_STATUS";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    
            Button clockIn = findViewById(R.id.clock_in);
            Button clockOut = findViewById(R.id.clock_out);
            status = findViewById(R.id.clocking_status);
    
            clockIn.setOnClickListener(v -> {
                updateStatus("Clocked In");
            });
    
            clockOut.setOnClickListener(v -> {
                updateStatus("Clocked Out");
            });
        }
    
        private void updateStatus(String newStatus) {
            // save the new state in the preferences - can use 
            // putInt, putBoolean, or several other options to 
            // save different data types
            SharedPreferences.Editor ed = prefs.edit();
            ed.putString(statusKey, newStatus);
            ed.apply();
    
            // Update the data shown in the TextView
            status.setText(newStatus);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
    
            // Load the saved status and show it in the TextView
            String defaultStatus = "Clocked Out";
            String savedStatus = prefs.getString(statusKey, defaultStatus);
            status.setText(savedStatus);
        }
    }