petroni
petroni

Reputation: 776

Null Pointer Exception at setAdapter

EDIT: Turns out I just don't know enough about Tabbed Activities... But thanks for the help!

I have searched for nearly an hour now why my code trows an NPE at setAdapter. Here's the part of code that issues the NPE (Line 83 and 84, the error being at line 84)

ListView cList = (ListView)findViewById(R.id.mylistview);
cList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listitems));

"listitems" is defined as

String[] listitems= {"A","b","C","d","E","f"};

Heres the full myActivity.java: http://pastebin.com/ymiKRUc4

That's what LogCat says: http://pastebin.com/gPZYtXng

My fragment_myactivity.xml is just

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/mylistview"
        android:layout_width="fill_parent"   
        android:layout_height="fill_parent" >

    </ListView>
</LinearLayout>

And this is my activity_myactivity.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapp.myActivity" />

Upvotes: 0

Views: 58

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83527

myActivity inflates activity_myactivity.xml for its layout:

setContentView(R.layout.activity_myactivity);

However, mylistview is in fragment_myactivity.xml. I assume that you inflate this XML file in a Fragment subclass which overrides onCreateView(). This is the method where you need to put

ListView cList = (ListView)findViewById(R.id.mylistview);
cList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listitems));

Note that the views inflated by a fragment are not available in Activity.onCreate(), so findViewById() will return null for these views.

Upvotes: 2

Related Questions