Vlad Pintea Vlad Pintea - 3 months ago 7
Android Question

How do I keep an updated TextView (via SharedPreferences) on the UI?

I've got this TextView (txtCounter), which updates itself every time I run a service. Said process runs smoothly, but whenever I close the application and open it up again, the TextView doesn't show the actual variable, only after I once again run the service.

I know I need to do something in the onCreate (or onResume?) method, something along the lines of receiving the updated TextView from the method which updates it (in my case, it's "UpdateUI") but I don't know what.

MainActivity:

public class MainActivity extends AppCompatActivity {

public TextView txtCounter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Button startApp = (Button) findViewById(R.id.startApp);
final EditText timer = (EditText) findViewById(R.id.insertTimer);

assert startApp != null;
startApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Countdown, Started", Toast.LENGTH_SHORT).show();

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);

Intent intent = new Intent(MainActivity.this, MainService.class);
assert timer != null;
intent.putExtra("timer", timer.getText().toString());
startService(intent);

Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000);

registerReceiver(broadcastReceiver, new IntentFilter(MainService.BROADCAST_ACTION));
}
});
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) { updateUI(intent); }
};

private void updateUI(Intent intent) {
txtCounter = (TextView) findViewById(R.id.txtCounter);

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
int counter = pref.getInt("counter", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("counter", ++counter);
editor.apply();

assert txtCounter != null;
txtCounter.setText(String.valueOf(counter));
}

@Override
public void onDestroy() {
try { unregisterReceiver(broadcastReceiver); } catch (IllegalArgumentException ignored) {}

super.onDestroy();
}

Answer

Call the following method in onResume():

private void updateTVUI() {
    txtCounter = (TextView) findViewById(R.id.txtCounter);

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
    int counter = pref.getInt("counter", 0);

    assert txtCounter != null;
    txtCounter.setText(String.valueOf(counter));
} 
Comments