-2

For some reason I am getting a null pointer exception pointing to videosFound when it is indeed not null. Even the parameter, adapter, that is being passed in is not null. I check and verify this simply by printing out if its null or not (both of them are NOT null). So can someone please tell me how I am getting this error?

private ListView videosFound; 

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        searchInput = (EditText)findViewById(R.id.search_input);
        videosFound = (ListView)findViewById(R.id.videos_found);

        handler = new Handler();

        addClickListener();

        searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    searchOnYoutube(v.getText().toString());
                    return false;
                }
                return true;
            }
        });
    }

   private void updateVideosFound(){
        ArrayAdapter<VideoItem> adapter = new ArrayAdapter<VideoItem>(getApplicationContext(), R.layout.video_item, searchResults){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if(convertView == null){
                    convertView = getLayoutInflater().inflate(R.layout.video_item, parent, false);
                }
                ImageView thumbnail = (ImageView)convertView.findViewById(R.id.video_thumbnail);
                TextView title = (TextView)convertView.findViewById(R.id.video_title);
                TextView description = (TextView)convertView.findViewById(R.id.video_description);

                VideoItem searchResult = searchResults.get(position);

                Picasso.with(getApplicationContext()).load(searchResult.getThumbnailURL()).into(thumbnail);
                title.setText(searchResult.getTitle());
                description.setText(searchResult.getDescription());
                return convertView;
            }
        };
        if(videosFound == null){
            System.out.println("videoFound is null***********");
        }else{
            System.out.println("videoFound is NOT null***********");
        }

        if(adapter == null){
            System.out.println("adapter is null***********");
        }else{
            System.out.println("adapter is NOT null***********");
        }
        videosFound.setAdapter(adapter);//ERROR HERE. neither videosFound no adapter are null
    }

private void addClickListener(){
        videosFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> av, View v, int pos,
                                    long id) {
                Intent intent = new Intent(getApplicationContext(), PlayerActivity.class);
                intent.putExtra("VIDEO_ID", searchResults.get(pos).getId());
                startActivity(intent);
            }
        });
    }

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/search"
        android:id="@+id/search_input"
        android:singleLine="true" />

    <ListView
        android:id="@+id/videos_found"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="5dp" />

</LinearLayout>

Console:

03-24 18:04:31.833 17014-17440/com.example.shawn.myyoutube D/YC: Could not search: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
                                                                 {
                                                                   "code" : 403,
                                                                   "errors" : [ {
                                                                     "domain" : "usageLimits",
                                                                     "message" : "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
                                                                     "reason" : "ipRefererBlocked",
                                                                     "extendedHelp" : "https://console.developers.google.com"
                                                                   } ],
                                                                   "message" : "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
                                                                 }
03-24 18:04:31.833 17014-17014/com.example.shawn.myyoutube I/System.out: videoFound is NOT null***********
03-24 18:04:31.833 17014-17014/com.example.shawn.myyoutube I/System.out: adapter is NOT null***********
03-24 18:04:31.843 17014-17014/com.example.shawn.myyoutube D/AndroidRuntime: Shutting down VM
03-24 18:04:31.843 17014-17014/com.example.shawn.myyoutube E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.shawn.myyoutube, PID: 17014
                                                                             java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                                                                                 at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
                                                                                 at android.widget.ListView.setAdapter(ListView.java:502)
                                                                                 at com.example.shawn.myyoutube.SearchActivity.updateVideosFound(SearchActivity.java:98)
                                                                                 at com.example.shawn.myyoutube.SearchActivity.access$200(SearchActivity.java:23)
                                                                                 at com.example.shawn.myyoutube.SearchActivity$2$1.run(SearchActivity.java:61)
                                                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                 at android.os.Looper.loop(Looper.java:145)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5951)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
bob dylan
  • 607
  • 9
  • 22
  • 5
    Could you post the stacktrace? – TheMirrox Mar 25 '16 at 00:56
  • @TheMirrox added. I should also mention this: when I debug it the values are null, but when I use an IF statement to compare, it is NOT null... – bob dylan Mar 25 '16 at 01:07
  • 5
    I think it's `searchResults` that is `null`. – Paul Boddington Mar 25 '16 at 01:07
  • Please post your adapter code. As for the code posted, it seems "searchResults" is null. – Shadab Ansari Mar 25 '16 at 01:10
  • @ShadabAnsari posted. – bob dylan Mar 25 '16 at 01:15
  • @PaulBoddington yes you are correct! But why...? – bob dylan Mar 25 '16 at 01:15
  • @bobdylan I don't know. I assume you never initialise it. – Paul Boddington Mar 25 '16 at 01:17
  • @PaulBoddington ok thanks. Thank you very much for your help, I got it from here! But for future reference, do you know why the error did not actually point to the line where searchResults was? I have never encountered something like this where one object is null, but the error points to another object. – bob dylan Mar 25 '16 at 01:20
  • 2
    When you set the adapter, part of that call gets the count, which is where the NPE occurred but this is not in your code so that line is the only human readable line that can show the error as the rest is in the Android code. – Dave S Mar 25 '16 at 01:23
  • 2
    @bobdylan I must admit, I am a bit surprised that you don't get a `NullPointerException` in the `ArrayAdapter` constructor - but this is android so expect it to be a bit crap. You can see from the stack trace that it can't be `videosFound` that is `null` - if it was then the method `setAdapter` wouldn't be executed. Always look at the very top - in this case the line highlighted in the accepted answer. – Paul Boddington Mar 25 '16 at 01:23
  • 1
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Linh Mar 25 '16 at 01:28

2 Answers2

4

In the stacktrace I see this:

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

The adapter is trying to call size() on a null List. Make sure your list searchResults is not null.

Leo
  • 808
  • 8
  • 14
2

NullPointerException occurred because searchResults is not initialized and is null. Regarding your question in the comment -

do you know why the error did not actually point to the line where searchResults was?

ArrayAdapter calls getCount() internally whenever you call setAdapter() or refresh the already created adapter using notifyDataSetChanged(). Till you call setAdapter() or notifyDataSetChanged(), ArrayAdapter won't create view for you and in order to create that, it needs to check the size of the data which you passed to it. For that it calls getCount()
which is

 public int getCount() {
        return mObjects.size();
    }

where mObjects is initialized to the data list which you pass while creating your adapter.

Apparently mObjects.size() will throw NullPointerException since mObjects is null because searchResults is null.

Hope you understood.

Shadab Ansari
  • 6,816
  • 1
  • 23
  • 38