简体   繁体   中英

How to force an update of the main activity from 'outside' in android?

This question is a kind of followup on this unanswered question with more and better details.

Basically, I have an android main activity showing some data which are taken from a database (via SQLiteDatabase ). Now I have a PreferenceActivity which is shown when the user wants to change some preference, or delete the content of the database. In the latter case the content of the database is deleted - but how do I make the main activity to be updated? If I look at the main activity after I pressed the button to delete the content of the database, I expect to show the main activity zero entries!

Here is the relevant part of the main activity:

public class MainActivity extends AppCompatActivity  {

    SharedPreferences.OnSharedPreferenceChangeListener mPrefListener;
    private SharedPreferences settings;
    public interface MyCallBack
    {
        public void refreshMainActivity();
    }

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

        Intent intent = new Intent(this, AlarmService.class);
        startService(intent);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mCallback = new MyCallBack() {
            @Override
            public void refreshMainActivity() {
                Toast.makeText(MainActivity.this, "TOAST MAINACTIVITY", Toast.LENGTH_LONG).show();
                MainActivity.this.recreate();
            }
        };
        /*
        settings = PreferenceManager.getDefaultSharedPreferences(this);
        mPrefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                Log.d("TEST", "testtest");

                Toast.makeText(MainActivity.this, "TOAST MAINACTIVITY", Toast.LENGTH_LONG).show();

                finish();
                startActivity(getIntent());
            }
        };
        */

        // Register the listener on the SharedPreferences
        settings.registerOnSharedPreferenceChangeListener(mPrefListener);

Here is the content of UserSettingActivity.java :

public class UserSettingActivity extends PreferenceActivity {

    private Preference myPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        myPreference = findPreference("reset");
        myPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(UserSettingActivity.this);
                alertDialog.setMessage("Are you sure to delete the database?");
                alertDialog.setCancelable(true);
                alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        final DBAdapter db = new DBAdapter(UserSettingActivity.this);
                        db.open();
                        db.resetDatabase();
                        callBack = MainActivity.mCallback;
                        callBack.refreshMainActivity();
                    } });
                alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    } });
                alertDialog.show();
                return false;
            }
        });

    }

}

And finally, the xml file describing the layout of the settings in xml/preferences.xml :

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference android:title="Your Name"
        android:key="username"
        android:summary="Please provide your username"></EditTextPreference>
    <CheckBoxPreference android:title="Application Updates"
        android:defaultValue="false"
        android:summary="This option if selected will allow the application to check for latest versions."
        android:key="applicationUpdates" />

    <Preference
        android:key="reset"
        android:title="Reset database"
        android:summary="This will remove every entry in the database"
         />
</PreferenceScreen>

When I click on the button reset on the Settings screen and confirm this choice, the database is deleted resetDatabase does a DROP and a CREATE TABLE of the two tables in the database). However, the Toast 'TOAST MAINACTIVITY' is never shown on the display!

What do I miss here to make this work as I expect it to work? How do I trigger a method/function/something in my main activity from the UserSettingActivity ?

The Solution could be a bit tricky with using callback but i hope this will work for you according to your conditions..

First of all create interface in your MainActivity.java like this

public interface MyCallBack
{
 public void refreshMainActivity();
}

then implement this interface in your main activity like this

public class MainActivity extends AppCompatActivity {
public static MyCallBack mCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mCallback = new MyCallBack() {
    @Override
    public void refreshMainActivity() {
           MainActivity.this.recreate();

              "OR"

              finish();
              startActivity(getIntent());
         }
    };
}

Now in your userSettingActivity.java use this interface like this and call its method when you want to update your MainActivity.java

public class UserSettingActivity extends AppCompatActivity{
MainActivity.MyCallBack callBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settingsactivity);
    callBack = MainActivity.mCallback;

    //this is sample code ..call this function when you want to update mainactivity
    callBack.refreshMainActivity();
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM