简体   繁体   English

如何从android中的“外部”强制更新主要活动?

[英]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 ). 基本上,我有一个android main活动,显示了一些从数据库中获取的数据(通过SQLiteDatabase )。 Now I have a PreferenceActivity which is shown when the user wants to change some preference, or delete the content of the database. 现在,我有一个PreferenceActivity ,当用户想要更改某些首选项或删除数据库的内容时显示。 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 : 这是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/preferences.xml设置布局的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). 当我单击“设置”屏幕上的“ reset ”按钮并确认此选择时,数据库将被删除resetDatabase对数据库中的两个表执行DROPCREATE TABLE的操作。 However, the Toast 'TOAST MAINACTIVITY' is never shown on the display! 但是, Toast “ TOAST MAINACTIVITY”永远不会显示在显示屏上!

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 ? 如何通过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 首先像这样在您的MainActivity.java中创建接口

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 现在,在userSettingActivity.java中使用此接口,并在要更新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();
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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