我正在创建的应用程序有问题。
我在一个主 Activity 中创建了一系列 fragment 。
在每个 Fragment 中,要么是一个用于数据收集的表单,要么是一个用于显示收集到的数据的 ListView。
数据操作由几个小部件的监听器方法和幕后的数据模型控制。
基本上,我使用数据收集 fragment 将数据存储在 SQLite 数据库中,然后在前往显示 fragment 时对其进行查询。显示 fragment 具有用于返回集合 fragment 以添加、编辑或删除选定项目的按钮。在按下添加/编辑按钮的情况下,我会在某些状态下发送一个 bundle ,该 bundle 可以根据用户的需要进行不同的填充。通常,一个包包含从父上下文发送到子上下文的信息,子上下文在该子上下文上解包包并将数据放置在文本字段中和/或设置包含静态数据的微调器。
我尝试使用一种过于复杂的方法,直接在正在使用的任何小部件监听器中创建一个新的 Bundle。
但我发现它在以下 fragment 中创建了不必要的复杂性,我需要测试来自几个不同可能来源的 bundle 中包含的键。
我的想法是在我会调用的任何 Fragment 的开头Bundle bundle = this.getArguments()
这将设置 bundle
传递给传入的任何 Bundle:fragment.setArguments(*bundle based on conditions*)
因此,从这个流程中,我必须创建一个非常长且难以阅读的 if 条件序列,以查找基于 bundle.isEmpty()
的特定键。如果您是第一次到达该 Fragment 并且尚未发送任何包,那么这当然会引发 NullPointerException。
然后为了使噩梦更加复杂,我将所有这些都放入了 try-catch 中以处理 bundle.isEmpty() 空指针,我试图将其用作当前状态的指示器(/sigh ...我知道)。
我想做的是使用 Bundle savedInstanceState
对于任何信息/状态流量到一个新的 fragment 。
所以理想情况下,我只需要访问一个 Bundle 并测试包含 key 。
那么看来我可以测试是否savedInstanceState
为空并以某种方式设置它。
问题是我的 fragment 中有这些小部件,我用它们来与我的模型交互并可能导航到下一个必要的 fragment 。
如果我使用 savedInstanceState
在 onClick
内其中一个小部件的监听器方法,我被迫使其 final
这立即使我无法使用 savedInstanceState
在任何其他范围内,但它的初始用法或至少这是我的理解。
当我尝试访问 savedInstanceState
时,这会导致 NullPointerException 错误在第一个范围之外。
如果我删除 final
IDE 告诉我(正确地)我无法访问 savedInstanceState
从内部类中,在我的例子中是几个小部件,我附加了监听器方法。
我读过了:
Are the bundles in android permanent in saving activity states ?
How to use the anonymous inner class?
How to use Outer Method's input in Anonymous Inner Class?
这是两个依赖于相互发送 Bundle 的 Fragment 的代码示例;
显示和选择类:
public class Row_main extends Fragment {
Spinner location_spinner;
Button add_row_btn,edit_row_button,delete_row_btn;
ListView row_list_holder;
StorageHandler sh;
List<Row> row_list;
ArrayAdapter<CharSequence> ls_adapter;
String [] location_test_values = {"test_location"};
boolean has_items;
public Row_main()
{
//default constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
if(savedInstanceState == null)
{
//this will satisfy if arriving here from navigation menu.
//I would like to set savedInstanceState here if null.
savedInstanceState = new Bundle();
//but I get error: 'cannot assign a value to final variable'
}
getActionBar().setTitle("Row");
//Create view
final View v = inflater.inflate(R.layout.row_main_layout, container, false);
add_row_btn = (Button) v.findViewById(R.id.add_row_btn);
edit_row_button = (Button) v.findViewById(R.id.edit_row_btn);
delete_row_btn = (Button) v.findViewById(R.id.delete_row_btn);
add_row_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addRow fragment = new addRow();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragment.setArguments(savedInstanceState);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("Add Row");
}
});
edit_row_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0; i<row_list.size(); i++)
{
if(row_list.get(i).isSelected())
{
row_list.get(i).setEdited(true);
addRow fragment = new addRow();
savedInstanceState.putStringArrayList("current_row",row_list.get(i).getList());
fragment.setArguments(savedInstanceState);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("Add Row");
}
}
}
});
return v;
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
这是数据收集表单类:
public class addRow extends Fragment {
IdGenerator generator;
String new_id;
AlertDialog.Builder alertDialogBuilder, fmdDialogBuilder;
EditText row_name,
rack_name,
tile_location,
tile_name,
separation,
bf_offset;
Spinner object_type,
direction,
rotation;
ArrayAdapter<CharSequence> objType_adapter,
direction_adapter,
rotation_adapter;
String[] objtype_values = {"Rack","FMD"};
String[] direction_values = {"Right","Left"};
String[] rotation_values = {"0","90","180","270"};
int RACK = 0,FMD = 1,RIGHT = 0,LEFT = 1;
Row current_row;
ArrayList<String> list_to_unpack;
Button save_row_btn,
add_btn,
cancel_btn;
public addRow() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.add_row_layout, container, false);
generator = new IdGenerator();
new_id = generator.randomString(5);
if(savedInstanceState != null)
{
//Bundle passed, edit button was used, unpack
if (savedInstanceState.containsKey("current_row")) {
Log.d("BUNDLE-CONTENTS", "" + savedInstanceState.size());
list_to_unpack = savedInstanceState.getStringArrayList("current_row");
current_row.setId(list_to_unpack.get(0));
current_row.setRow_name(list_to_unpack.get(1));
current_row.setObject_type(list_to_unpack.get(2));
current_row.setRack_name(list_to_unpack.get(3));
current_row.setTile_location(list_to_unpack.get(4));
current_row.setTile_name(list_to_unpack.get(5));
current_row.setDirection(list_to_unpack.get(6));
current_row.setRotation(list_to_unpack.get(7));
current_row.setSeparation(list_to_unpack.get(8));
current_row.setBf_offset(list_to_unpack.get(9));
current_row.setEdited(true);
row_name.setText(current_row.getRow_name());
if (current_row.getObject_type().equalsIgnoreCase("Rack")) {
object_type.setSelection(RACK);
} else {
object_type.setSelection(FMD);
}
rack_name.setText(current_row.getRack_name());
tile_location.setText(current_row.getTile_location());
tile_name.setText(current_row.getTile_name());
if (current_row.getDirection().equalsIgnoreCase("Right")) {
direction.setSelection(RIGHT);
} else {
direction.setSelection(LEFT);
}
switch(current_row.getRotation())
{
case "0": rotation.setSelection(0); break;
case "90": rotation.setSelection(1); break;
case "180": rotation.setSelection(2); break;
case "270": rotation.setSelection(3); break;
}
separation.setText(current_row.getSeparation());
bf_offset.setText(current_row.getBf_offset());
}
}
row_name = (EditText) v.findViewById(R.id.rowName_value);
rack_name = (EditText) v.findViewById(R.id.rackName_value);
tile_location = (EditText) v.findViewById(R.id.tileLoc_value);
tile_name = (EditText) v.findViewById(R.id.tileName_value);
separation = (EditText) v.findViewById(R.id.separation_value);
bf_offset = (EditText) v.findViewById(R.id.bfOffset_value);
object_type = (Spinner) v.findViewById(R.id.obj_type);
direction = (Spinner) v.findViewById(R.id.direction);
rotation = (Spinner) v.findViewById(R.id.rotation_spinner);
objType_adapter = new ArrayAdapter<CharSequence>(this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, objtype_values);
direction_adapter = new ArrayAdapter<CharSequence>(this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, direction_values);
rotation_adapter = new ArrayAdapter<CharSequence>(this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, rotation_values);
object_type.setAdapter(objType_adapter);
direction.setAdapter(direction_adapter);
rotation.setAdapter(rotation_adapter);
save_row_btn = (Button) v.findViewById(R.id.save_row_btn);
add_btn = (Button) v.findViewById(R.id.add_btn);
cancel_btn = (Button) v.findViewById(R.id.cancel_btn);
alertDialogBuilder = new AlertDialog.Builder(getActivity());
fmdDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("Add Rack or FMD:");
fmdDialogBuilder.setMessage("Add Power Providing or Power Consuming FMD:");
alertDialogBuilder.setNegativeButton("Rack", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//if user selects power providing fmd
//send id with it
//StorageHandler sh = new StorageHandler(getActivity());
Row row = new Row(
new_id,
row_name.getText().toString(),
object_type.getSelectedItem().toString(),
rack_name.getText().toString(),
tile_location.getText().toString(),
tile_name.getText().toString(),
direction.getSelectedItem().toString(),
rotation.getSelectedItem().toString(),
separation.getText().toString(),
bf_offset.getText().toString());
ArrayList<String> rowList = row.getList();
for(String i : rowList)
{
Log.d("ADD ROW BTN","rowList[i]=" + i);
}
savedInstanceState.putStringArrayList("current_row", rowList);
addRack fragment = new addRack();
fragment.setArguments(savedInstanceState);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("Add Rack to: " + row.getRow_name());
}
});
alertDialogBuilder.setPositiveButton("FMD", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//todo choice between consuming and providing
fmdDialogBuilder.show();
}
});
fmdDialogBuilder.setPositiveButton("Providing", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Row row = new Row(
new_id,
row_name.getText().toString(),
object_type.getSelectedItem().toString(),
rack_name.getText().toString(),
tile_location.getText().toString(),
tile_name.getText().toString(),
direction.getSelectedItem().toString(),
rotation.getSelectedItem().toString(),
separation.getText().toString(),
bf_offset.getText().toString());
ArrayList<String> obj_as_list = row.getList();
Log.d("newId", obj_as_list.get(0));
Log.d("row_name", obj_as_list.get(1));
Log.d("object_type", obj_as_list.get(2));
Log.d("rack_name", obj_as_list.get(3));
Log.d("objaslistsize", ""+obj_as_list.size());
savedInstanceState.putStringArrayList("current_row", obj_as_list);
addPowerProvidingFMD fragment = new addPowerProvidingFMD();
fragment.setArguments(savedInstanceState);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("add FMD to: " + row_name.getText().toString());
}
});
fmdDialogBuilder.setNegativeButton("Consuming", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Row row = new Row(
new_id,
row_name.getText().toString(),
object_type.getSelectedItem().toString(),
rack_name.getText().toString(),
tile_location.getText().toString(),
tile_name.getText().toString(),
direction.getSelectedItem().toString(),
rotation.getSelectedItem().toString(),
separation.getText().toString(),
bf_offset.getText().toString());
ArrayList<String> obj_as_list = row.getList();
savedInstanceState.putStringArrayList("current_row", obj_as_list);
addPowerConsumingFMD fragment = new addPowerConsumingFMD();
fragment.setArguments(savedInstanceState);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("add FMD to: " + row_name.getText().toString());
}
});
save_row_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//save row info to database
StorageHandler sh = new StorageHandler(getActivity());
if(current_row.isEdited())
{
//update row
String current_id = current_row.getId();
Log.d("*update row*", "id=" + current_id);
//get updated values from fields, send to database
Row row = new Row(current_id, row_name.getText().toString(), object_type.getSelectedItem().toString(),
rack_name.getText().toString(), tile_location.getText().toString(),
tile_name.getText().toString(), direction.getSelectedItem().toString(),
rotation.getSelectedItem().toString(), separation.getText().toString(),
bf_offset.getText().toString());
sh.updateRow(row);
sh.close();
}
else
{
//save new row
Log.d("*save row*", "id=" + new_id);
//save row to database
sh.addRow(new Row(new_id, row_name.getText().toString(), object_type.getSelectedItem().toString(),
rack_name.getText().toString(), tile_location.getText().toString(),
tile_name.getText().toString(), direction.getSelectedItem().toString(),
rotation.getSelectedItem().toString(), separation.getText().toString(),
bf_offset.getText().toString()));
sh.close();
}
Row_main fragment = new Row_main();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("Row");
}
});
add_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialogBuilder.show();
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Row_main fragment = new Row_main();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("Row");
}
});
return v;
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
我想在这里使用 bundle ,因为如果用户离开应用程序或按下后退按钮,从 bundle 中恢复任何内容并不重要。
我这样做对吗?
onClickListener
中的最终 Bundle 情况我该怎么办?方法?我绝对需要按照我现在设置的方式从他们那里传递 bundle ,如果可以的话,我想使用相同的 bundle 。我有一个要考虑的最后期限,所以彻底检修可能是不可能的。
非常感谢任何输入。
最佳答案
我认为一旦你重构了一些代码,隔离你的数据传递问题会更容易。
1. 用方法替换这些类似的 block 。您似乎已经将同样的代码复制了大约五次。
让它成为一种方法!调用 getRow()
,如果必须的话,给它一个参数,比如 int id
.
// int id = <some_value>;
return new Row(id, row_name.getText().toString(), object_type.getSelectedItem().toString(),
rack_name.getText().toString(), tile_location.getText().toString(),
tile_name.getText().toString(), direction.getSelectedItem().toString(),
rotation.getSelectedItem().toString(), separation.getText().toString(),
bf_offset.getText().toString());
2. 现在,您似乎正在绕过这个
Row
类,所以建议做 implement Parcelable
这样您就可以更轻松地在 Bundle
之间传递s 需要时。3. 接下来,您应该 let the Fragment interactions happen across the Activity boundary ,而不是来自每个 fragment 内。因此,例如,您添加接口(interface)。如果您不需要所有这些功能,您可以将其拆分为许多接口(interface)。
public interface OnRowInteractionListener {
public void onRowAdded(Row row);
public void onRowEdited(Row row);
public void onRowRemoved(Row row);
public void onRowActionCancel();
}
3a。 实现
onAttach
Fragment 类来设置这些接口(interface)。private OnRowInteractionListener mListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
final String contextName = context.class.getSimpleName();
try {
mListener = (OnRowInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(contextName + " must implement OnRowInteractionListener");
}
}
3b。 现在,清理 Fragment 按钮
add_row_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Row added = getRow(); // remember about that parameter value
if (mListener != null) mListener.onRowAdded(added);
}
});
3c。 在Activity中,你需要在创建类
implements OnRowInteractionListener
之后实现这些接口(interface)。 .@Override
public void onRowAdded(Row row) {
getActionBar().setTitle("Add Row");
// This acts like your 'constructor'
AddRowFragment fragment = AddRowFragment.newInstance(row);
// fragment.setArguments(savedInstanceState);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
(与
onRowEdited
类似)4. 我还看到这个 fragment 替换代码块对取消和保存按钮重复,所以也把它作为一个方法。
Row_main fragment = new Row_main();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
getActionBar().setTitle("Row");
我真的建议您在 Activity 中创建一个非常通用的方法来处理所有 fragment 转换。
public void transitionFragment(Fragment fragment, Bundle arguments, String title) {
getSupportActionBar().setTitle(title);
if (arguments != null) fragment.setArguments(arguments);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
然后,只需传入相应的
newInstance()
'd Fragment 到该方法,只要你需要它。可选地传递额外的参数,否则,只是 null
.因此,您现在可以在前面的代码块中使用该方法,例如,在接口(interface)实现的取消操作中。
@Override
public void onRowActionCancel() {
Fragment fragment = RowMainFragment.newInstance();
transitionFragment(fragment, null, "Add Row");
}
就 SQLite 处理而言,可以查看 RealmDB、SugarORM 或任何 ORM 库。
findViewById
可以使用 Butterknife 简化代码。此外,Android Data Binding library如果您经常将数据从 Java 对象映射到 View 对象。
关于java - 如何在监听器中正确使用 bundle (匿名内部类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411385/