0

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?

Community
  • 1
  • 1
Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

3

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();
}

}
Arslan Ashraf
  • 867
  • 7
  • 12
  • I get an error `Error:(42, 8) error: class MyCallBack is public, should be declared in a file named MyCallBack.java`. Do I really need to do that? Create a separate file for three lines of code? – Alex Dec 07 '15 at 18:55
  • no make sure your this class public interface MyCallBack { public void refreshMainActivity(); } is outside oncreate() and also make your activity public and try. – Arslan Ashraf Dec 07 '15 at 18:59
  • update your code so that i can see how you are doing this. – Arslan Ashraf Dec 07 '15 at 19:02
  • So far it works, code compiles and the code in `refreshMainActivity` is executed! But still, the main activity does not change. I guess I need to override the method `recreate` in the main activity? – Alex Dec 07 '15 at 19:04
  • Yes that is an options but recreate should do the trick . Or you can notify your list etc whatever you want in callback method in mainactivity. give that a try. – Arslan Ashraf Dec 07 '15 at 19:07
  • I am not sure what you mean by 'notify my list'. I have a `ListView` which is fed by the relevant data in the `onCreate` method, as I did no see another ways of doing this – Alex Dec 07 '15 at 19:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97230/discussion-between-alex-and-arslan). – Alex Dec 07 '15 at 19:12