1

In my settings activity, the user is able to change their name. What I want to do is when the user changes their name, I want to get that data and set the text in another activity to the new name.

In my settings activity, I have this bit of code:

if (preference instanceof EditTextPreference) {
    if (preference.getKey().equals("key_full_name")) {
        // update the changed name to summary filed
        preference.setSummary(stringValue);
        Intent returnIntent = new Intent();
        returnIntent.putExtra("new_Name", stringValue);
        setResult(Activity.RESULT_OK,returnIntent);
    }
}

stringValue has the data that stores the new name. I want it when the user clicks the back button at the top left corner of the settings screen, the other activity has the text set to the new name.

Here is the xml file of the other activity that displays the text:

<TextView
    android:id="@+id/myName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/default_full_name"
    android:textSize="35sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.358" />

Edit: Including AppCompatPreferenceActivity.java file

package app.debata.com.debata;

import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls
 * to be used with AppCompat.
 */
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getDelegate().installViewFactory();
        getDelegate().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getDelegate().onPostCreate(savedInstanceState);
    }

    public ActionBar getSupportActionBar() {
        return getDelegate().getSupportActionBar();
    }

    public void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }

    @Override
    public MenuInflater getMenuInflater() {
        return getDelegate().getMenuInflater();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().addContentView(view, params);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        getDelegate().onPostResume();
    }

    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        getDelegate().setTitle(title);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getDelegate().onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDelegate().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDelegate().onDestroy();
    }

    public void invalidateOptionsMenu() {
        getDelegate().invalidateOptionsMenu();
    }

    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, null);
        }
        return mDelegate;
    }
}

Edit: The entire method that includes the above if statement in the settings.java file

private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String stringValue = newValue.toString();

            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);

            } else if (preference instanceof RingtonePreference) {
                // For ringtone preferences, look up the correct display value
                // using RingtoneManager.
                if (TextUtils.isEmpty(stringValue)) {
                    // Empty values correspond to 'silent' (no ringtone).
                    preference.setSummary(R.string.pref_ringtone_silent);

                } else {
                    Ringtone ringtone = RingtoneManager.getRingtone(
                            preference.getContext(), Uri.parse(stringValue));

                    if (ringtone == null) {
                        // Clear the summary if there was a lookup error.
                        preference.setSummary(R.string.default_ringtone);
                    } else {
                        // Set the summary to reflect the new ringtone display
                        // name.
                        String name = ringtone.getTitle(preference.getContext());
                        preference.setSummary(name);
                    }
                }

            } else if (preference instanceof EditTextPreference) {
                if (preference.getKey().equals("key_full_name")) {
                    // update the changed name to summary filed
                    preference.setSummary(stringValue);
                    Intent returnIntent = new Intent();
                    returnIntent.putExtra("new_Name", stringValue);
                    setResult(Activity.RESULT_OK,returnIntent);
                } else if (preference.getKey().equals("key_username")) {
                    // update the changed gallery name to summary filed
                    preference.setSummary(stringValue);
                } else if (preference.getKey().equals("key_birthday")) {
                    // update the changed gallery name to summary filed
                    preference.setSummary(stringValue);
                } else if (preference.getKey().equals("key_email")) {
                    // update the changed gallery name to summary filed
                    preference.setSummary(stringValue);
                }
            } else {
                preference.setSummary(stringValue);
            }
            return true;
        }
    };
Bert Hanz
  • 417
  • 1
  • 7
  • 16
  • possible duplicate : https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application – Sayem Dec 22 '18 at 18:19
  • @Sayem I disagree that it's a possible duplicate. The settings activity is different from the other activities as makes use of the AppCompatPreferenceActivity.java file. – Bert Hanz Dec 22 '18 at 18:29

2 Answers2

0

If you store values in Shared Preferences you can use OnSharedPreferencesChangedListener in the activity which needs to get the new data. https://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener Register to this listener in onResume and in onCreate.

Another option is to save to the database. Then you can use Room library which returns LiveData object. LiveData will automatically update the screen if data is changed.

Angelina
  • 1,473
  • 2
  • 16
  • 34
  • How do I go about using `OnSharedPreferencesChangedListener`? I've updated my post with more code to make solving the problem easier. – Bert Hanz Dec 22 '18 at 21:37
  • Check this example: http://androidtechnicalblog.blogspot.com/2014/02/listening-to-preference-changes.html – Angelina Dec 23 '18 at 13:26
  • Implement SharedPreferences.OnSharedPreferenceChangeListener interface in the Activity where you need the Views to be updated. Then implement `onSharedPreferenceChanged` method there - in this method you update the View with new data from the shared preferences – Angelina Dec 23 '18 at 13:27
0
      //if you want to set data on back press button ,it means you have previous 
        // activity 
     // so first of all when you start Setting activity,
     // use this to satrt settingActivity -
     Intent i = new Intent(this, SettingActivity.class);
     startActivityForResult(i, 1);

     // in SettingActivity when name updated 

    Intent returnIntent = new Intent();
    returnIntent.putExtra("new_Name",name);
    setResult(Activity.RESULT_OK,returnIntent);
   // finish();

    //override this one in your previous activity where you want to set new name
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
          String name=data.getStringExtra("new_Name");
          //set this name where you want
          }
         if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
         }
      }
     }
Amit
  • 72
  • 4