null object reference on fragment new instance - android

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;
}
}

This line is one of your problems:
mStaggeredView.addItem(item);
From the code you posted it is logical that you get a nullpointer on mStaggeredView.addItem() because you did not assign anything to mStaggeredView. You must do something like mStaggeredGridView = (StaggeredGridView) rootView.findViewById(R.id.some_id) somewhere

Related

Why the view is null outside onCreateView

I declare a view variable in the class and assign its value in OnCreateView using findviewbyid as usual, and I use an interface to interact between this fragment and another one, when the other fragment interacts with this fragment using a method called "ask" in which the local variable is invoked, I find that the variable is null Here is the variable
private TextInputLayout questionLayout;
Here I assign its value
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_article_, container, false);
Button ask = v.findViewById(R.id.ask);
questionLayout = v.findViewById(R.id.QuestionInputLayoutArticle);
if(questionLayout == null){
Log.d("ORDERARTICLE","QUESTION");
}
Log.d("ORDERORDER","CreateView");
return v;
}
Here is the method
#Override
public boolean ask() {
Log.d("ORDERORDER","ASK");
if(questionLayout == null){
Log.d("ORDERARTICLE","QUESTION");
}
if(questionLayout.getEditText().getText().toString().isEmpty()){
return false;
}else {
FirebaseFirestore Fs = FirebaseFirestore.getInstance();
Map<String, String> QuestionMap = new HashMap<>();
QuestionMap.put("Head", questionLayout.getEditText().getText().toString());
QuestionMap.put("Type", "Article");
Fs.collection("Questions").document().set(QuestionMap);
return true;
}
}
You can note that I am logging to make sure that the value is assigned before invoking the variable and it's assigned before invoking indeed

How use a fragment with recyclerview?

how I can solve the error and app crashing when I try to use the code:
Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
I try to show a recyclerview in a fragment but when I use the code below got an error and app crash.
Can anyone help me to solve=
public class dashboard_device extends Fragment{
RecyclerView mRecicleView1;
RecyclerView.LayoutManager mLayoutManager1;
RecyclerView.Adapter mAdapter1;
ArrayList<String> lista_show;
String preadd;
public dashboard_device() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> lista_show = new ArrayList<String> ();
dashboard_DB db1 = new dashboard_DB (getContext ());
//recupero datbase DB
db1.open();
Cursor c = db1.ottieniTuttidati();
if (c.moveToFirst()) {
do {
lista_show.add (c.getString(2));
} while (c.moveToNext());
}
db1.close();
//fine recupero dati da db
// Inflate the layout for this fragment
mRecicleView1=container.findViewById (R.id.Reclycler_dashboard);
mRecicleView1.setHasFixedSize (true);
mLayoutManager1 = new GridLayoutManager (getContext (),3);
mAdapter1 = new adapter_dash (lista_show,getContext ());
mRecicleView1.setLayoutManager (mLayoutManager1);
mRecicleView1.setAdapter (mAdapter1);
runanimation1(mRecicleView1,0);
Log.d("tag", String.valueOf (lista_show));
return inflater.inflate (R.layout.dashboard_device_layout, container, false);
}
private void runanimation1(RecyclerView mRecicleView, int type) {
Context context=mRecicleView.getContext ();
LayoutAnimationController controller = null;
if(type==0)
controller = AnimationUtils.loadLayoutAnimation (context,R.anim.layout_animation);
mRecicleView.setLayoutAnimation (controller);
mRecicleView.getAdapter ().notifyDataSetChanged ();
mRecicleView.scheduleLayoutAnimation ();
}
}
You are trying to access view elements before it's being created.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate (R.layout.dashboard_device_layout, container, false);
ArrayList<String> lista_show = new ArrayList<String> ();
dashboard_DB db1 = new dashboard_DB (getContext ());
//recupero datbase DB
db1.open();
Cursor c = db1.ottieniTuttidati();
if (c.moveToFirst()) {
do {
lista_show.add (c.getString(2));
} while (c.moveToNext());
}
db1.close();
//fine recupero dati da db
// Inflate the layout for this fragment
mRecicleView1=fragmentView.findViewById (R.id.Reclycler_dashboard);
mRecicleView1.setHasFixedSize (true);
mLayoutManager1 = new GridLayoutManager (getContext (),3);
mAdapter1 = new adapter_dash (lista_show,getContext ());
mRecicleView1.setLayoutManager (mLayoutManager1);
mRecicleView1.setAdapter (mAdapter1);
runanimation1(mRecicleView1,0);
Log.d("tag", String.valueOf (lista_show));
return fragmentView;
}
More over you should not do db operation in OnCreateView as its creates blanks screen effect as you will be returning view after querying the db.

How to get context for Gilde from interface

I'm trying to use Glide to load a picture. Glide needs context/fragment/activity/view...
I have fragment, and in the fragment i implenet interface. The data that i receive is from the MainActivity and it transfer by the interface.
The data that i transfer is image path, and with this image path i want to load with Glide.
The problem is that i need context/fragment/activity/view for the Glide.
For example
public class MyAccountFragment extends Fragment implements View.OnClickListener,
ChangeProfileImgDialog.OnPhotoReceivedListener{
#Override
public void getImagePath(Uri imagePath) {
if( !imagePath.toString().equals("")){
mSelectedImageUri = imagePath;
mSelectedImageBitmap = null;
Log.d(TAG, "getImagePath: got the image uri: " + mSelectedImageUri);
Glide.with(**What should i do here **).load(imagePath).into(cvUserProfileImage);
}
}
#Override
public void getImageBitmap(Bitmap bitmap,Context context) {
if(bitmap != null){
mSelectedImageUri = null;
mSelectedImageBitmap = bitmap;
Log.d(TAG, "getImageBitmap: got the image bitmap: " + mSelectedImageBitmap);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_my_account, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
Well thats the code, i have tried several things but nothing worked.
I always got null. How can i resolve that problem?
Just use the fragment's getContext() method to get your context. This will be the host activity (same as calling getActivity(), it's just cast as a context).
Neither of these methods will work if called before the fragment's onAttach method has been called. onAttach will be called when the fragment is attached to your activity. Before this, it cannot get a context. I would recommend having your interface method save the uri to a local variable and then you can make the call to load it after or inside of onAttach.
However, if cvUserProfileImage is a part of your fragment, you'll need to do this after you inflate your layout in onCreateView. Otherwise, it won't have been created yet. I am not sure where you are getting that variable from.
Code would look something like:
public class MyAccountFragment extends Fragment implements View.OnClickListener,
ChangeProfileImgDialog.OnPhotoReceivedListener {
private Uri mSelectedImageUri;
private Bitmap mSelectedImageBitmap;
private ImageView cvUserProfileImage;
#Override
public void getImagePath(Uri imagePath) {
if (!imagePath.toString().equals("")) {
mSelectedImageUri = imagePath;
mSelectedImageBitmap = null;
Log.d(TAG, "getImagePath: got the image uri: " + mSelectedImageUri);
}
}
#Override
public void getImageBitmap(Bitmap bitmap, Context context) {
if (bitmap != null) {
mSelectedImageUri = null;
mSelectedImageBitmap = bitmap;
Log.d(TAG, "getImageBitmap: got the image bitmap: " + mSelectedImageBitmap);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_my_account, container, false);
cvUserProfileImage = v.findViewById(R.Id.cvUserProfileImage);
if (mSelectedImageUri != null) {
Glide.with(getContext()).load(mSelectedImageUri).into(cvUserProfileImage);
} else if (mSelectedImageBitmap != null){
cvUserProfileImage.setImageBitmap(mSelectedImageBitmap);
}
return v;
}
}

ListView in Fragment in ViewPager Only Showing New Values After Screen Orientation Changes Twice

In my app I have a ViewPager with four fragments one of which contains a ListView which I dynamically add too at certain points using an update method that recreates the adapter. When the fragment is first loaded it displays all items perfectly but when I do operations later on, which add views to a list which is used to create the Fragment's ListView's adapter, the new items are not shown (or removed). Does anybody know why this occurs.
The Fragment with the ListView:
public static class FavoritesFragment extends Fragment
{
ListView list;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
update();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View lv = inflater.inflate(R.layout.fragment_favorites, null);
ListView list = (ListView) lv.findViewById(R.id.favorite_list);
SeparatedListAdapter mAdapter = new SeparatedListAdapter(getActivity(), favoriteList);
list.setAdapter(mAdapter);
return list;
}
public static FavoritesFragment newInstance(String text)
{
FavoritesFragment f = new FavoritesFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
The update method:
public static void update() {
favoriteList = new ArrayList<SeparatedListAdapter.Item>();
sections = new ArrayList<String>();
ListMultimap<String, JSONObject> listObjects = ArrayListMultimap.create();
try {
JSONObject obj = new JSONObject(loadJSONFromAsset(con));
JSONArray m_jArry = obj.getJSONArray("Locations");
for (int i = 0; i < m_jArry.length(); i++)
{
JSONObject jo_inside = m_jArry.getJSONObject(i);
if (favorites.contains(jo_inside.getString("Unique")))
{
listObjects.put(jo_inside.getString("Section"), jo_inside);
if (!sections.contains(jo_inside.getString("Section"))) sections.add(jo_inside.getString("Section"));
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
for (String s : sections)
{
favoriteList.add(new SeparatedListAdapter.SectionItem(s));
List<JSONObject> objectsInSection = listObjects.get(s);
for (JSONObject j : objectsInSection)
{
try {
favoriteList.add(new SeparatedListAdapter.EntryItem(j.getString("name");
}
catch (JSONException e)
{
}
}
}
}
When page is changed to Fragment with ListView:
View vc = mPager.findViewWithTag("favorites");
if (vc != null) {
ListView lv = (ListView) vc.findViewById(R.id.favorite_list);
update();
lv.setAdapter(new SeparatedListAdapter(MainActivity.this, favoriteList));
}
Sorry for the long post but any help would be really appreciated :)
have you tried calling this:
have mAdapter be an instance variable instead of instantiating it in the onCreateView
mAdapter.notifyDataSetChanged();
EDIT:::
what if you did something like this?
mAdapter.clear();
mAdapter.addAll(favoriteList);

trouble loading JSON in AsyncTask in Fragment

I got 3 swipeable empty Views. The 3rd View is the "ViewAll". The first View works fine but when I swipe to the second it shows this error.
I've tried to display data that I loaded with JSON in a AsyncTask, but there is this NullPointerException error
and I don't know how to solve it...
11-12 10:00:23.046: E/InputEventReceiver(12007): Exception dispatching input event.
11-12 10:00:23.046: E/MessageQueue-JNI(12007): Exception in MessageQueue callback: handleReceiveCallback
11-12 10:00:23.056: E/MessageQueue-JNI(12007): java.lang.NullPointerException
11-12 10:00:23.056: E/MessageQueue-JNI(12007): at com.example.rumorz.ViewAll$PostTask.onPreExecute(ViewAll.java:52)
11-12 10:00:23.056: E/MessageQueue-JNI(12007): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
Here is my code:
public class ViewAll extends Fragment {
//URL to get JSON Array
private static String url = ""; //URL to my site with JSON-code
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_message= "message";
TextView tvuser ;
TextView tvmessage ;
JSONArray user = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new PostTask().execute();
View rootView = inflater.inflate(R.layout.viewall, container, false);
return rootView;
}
private class PostTask extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
tvuser = (TextView)getView().findViewById(R.id.tvUser);
tvmessage = (TextView)getView().findViewById(R.id.tvmessage);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String users = c.getString(TAG_USER);
String message = c.getString(TAG_message);
tvuser.setText(users);
tvmessage.setText(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
onPreExecute(), invoked on the UI thread immediately after the task is executed.
intialize
tvuser = (TextView)rootView.findViewById(R.id.tvUser);
tvmessage = (TextView)rootview.findViewById(R.id.tvmessage);
in onCreateView
Initialize it in onCreateView. Use the inflated view object to initialize your textview's. or use getView in onActivityCreated to initialize textview's.
Since the textview is declared as a class member you can use it in onPostEecute to set text to the same.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.viewall, container, false);
tvuser = (TextView)rootView.findViewById(R.id.tvUser);
tvmessage = (TextView)rootview.findViewById(R.id.tvmessage);
new PostTask().execute();
return rootView;
}

Categories

Resources