Android-在重新启动应用程序之前保存更新的数据

时间:2014-12-02 00:13:06

标签: android save

在我正在处理的Android应用程序中,我有一个活动,其中用户输入使用SharedPreferences保存的数据,并用于主要活动的某些计算。我遇到的一个问题是,在保存数据之后,更改实际上不会在应用程序重新启动后生效。有没有办法让它能够在重新启动之前更新与这些SharedPreferences相关的变量?

这是我在单独的活动中保存数据的地方。

     saveBn.setOnClickListener(new View.OnClickListener() { 

        @Override
        public void onClick(View v) {

            weightString = weightText.getText().toString();
            ageString = ageText.getText().toString();

            getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
            .putString("savedWeight", weightString).commit();
            getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
            .putString("savedAge", ageString).commit();

            //Intent i = new Intent("com.williammiller.capstonelapv2.MainActivity");
            //startActivity(i);

                finish();
        }
    });

这是我在主要活动中查看它们是什么的地方

    String age = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getString("savedAge", "25");

   String weight = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getString("savedWeight", "200");

    startBn.setOnClickListener(new View.OnClickListener() { 

        @Override
        public void onClick(View v) {



                Toast.makeText(getApplicationContext(), "weight = " + weightInt + " age = " + ageInt, Toast.LENGTH_LONG).show();





        }
    });

1 个答案:

答案 0 :(得分:0)

您可以使用BroadcastReceiver来实现这一目标。请执行以下操作:

  1. 在主要活动中注册BroadcastReceiver:
  2. public static final String UPDATE_ACTION = "yourpackage.update";
    public static final String EXTRA_KEY_AGE = "key_age";
    public static final String EXTRA_KEY_WEIGHT = "key_weight";
    private BroadcastReceiver mReceiver;    
    
    // In the onCreate() method
    mReceiver = new BroadcastReceiver(){
                @Override
              public void onReceive(Context context, Intent intent) {
                    if(intent.getAction().equals(UPDATE_ACTION)){
                        // Here you get the update data from another activity
                        String age = intent.getStringExtra(EXTRA_KEY_AGE);
                        String weight = intent.getStringExtra(EXTRA_KEY_WEIGHT);
                    }
                }
    };
    registerReceiver(receiver, new IntentFilter(UPDATE_ACTION ));
    
    // Add the following code to onDestroy() method
    unregisterReceiver(mReceiver);
    
    1. 在“单独活动”中发送广播:

       public void onClick(View v) {
           weightString = weightText.getText().toString();
           ageString = ageText.getText().toString();
           Intent intent = new Intent(MainActivity.UPDATE_ACTION );
           intent.putExtra(MainActivity.EXTRA_KEY_AGE, ageString);
           intent.putExtra(MainActivity.EXTRA_KEY_WEIGHT, weightString );
           sendBroadcast(intent);    
        }
      
    2. 更新:更改部分代码,以便在销毁活动时取消注册BroadcastReceiver。