我试图用片段的onSaveInstanceState()来保存变量的状态。我尝试保存的变量是在我的程序中的另一个类中创建的,但它总是被读为0(初始值)。我知道我正在增加变量值。 如何获得变量的实际值?这是我的代码:
public class ObjectivesActivity extends Fragment {
//Variables
ObjectivesLogic objectivesLogic = new ObjectivesLogic();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
System.out.println("savedInstanceState: " + savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_objectives, container, false);
}
@Override
public void onStart() {
super.onStart();
if (objectivesLogic.getCount()>0){
objectivesLogic.restoreFragment();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int save = objectivesLogic.getCount();
System.out.println("save: "+save);
outState.putInt("Count",save);
}
}
这就是我创建变量的地方:
public class ObjectivesLogic extends AppCompatActivity {
//Variables
int count = 0;
View savedLinearLayoutView = null;
Context savedContext = null;
public void addObjective(Context context, View linearLayoutView) {
savedContext = context;
savedLinearLayoutView = linearLayoutView;
if (count < 8) {
EditText editText = new EditText(context);
LinearLayout linearLayoutObjectives = (LinearLayout) linearLayoutView;
editText.setId(R.id.edit_text_);
linearLayoutObjectives.addView(editText);
count++;
}
}
public void restoreFragment(){
for(int i=0; i<count;i++){
EditText editText = new EditText(savedContext);
LinearLayout linearLayoutObjectives = (LinearLayout) savedLinearLayoutView;
editText.setId(R.id.edit_text_);
linearLayoutObjectives.addView(editText);
count++;
}
}
public int getCount() {
return count;
}
}
getCount()始终为0。 谢谢你的帮助:))
答案 0 :(得分:1)
我在您的代码中看到的两个问题应该解决。
ObjectivesLogic
类正在扩展Activity
类,这看起来并不需要。此外,你永远不应该手动实例化一个扩展Activity
的类,这应该由Android框架完成而不是你。
您只保存该变量:outState.putInt("Count",save);
。我看不出任何关于恢复它的事情。
答案 1 :(得分:0)
您在super.onSaveInstanceState(outState);
outState.putInt("Count",save);
@Override
public void onSaveInstanceState(Bundle outState) {
int save = objectivesLogic.getCount();
System.out.println("save: "+save);
outState.putInt("Count",save);
super.onSaveInstanceState(outState);
}