我正在使用 GridView 将动态数据加载到我的活动中:
private ArticuloAdapter articuloAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_articulos);
// get ListaArticulos from the database
articuloAdapter = new ArticuloAdapter(this,R.layout.lista_articulo, ListaArticulos);
grdArticulos.setAdapter(articuloAdapter);
}
我想在方向改变后恢复数据:
ArrayList<String> articulosBackup = new ArrayList<String>();
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int size = grdArticulos.getChildCount();
for(int i = 0; i < size; i++) {
ViewGroup layout = (ViewGroup) this.grdArticulos.getChildAt(i);
ViewGroup gridChild = (ViewGroup) layout.getChildAt(1);
EditText et =(EditText)gridChild.getChildAt(0).findViewById(R.id.Cantidad);
EditText et2 = (EditText)gridChild.getChildAt(1).findViewById(R.id.jaulas);
EditText et3 =(EditText)gridChild.getChildAt(2).findViewById(R.id.contenedores);
CheckBox cb = (CheckBox)gridChild.getChildAt(3).findViewById(R.id.manipulado);
String dato = et.getText().toString() + ":" + et2.getText().toString() + ":" + et3.getText().toString() + ":" + String.valueOf(cb.isChecked());
articulosBackup.add(dato);
}
outState.putSerializable("articulosBackup", articulosBackup);
outState.putInt("items", size);
}
我将数据保存在 ArrayList 中,例如字符串,格式为:data1:data2:data3:data4。这很好用。但是现在当我尝试恢复它们时,我在注释的行中得到了 NullPointerException:
@SuppressWarnings("unchecked")
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
articulosBackup = (ArrayList<String>)savedInstanceState.getSerializable("articulosBackup");
items = savedInstanceState.getInt("items");
if (articulosBackup != null) {
for(int i = 0; i < items; i++) {
ViewGroup layout = (ViewGroup) grdArticulos.getChildAt(i);
ViewGroup gridChild = (ViewGroup) layout.getChildAt(1); // NULLPOINTEREXECPTION: layout variable is null
String datos[] = articulosBackup.get(i).split(":");
// Cantidad
EditText et =(EditText)gridChild.getChildAt(0).findViewById(R.id.Cantidad);
et.setText(datos[0]);
// Jaulas
EditText et2 = (EditText)gridChild.getChildAt(1).findViewById(R.id.jaulas);
et2.setText(datos[1]);
// Contenedores
EditText et3 =(EditText)gridChild.getChildAt(2).findViewById(R.id.contenedores);
et3.setText(datos[2]);
// Manipulado
CheckBox cb = (CheckBox)gridChild.getChildAt(3).findViewById(R.id.manipulado);
cb.setChecked(Boolean.parseBoolean(datos[3]));
}
}
}
所以我的问题是:如何在方向改变后恢复我的动态 GridView?谢谢。