Mattigins
Mattigins

Reputation: 1016

ListView causes NullPointerException

This is my first Android app, i am trying to put a listview on and i have followed numerous tutorials but i always get the same result, a crash upon starting the app.

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:gravity="top"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mattigins.mediacenter.MainActivity$PlaceholderFragment" >

<View
    android:id="@+id/view1"
    android:layout_width="550dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/View01"
    android:background="@drawable/semi_trans_box" />

<View
    android:id="@+id/View01"
    android:layout_width="550dp"
    android:layout_height="wrap_content"
    android:layout_marginRight="58dp"
    android:layout_toLeftOf="@+id/view1"
    android:background="@drawable/semi_trans_box" />

<ListView
    android:id="@+id/List1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/View01"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/View01" >

</ListView>

Code

protected void onCreate(Bundle savedInstanceState) {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        ListView listView = (ListView) findViewById(R.id.List1);
        String[] test_items = {"1","2","3","4"};
        ArrayAdapter<String> test_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test_items);
        listView.setAdapter(test_adapter);

}

Upvotes: 0

Views: 67

Answers (1)

Raghunandan
Raghunandan

Reputation: 133560

Looks like your ListView belongs to the Fragment layout. Looking at

In onCreateView of Fragment.

ListView listView = (ListView) rootView.findViewById(R.id.List1);
String[] test_items = {"1","2","3","4"};
ArrayAdapter<String> test_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, test_items);
listView.setAdapter(test_adapter);

Upvotes: 1

Related Questions