Search code examples
androidandroid-layoutandroid-listviewandroid-arrayadapter

How to avoid crashing for an listview android app


I build an android app with the help of an tutorial.

This is the MainActivity.java:-

package com.example.listdisplay;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
    // Array of strings...
    String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
            "WebOS","Ubuntu","Windows7","Max OS X", "PHP", "Java", "HTML", "CSS", "JavaScript","MySQL"};

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

        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.activity_listview, mobileArray);

        ListView listView = (ListView) findViewById(R.id.mobile_list);
        listView.setAdapter(adapter);
    }
}

This is the activity_main.xml:-

<LinearLayout 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:orientation="vertical">

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

</LinearLayout>

This is the activity_listview.xml:-

<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="20dip"
    android:textSize="16dip"
    android:textStyle="bold"
    android:orientation="horizontal">
</TextView>

When I change the textview to any other view like cardview and more things. The app is going to crashed. I want to do more styling with cardview and layout. Like i also tried with the linearlayout.I inserted this textview with an button in linear layout. But, it is still going to crash.

Please help me.


Solution

  • You can't change the TextView from activity_listview.xml because ArrayAdapterconstructor expects a Layout with an only EditText.

    If you want to modify that, you have to implement a custom ArrayAdaptermaking a class that extends from it.

    You can follow next Medium tutorial to achieve this. https://medium.com/mindorks/custom-array-adapters-made-easy-b6c4930560dd

    If you want to add a Button or something else, you need the custom ArrayAdapter.