The Well
The Well

Reputation: 894

Messing with ListView in Android

Good day to everyone, I am new to Android, I keep on messing with ListView. The code below wont work! I dont know why. Please let me know where's the mistake.

Main Activity.java

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

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

    ArrayList<String> data = new ArrayList<String>();
    data.add("Follow Me!");
    data.add("This is now.");

    ArrayAdapter<String> adapter = new ArrayAdapter<String>  (this,android.R.layout.simple_list_item_1,data);
    listView.setAdapter(adapter);

    setContentView(R.layout.activity_main);
}

}

activity_main.xml:

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

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView" />
 </LinearLayout>

After running the above code, my adroid device will show a dialogue saying: "Sorry! The application CodeGenerator has stopped unexpectedly. System failed to repair the error. Please use other software."

Please help!

Upvotes: 1

Views: 56

Answers (2)

The Well
The Well

Reputation: 894

Anyway, I changed the code, and its running now. Here's the code:

public class MainActivity extends ListActivity {

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

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

    ArrayList<String> data = new ArrayList<String>();
    data.add("Follow Me!");
    data.add("This is now.");

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);

    setListAdapter(adapter);
}

}

Still a mystery for me, why my first code did not work! If anyone can explain that, please let me know! Thank you!

Upvotes: 0

Antrromet
Antrromet

Reputation: 15424

The setContentView(R.layout.activity_main); line should be immediately after super.onCreate(savedInstanceState);.

What this
setContentView(R.layout.activity_main);
line does is it basically displays the screen (your android xml to the user). Now when you do

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

You are trying to get your ListView from your xml in your java code. But if you dont set the content itself, then there is no ListView and hence your application is crashing.

Upvotes: 1

Related Questions