我已就此问题做了大量研究,但我无法解决此错误。在Internet上,人们建议使用findFragmentBy ID或Tag,但这两者都会导致空指针异常。 这是我写的代码:
这是托管此更新按钮的主要片段。按照预期,此按钮打开一个对话框以选择日期或时间,然后激发另一个允许用户编辑日期或时间的对话框。我在这里设置setTargetFragment。
updateInfo= (Button) v.findViewById(R.id.update_info);
...// Code to display date on button(unnecessary code)
updateInfo.setText(currentData+" "+currentDataTime);
updateInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm=getActivity().getSupportFragmentManager();
Date date=crime.getDate();
UpdateSelector updateSelector=UpdateSelector.newInstance(date);
updateSelector.setTargetFragment(CrimeFragment.this,getRequest_code_updateSelector);
updateSelector.show(fm,Update_Selector);
}
});
以下是updateSelector类的代码
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
... //unnecessary code
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (selected == 0) {
FragmentManager fm = getActivity().getSupportFragmentManager();
DatePickerFragment datePicker = DatePickerFragment.newInstance(date);
datePicker.show(fm, datepickertag);
}
if (selected == 1) {
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment timePicker = TimePickerFragment.newInstance(date);
timePicker.show(fm, timepickertag);
}
}
});
return builder.create();
}
public void sendResult(int resultCode)
{
if(getTargetFragment== null)
return;
Intent intent=new Intent();
date= (Date) getArguments().getSerializable(tag);
intent.putExtra(tag, date);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
//New Instance method to create instance
我设计了datePickerFragment和TimePickerFragment,打开第二个对话框(Spinner进行编辑)。因此,我正在使用它们将结果发送到CrimeFragment。
public class DatePickerFragment extends DialogFragment {
public final static String Extra_Date="date";
private Date date;
UpdateSelector update;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
//Setup of dialog elements and get date (Unnecessary code)
return new AlertDialog.Builder(getActivity()).setView(view).setTitle(R.string.date_picker).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
update.sendResult(Activity.RESULT_OK);
}
}).create();
}
现在,update.sendResult(Activity.OK)将结果发送到此方法
public void sendResult(int resultCode)
{
if(getTargetFragment== null)
return;
Intent intent=new Intent();
date= (Date) getArguments().getSerializable(tag);
intent.putExtra(tag, date);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
其中fragment是null。请详细解释。感谢