Yash Mathur
Yash Mathur

Reputation: 103

My app shows an error on my android smartphone

The code-

package myusic.app.activity;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MyusicActivity extends Activity {
    ArrayList<String> listItems=new ArrayList<String>();

    ArrayAdapter<String> adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        ListView myList=(ListView)findViewById(android.R.id.list);
        myList.setAdapter(adapter);
    }

    public void addItems(View v) {
         listItems.add("Clicked");
         adapter.notifyDataSetChanged();
        }
}

XML Layout code-

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Myusic player"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/b1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add" 
        android:onClick="addItems"
        />

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

</LinearLayout>

The error that is shown when I run it on my phone is:

The application Myusic(process myusic.app.activity) has stopped unexpectedly. Please try again.

I think the error is in the line myList.setAdapter(adapter) because I've tried removing this line, and it shows no error, but obviously it does when i press the button. Please help me out in this. Thanks in advance. :)

Upvotes: 0

Views: 68

Answers (1)

Houcine
Houcine

Reputation: 24181

The error is that you have the id of your ListView on the Layout XML as : @+id/list , and you try to find it on your onCreate() method using another id ;

so change your line of code to get the listView like this :

ListView myList=(ListView)findViewById(R.id.list);

or change the id of your ListView on the layout to be like this :

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

Upvotes: 2

Related Questions