-2

I want to create a new ListAdapter in a Fragment, but everytime when I run this code I will get this error:

Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

on this line: listAdapter = new ListAdapter(this.getActivity(), dataModelArrayList);.

I am not sure what I am doing wrong here. I had this: listAdapter = new ListAdapter(this, dataModelArrayList); first in my MainActivity and everything seems to work fine, but when I put it in the fragment and changed this to this.getActivity() and it stopped working. If you need more code please tell me.

In my Fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                         Bundle savedInstanceState) {
           View v = inflater.inflate(R.layout.fragment_home, container,false);
          listView = v.findViewById(R.id.lv);
          return v;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //..

        loadData();

        UsernameInput.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                Username = UsernameInput.getText().toString();
                if (Username.trim().length() == 0) {
                   //..
                    loadData();
                }else{
                    retrieveJSON();
                    //..    
                }
            }
           //..
        });
    }

    private void retrieveJSON() {
        //..
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("ok")){

                                //..
                                setupListview();
                            }
                            if (Username.trim().length() == 0) {
                                //..
                            }else{

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {//..});

       //...
    }




    private void setupListview() {
            listAdapter = new ListAdapter(getActivity(), dataModelArrayList);
            if (listAdapter.getCount() != 0) {
                listView.setAdapter(listAdapter);
            }
           listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              //..
            }
        });
        }
private void loadData() {

        //..
        if (HistoryList == null) {
            HistoryList = new ArrayList<>();
            setupListview_History();
            //..
        }else{
            setupListview_History();
            //..
        }
    }

Errors:

2019-08-27 12:31:13.098 10033-10033/com.instapf.danik.instapfforinstagram E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.instapf.danik.instapfforinstagram, PID: 10033
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at com.instapf.danik.instapfforinstagram.Home.setupListview_History(Home.java:257)
        at com.instapf.danik.instapfforinstagram.Home.loadData(Home.java:336)
        at com.instapf.danik.instapfforinstagram.Home.onCreate(Home.java:119)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2414)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1418)
        at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1195)
        at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1078)
        at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:117)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2408)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2243)
        at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
        at androidx.fragment.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:168)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:742)
        at android.view.View.measure(View.java:24545)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3006)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1833)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2122)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7598)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
        at android.view.Choreographer.doCallbacks(Choreographer.java:790)
        at android.view.Choreographer.doFrame(Choreographer.java:725)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951)
2019-08-27 12:31:13.099 10033-10033/com.instapf.danik.instapfforinstagram E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Vine Tube
  • 15
  • 4
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – a_local_nobody Aug 27 '19 at 10:02
  • your `ListView` is potentially/probably null – a_local_nobody Aug 27 '19 at 10:02
  • might be you forget to initialize your list. – Hemant Parmar Aug 27 '19 at 10:03
  • Use getActivity() instead of this – Blnpwr Aug 27 '19 at 10:03
  • The problem doesn't seem to be related to `getActivity()`, but to `listView` that is `null`. How do you instantiate listView in the Fragment? – Gabriele Mariotti Aug 27 '19 at 10:05
  • Your `listView` might not be initiated properly. Attach your XML code and import line of ListView. – Abu Noman Aug 27 '19 at 10:14
  • I have added some more code to the question. – Vine Tube Aug 27 '19 at 10:18
  • Try with casting ListView, like: `listView = (ListView) v.findViewById(R.id.lv);` – Abu Noman Aug 27 '19 at 10:21
  • @AbuNoman Your solution is not working sadly, still getting the same error. – Vine Tube Aug 27 '19 at 10:24
  • Are you certain you're looking at the right code? Please provide the complete stack trace. Are you sure that the layout you've posted is `fragment_home`? Do you possibly have multiple versions of that layout – e.g., one each for portrait and landscape, or for different screen sizes – and that `` is not in one? – Mike M. Aug 27 '19 at 10:28
  • The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView(). – Gabriele Mariotti Aug 27 '19 at 10:29
  • It might be a problem of threading, you are trying to `setAdapter` from a background thread, in this case, your `listView` should be final. I will suggest you to setup adapter in `onCreateView` with an empty list (but not null). When you will get data from API response then update (add data) to the `ArrayList` and notify change in the adapter. – Abu Noman Aug 27 '19 at 10:36
  • That stack trace doesn't match up with the code you've posted. Follow the methods listed there. – Mike M. Aug 27 '19 at 10:37
  • @AbuNoman I have created a empty list in my onCreateView, but I still getting the same error. – Vine Tube Aug 27 '19 at 10:50
  • @VineTube the question is very confused. Too much code. What does it mean "I have created an empty list? The error happens **before** in onCreate()/setupListview_History. – Gabriele Mariotti Aug 27 '19 at 10:54

3 Answers3

0

Check the Fragment lifecycle.
The create() method is called before onCreateView().

In your case it means that you are using in the setupListview()/loadData() methods

listView.setAdapter(listAdapter);

before listView = v.findViewById(R.id.lv); is called in onCreateView().

Then listView is null in your case.

You should move the setup code from onCreate() to the onActivityCreated(Bundle) method.

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • Thank you for your respone. I have changed my code so that `listView = v.findViewById(R.id.lv);` is called before `listView.setAdapter(listAdapter);` But it doesn't seem to do the trick. Still getting the same error. – Vine Tube Aug 27 '19 at 10:48
  • You can't use this code in any case before `onCreateView()`. – Gabriele Mariotti Aug 27 '19 at 10:50
0

You didn't follow the lifecycle of the fragment. You can follow the sequence bellow:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //do nothing here
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
      View v = inflater.inflate(R.layout.fragment_home, container,false);
      listView = v.findViewById(R.id.lv);
      return v;
}

@Override
public View onViewCreated(View view, Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
      dataModelArrayList = new ArrayList<>();
      setupListview();
      //retrive data based on text change
      retrieveJSON()
}
Abu Noman
  • 435
  • 3
  • 13
-1

I just needed to place:

        loadData();

        Clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClearData();
            }
        });

        UsernameInput.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                Username = UsernameInput.getText().toString();
                if (Username.trim().length() == 0) {
                    Search.setText("SEARCH HISTORY");
                    //Remove.setVisibility(View.VISIBLE);
                    if (HistoryList != null) {
                        HistoryList.clear();
                    }
                    if (dataModelArrayList != null) {
                        dataModelArrayList.clear();
                    }

                    loadData();
                    Log.d("Empty", "Empty");
                }else{
                    retrieveJSON();
                    Search.setText("SEARCH RESULTS");
                    //Remove.setVisibility(View.GONE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });

in onCreateView instead of onCreate.

Vine Tube
  • 15
  • 4