Lethjakman
Lethjakman

Reputation: 997

Android listview is returning null?

So I'm trying to make a tabbed application...But it keeps crashing with null pointer exception . I checked through all the variables that could be causing a null pointer and I think I've narrowed it down.

ListView activeList = (ListView) findViewById(R.id.activelist);
if(activeList == null) {
  Log.e("com.name.app", "activeList null");
}

This returns a null. Should it? I'm using fragments to try and build a tabbed layout. This is the xml it's referencing.

<?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" 
    >

    <ListView
        android:id="@+id/activelist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:persistent="true" >    
    </ListView>

</LinearLayout>

Thank you for any help!

Edit:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.tabs_layout);

That's what my contentview looks like.

Edit: This is what my final code looked like!

    LayoutInflater inflater = (LayoutInflater)   getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    LinearLayout mContainer = (LinearLayout)     inflater.inflate(R.layout.tab_frag1_layout, null); 
    ListView activeList = (ListView) mContainer.findViewById(R.id.activelist);

Upvotes: 1

Views: 4511

Answers (2)

Iulia Barbu
Iulia Barbu

Reputation: 1530

LinearLayout mContainer = inflater.inflate(R.layout.linear_layout, null); 
ListView activeList = (ListView) mContainer.findViewById(R.id.activelist);

Where R.layout.linear_layout is the id of LinearLayout which contains your ListView.

Upvotes: 4

PoeHaH
PoeHaH

Reputation: 1936

Did you reffer in your activity to your XML layout?

You can do this in your oncreate method:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView.(R.layout.your_XML_file_name);
}

Upvotes: 1

Related Questions