我有一个Selectl
宿主 Activity 类表单,我在其中实例化我的AddHttpLinksFragment
.Just 之后我调用 Fragment 的getPls()
方法。只要我没有View
在 Fragments 的getPls()
方法中调用任何元素(小部件、适配器),一切都会正常工作。似乎当我调用这个方法时,片段的视图还没有创建,所以它的小部件是Null
. 我怎样才能防止这种情况?
选择类:
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
AddHttpLinksFragment fragment2 = new AddHttpLinksFragment();
fragmentTransaction.add(R.id.fragment_container1, fragment2, "addlinksF");
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
AddHttpLinksFragment fragment = (AddHttpLinksFragment) getFragmentManager().findFragmentByTag("addlinksF");
fragment.getPls(path);
添加HttpLinksFragmen.class:
public class AddHttpLinksFragment extends android.app.Fragment implements View.OnClickListener {
EditText httpAddressEdit;
EditText linkText;
URI uriPls;
ListView lv;
ArrayList<String> strList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
int itemPosition;
DBHttpLinks db;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.addhttplinksfragment, container, false);
// ListView init
lv = (ListView) v.findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, strList);
lv.setAdapter(arrayAdapter);
return v;
}
// ...
public void getPls(Uri path) {
try {
uriPls = new URI(path.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
PlsReader mPlsReader = new PlsReader(uriPls);
strList.addAll(mPlsReader.Read());
arrayAdapter.notifyDataSetChanged(); // <--- ANR, line 233
TextView tv = (TextView) getActivity().findViewById(R.id.textView_long_press); // <--- ANR
tv.setText(getString(R.string.long_press_to)); // <---ANR
}
// ...
}
日志猫:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.Selectl}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.krisk.astream.AddHttpLinksFragment.getPls(AddHttpLinksFragment.java:233)