0

The below is my testing code to create the list view, the list view display successfully, however, there is error in click event. Here is my simple code:

public class MainActivity extends Activity {

    private String[] Ass;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
         Ass=new String[]{"Ass1","Ass"};
        ListView mListView = (ListView) findViewById(R.id.ass);

        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Ass);
        mListView.setAdapter(mAdapter);
        mListView.setClickable(true);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

                textView.setText(Ass[arg2]);

        });

    }

Here is the XML FILE

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.a21.proplay.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ass"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="67dp" />

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="20dp"
        android:layout_marginStart="20dp"
        android:layout_marginBottom="23dp"
        android:id="@+id/textView" />
</RelativeLayout>

When I click to list it crashes.I cannot figure out why the click is not working.How can I fix that?

STepHan
  • 57
  • 1
  • 11

2 Answers2

2

add this line

textView = (TextView) findViewById(R.id.textView)
1

Your textView is null.

initialize it like:

TextView textView = (TextView) findViewById(R.id.textView);

change your code to :

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

            String selectedFromList =(String) (mListView.getItemAtPosition(arg2));
            textView.setText(selectedFromList);

    });
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62