I want to run an instance of fragment from activity. But it returns error null object reference.
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mani.view.StaggeredGridView.addItem(com.mani.view.StaggeredGridViewItem)' on a null object reference
at com.example.myapp.FavouriteListFragment.onCreateView(FavouriteListFragment.java:57)
When i debug, this line shows null pointer error
mStaggeredView.addItem(item);
debug result shows that fragmentClass is null value. It does not works well now after I have added inheritance class in my fragment. Here is my fragment
public class FavouriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
private SharedPreference sharedPreference;
private StaggeredGridView mStaggeredView;
TextView tv;
ImageView iv;
String text;
String favouriteUrl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favourite_staggeredgridview, container, false);
sharedPreference = new SharedPreference();
iv=(ImageView)rootView.findViewById(R.id.imageView);
text = sharedPreference.getValue(getActivity());
sharedPreference.saveFavourite(getActivity(), text);
String[] photoUrl;
photoUrl = new String[10];
for (int index = 0; index < photoUrl.length; index++) {
photoUrl[index]=text;
StaggeredGridViewItem item = null;
item = new FavouriteGridItem(getActivity(),photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
URL url = null;
try {
url = new URL(text);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
iv.setImageBitmap(bmp);
return rootView;
}
}
答案 0 :(得分:1)
这一行是你的一个问题:
mStaggeredView.addItem(item);
根据您发布的代码,您在mStaggeredView.addItem()
上获得nullpointer是合乎逻辑的,因为您没有为mStaggeredView
分配任何内容。您必须在某处{/ 1}}执行某些操作