SilverShotBee SilverShotBee - 1 month ago 18
Android Question

Android Updating A TextView From A Different Activity

I'm new to android and not 100% certain I have the terminology of my question correct, but here it is.

I have a layout that has a

TextView
that I want to reflect a setting. The problem I am facing is that the Setting page ("customsignalsetup") is navigated to from the page that the
TextView
I want to update is situated on. When the option is changed on the settings page, and closed using
Finish()
, the
TextView
hasn't updated. However, if I close the page the
TextView
is on, then open it again, it has updated.

Here's my code:

TextView Update Code (Before any changes on the settings page)

settings = getSharedPreferences("CustomSignalSettings", 0);
TextView CustLabel = (TextView)findViewById(R.id.cunitslabel);
CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");


Code To Handle "Settings" Pressed From Menu And Switch To Settings Page

public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.custom_signal_setup:
// Open Settings Page
Intent intent = new Intent(PLCActivity.this, customsignalsetup.class);
startActivity(intent);

return true;
case R.id.help:
//get help
return true;
default:
return super.onOptionsItemSelected(item);
}
}


Setting Page Code To Update TextView

public class customsignalsetup extends AppCompatActivity implements View.OnClickListener {

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customplcsettingspopup);

Button button = (Button) findViewById(R.id.save);
button.setOnClickListener(this);
}

public void onClick(View v) {
switch(v.getId()){
case R.id.save:

//THE BELOW LINE IS SUPPOSED TO SET 'CustLabel' TO THE TEXTVIEW TO BE UPDATED
TextView CustLabel = (TextView)findViewById(R.id.cunitslabel);

SharedPreferences settings = getSharedPreferences("CustomSignalSettings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("CustomSignalUnit",CusUnit.getText().toString());
editor.commit();

// THE BELOW LINE IS SUPPOSED TO UPDATE THE TEXTVIEW ON A DIFFERENT PAGE
CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");

finish();
}
}


}


My code throws no errors, but the TextView simply doesn't update. Im assuming this is because the activity loaded the original textview hasn't ended yet and only future labels will be updated?

Thanks

Answer

put this line like this so you will get the updated value everytime.

@Override
public void onResume() {
   super.onResume();  // Always call the superclass method first
   CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");
}
Comments