【发布时间】:2014-04-13 06:49:25
【问题描述】:
在我的应用程序中,数据正在加载,同时显示启动画面。完成后,用户可以输入显示在片段中的新数据并插入到数据库中。此外,用户输入的新数据允许计算一个变量,该变量也显示在自定义视图中(在片段中)并插入到数据库中。所以,在初始屏幕之外,我只使用db.insert()。
我有几个片段,当我从一个片段切换到另一个片段而不使用db.get() 调用数据库时,我想恢复我的数据
现在,当我切换到另一个片段(使用导航抽屉)并返回上一个片段时,我的数据不再显示...
确实,我想在应用运行时限制对数据库的调用。
更新
稍微更新一下更明确:)
我有一个处理导航抽屉的活动。目前,我在 2 个片段(Frag1 和 Frag2)之间切换。
在第一个片段中,我有一个自定义视图(例如命名为 CustomView1)和一些 TextView(TextView1 和 TextView2)。 通过操作栏中的项目,用户可以更新 TextView1。为 TextView1 设置的值也插入到数据库中。 TextView2 会自动更新为 TextView1 的先前值,如下所示:
/**
* Listener to see if TextView1 change
**/
TextView1.addTextChangedListener(new TextWatcher() {
String X;
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
X = charSequence.toString();
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable editable) {
TextView2.setText(X);
}
});
当我切换到 Frag2 并返回到 Frag1 时,TextView1 和 TextView2 为空,没有任何显示。
我尝试像这样使用onSaveInstanceState:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putFloat("mTextView1", mTextView1);
savedInstanceState.putFloat("mTextView2", mTextView2);
}
在 onCreateView 中:
if(savedInstanceState != null) {
// Restore last state
mTextView1 = savedInstanceState.getFloat("mTextView1");
mTextView2= savedInstanceState.getFloat("mTextView2");
}
我的 savedInstanceState 总是返回 null...
这就是我在片段之间切换的方式:
private void selectItem(int position) {
// update the main content by replacing fragments
switch(position){
case 0:
Fragment1 Frag1 = new Fragment1();
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
fragTransaction.replace(R.id.content_frame,Frag1,"TAG1");
fragTransaction.commit();
break;
case 1:
Fragment2 Frag2 = new Fragment2 ();
FragmentTransaction fragTransaction1 = getSupportFragmentManager().beginTransaction();
fragTransaction1.replace(R.id.content_frame,Frag2,"TAG2");
fragTransaction1.commit();
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mSection[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
解决方案
我在用户操作期间使用SharedPreference 来存储我想要的数据(而且这些数据是插入到数据库中的)
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("mKey1", value1);
editor.commit();
在 onCreate 中,我得到了之前存储的数据:
sharedPref = this.getActivity().getPreferences(Context.MODE_PRIVATE);
if(sharedPref!=null) {
variable1 = sharedPref.getFloat("mKey1",DEFAULT_VALUE);
}
TextView1.setText(String.valueOf(variable1));
随着 TextView1 的更新,TextView2 也随之更新,侦听器采用 TextView1 的先前值。
【问题讨论】:
-
你是如何切换的?我的意思是使用 fragment.attach() & .detach、.add() & .remove() 或 .show() & .hide()。你用的是哪一个?尝试使用其他人并进行测试。
-
我使用 .replace()。我会测试其他人。