Crash on Fragment Change

Crash on Fragment Change



This is the Code snippet of one of my fragments:


@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState)

View view = inflater.inflate(R.layout.fragment_three, container, false);

listView = (ListView)view.findViewById(R.id.list_listview);
adapter=new list_adapter(getActivity(),transaction_list);
transaction_list.clear();
listView.setAdapter(adapter);
setListViewData();
return view;



private void setListViewData()

RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, listurl, null,
new Response.Listener<JSONArray>()
public void onResponse(JSONArray jsonArray)
if (jsonArray.length() > 0)
Log.e("JSON ARRAY", jsonArray.toString());


for (int i = 0; i < jsonArray.length(); i++)
try

JSONObject obj = jsonArray.getJSONObject(i);
User user = new User();

User.setmName(obj.getString("name"));
User.setmnName(obj.getString("nname"));
User.setmDate(obj.getString("date"));
User.setmProfile(obj.getString("profile"));
user.setmDirection(obj.getString("direction"));


transaction_list.add(user);

catch (JSONException e)
e.printStackTrace();

adapter.notifyDataSetChanged();

try
info.setText(getView().getResources().getString(R.string.user_rest, jsonArray.getJSONObject(0).getString("info")));

Button edit = getActivity().findViewById(R.id.button_edit);
edit.setClickable(true);

catch (JSONException e)
e.printStackTrace();







, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError volleyError)
Log.e("Error", String.valueOf(volleyError));

);

// add json array request to the request queue
requestQueue.add(jsonArrayRequest);



}



The Code works fine, but when I'm switching to another fragment while the Volley Request is processed (basically while the fragment is loading the data from the server) the App crashes, giving me the following error:



java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.view.View.getResources()' on a null object reference
.onResponse(fragment_three.java:178)
.onResponse(fragment_three.java:151)



Line 178:
info.setText(getView().getResources().getString(R.string.user_rest, jsonArray.getJSONObject(0).getString("info")));



Line 151:
new Response.Listener() {



The Error in Line 178 is somehow clear why it occurs, but how can I prevent it from happening?



The Error in Line 151 is somehow strange, is it maybe because in the line before "Volley.newRequestQueue(getContext()); " the getContext() is "null" when I'm switching to another fragment or is this the Context of the Main Activity containing all the fragments (so it basically is never null while going through the menu)?






i believe getView() is null

– Prashanth Verma
Sep 16 '18 at 20:20




3 Answers
3



The first line of the stack trace is telling you that getView() is returning null, which I think you already knew. The second line of the stack trace is the “cause” for it, and is just telling you “where” that call came from: the request’s response listener.


getView()


null



The root cause for what’s going on here is that the navigation away from your Fragment is causing the Android framework to destroy your Fragment. Part of that process is that your Fragment’s onDestroyView() method will be called, after which getView() will return null.


onDestroyView()


getView()


null



To fix the crash, you can do one of two things.



The easiest would be just to wrap your call in if (getView() != null). That will fix the problem for now, but it’s sort of a quick and dirty kind of thing.


if (getView() != null)



The better solution would be to use the fact that the Android framework calls your Fragment’s onDestroyView() to cancel your Volley request. That way (a) your app won’t do useless work on a network call that it’s not going to use and (b) you don’t have to worry about whether or not you’d ever add some other crash-prone code in the future.


onDestroyView()



Probably the simplest thing to do is to declare the JsonArrayRequest jsonArrayRequest variable at your Fragment’s class level (outside the setListViewData() method), and then clean it up in onDestroyView():


JsonArrayRequest jsonArrayRequest


setListViewData()


onDestroyView()


JsonArrayRequest jsonArrayRequest;

private void setListViewData()
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, listurl, null,
new Response.Listener<JSONArray>()
...
);


@Override
public void onDestroyView()
if (jsonArrayRequest != null)
jsonArrayRequest.cancel();







That's the one to go. I worked with this code and tried to enable a Button when the jsonArray gets parsed and I got another "NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setClickable(boolean)' on a null object reference" . Do I have to check every action conntected to the jsonArray Request if it !=null ?

– Los Kayos
Sep 23 '18 at 19:29






Look at my Edit, it's the "Button edit" I'm talking about

– Los Kayos
Sep 23 '18 at 19:30






Are you sure you want to be calling getActivity().findViewById() ? That will look for the button in the activity's layout, but I assume you want to find it in the fragment's layout instead. Try getView().findViewById() instead.

– Ben P.
Sep 23 '18 at 19:34


getActivity().findViewById()


getView().findViewById()






No, it's the getResources() which does lead to an Error, I invoke it in a class outside the onCreateView.

– Los Kayos
Sep 24 '18 at 18:45






java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.view.View.getResources()' on a null object reference

– Los Kayos
Sep 24 '18 at 18:47



Replace this line:


info.setText(getView().getResources().getString(R.string.user_rest, jsonArray.getJSONObject(0).getString("info")));



with:


info.setText(getActivity().getResources().getString(R.string.user_rest, jsonArray.getJSONObject(0).getString("info")));



Notice this:


setListViewData(); //call function(getView()) before really get view.
return view;//only after this line the view returnd.






yeah but... I can't put setListViewData() after the return view. So I don't really get your hint! Thx anyway!

– Los Kayos
Sep 23 '18 at 19:24



Follow this github repo to help you with navigating between fragments
https://github.com/SWAQ-COMMUNITY/SliderModule.git
Then i think you need to do some adjustments in your res folder,check if you have something like this drawable-v21 or similar folder, move the content to folders like this drawable



For example move all the content in drawable-v21 > drawable



and apply the same for mimap and value. Then delete those folders...



this folders drawable-v21 and similar
invalidate and restart, then you should be fine



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?