rahul
rahul

Reputation: 71

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

I am getting this error. mostly error i checked getting a erro about null object refernce

public class MainActivity extends Activity {

     //SQLiteOpenHelper sqLiteOpenHelper;
    //SQLiteDatabase sqLiteDatabase;
      String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS","Ubuntu","Windows7","Max OS X"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ArrayAdapter<String> adapter;
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_2,mobileArray);
        ListView mylistView= (ListView) findViewById(R.id.listView1);
        mylistView.setAdapter(adapter);

    }
}

activity_main.xml

here is the main.xml file

          xmlns:tools="http://schemas.android.com/tools"

          android:layout_width="match_parent"

          android:layout_height="match_parent"

          tools:context="com.example.myapplication5.app.MainActivity"

          android:orientation="vertical">

<android.support.v7.widget.Toolbar

        android:id="@+id/toolbar"

        android:layout_width="match_parent"

        android:layout_height="attr/actionBarSize"

        android:background="attr/colorPrimary"/> 
<ListView
        android:layout_width="match_parent"

        android:layout_height="wrap_content"


        android:id="@+id/listView1" />



</LinearLayout>

this is the listview through which the adapter is connected

Upvotes: 1

Views: 20028

Answers (1)

Andrei T
Andrei T

Reputation: 3083

As far as I see you have a null object, myListView.
Trying checking for null before setting the adapter.
EDIT The next line:

ListView mylistView= (ListView) findViewById(R.id.listView);

is probably null. You must see why it is null. That's it, as far as I can see from the error and the code.
EDIT 2
Take a look at this tutorial it might help you see what you did wrong.
http://www.vogella.com/tutorials/AndroidListView/article.html

Upvotes: 1

Related Questions