关闭应用程序或切换片段时保存值

时间:2018-07-16 23:00:48

标签: android android-studio android-fragments sharedpreferences

我是Android新手,在关闭应用程序时需要保留一个整数weekNumber。我的想法是在处理需要使用该值的片段的活动中设置值,并始终使用getter从那里获取值,但是当我关闭应用程序或切换片段时,即使使用共享首选项。我将保存的数据加载到活动的onCreate中,并将数据保存在onPause中。也许这是错误的。为什么会这样?我将不胜感激,并且希望了解更多信息!

这是我的处理片段的MainActivity:

public class MainActivity extends AppCompatActivity {

private int weekNumber;

private static final String SHARED_PREFS = "sharedPrefs";
private static final String WEEK_NUMBER = "weekNumber";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(navListener);

    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new HomeFragment()).commit();

    loadData();

    }

private BottomNavigationView.OnNavigationItemSelectedListener navListener =
        new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment selectedFragment = null;

                switch (item.getItemId()) {
                    case R.id.nav_home:
                        selectedFragment = new HomeFragment();
                        break;
                    case R.id.nav_add:
                        selectedFragment = new CalculatorFragment();
                        break;
                    case R.id.nav_settings:
                        selectedFragment = new SettingsFragment();
                        break;
                }

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
                return true;
            }
        };



@Override
protected void onPause() {
    super.onPause();
    saveData();
}

public void saveData() {
    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    editor.putInt(WEEK_NUMBER,weekNumber);
    }

public void loadData() {
    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
    weekNumber = sharedPreferences.getInt(WEEK_NUMBER,1);
}

public int getWeekNumber() {
    return weekNumber;
}

public void setWeekNumber(int weekNumber) {
    this.weekNumber = weekNumber;
}

其中一个片段:

public class HomeFragment extends Fragment {

View rootView;

private TextView[] textViews;

MainActivity mainActivity = new MainActivity();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_home,container,false);

    textViews = new TextView[16];

    for(int i=0; i<textViews.length; i++) {
        {
            String buttonID = "textView" + (i+1);

            int resID = getResources().getIdentifier(buttonID, "id", getActivity().getPackageName());
            textViews[i] = ((TextView) rootView.findViewById(resID));
        }
    }

    setWeekText();

    textViews[9].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getActivity(),ActivityDay1.class));
        }
    });

    Button buttonNextWeek = rootView.findViewById(R.id.buttonNextWeek);
    buttonNextWeek.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mainActivity.setWeekNumber(mainActivity.getWeekNumber()+1);
            setWeekText();
        }
    });

    return rootView;
}

private void setWeekText() {
    textViews[8].setText(String.valueOf(mainActivity.getWeekNumber()));
}

2 个答案:

答案 0 :(得分:1)

editor.apply();函数末尾调用saveData,以将值实际保存在SharedPreferences中。

此外,您不能在片段中调用MainActivity mainActivity = new MainActivity();。在onCreateView中或直接在onClick侦听器中使用mainActivity = getActivity();进行设置。

为什么?您所拥有的将在该片段内创建一个新的MainActivity实例,而不是引用您在其上设置了所需数据的那个实例。

此外,如果您保留当前的设计,则在创建活动之前尝试访问片段的片段loadData 中调用onCreate可能更安全。数据。

也许更好的选择是直接在片段中直接使用共享首选项。

答案 1 :(得分:0)

几件事。

  1. 您需要确保实际保存了数据。在您的editor.commit()中添加saveData()
  2. 您应该在onSaveInstance中保存并在onSaveInstance中进行恢复,因为这是当系统在内存不足等情况下杀死您的活动时android会调用的