Search code examples
javaandroidlistviewbluetoothandroid-arrayadapter

Application crashes when adding object to an ArrayAdapter


So basically for my school project I have to be able to analyse nearby devices using Bluetooth, and well I decided to display them using a ListView, for which I have to fill an ArrayAdapter with at least names.

The thing is, for some reason, my application crashes everytime I try to do ANYTHING related to ArrayAdapter.

Considering what a disaster it was, I made this really simple code:

package z.ut010;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

String[] myStringTab = {"String01", "String02", "String03", "String04", "String05"};
ArrayAdapter <String> myArrayAdapter;
ListView myListView;

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

    myListView = (ListView) findViewById(R.id.LV);

    myArrayAdapter = new ArrayAdapter <> (MainActivity.this, android.R.layout.simple_list_item_1, myStringTab.length);
    myArrayAdapter.add("String06");

    myListView.setAdapter(myArrayAdapter);
   }
}

I've made just a ListView on my app for that code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ListView
    android:id="@+id/LV"
    android:layout_width="500dp"
    android:layout_height="800dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</android.support.const

Unfortunately, that didnt work out at all, and even with only that, my application crashes on

myArrayAdapter.add("String06");

Am I doing anything wrong?


Solution

  • First, you have used the wrong constructor.

    Use

    ArrayAdapter(Context context, int resource, T[] objects)
    

    or

    ArrayAdapter(Context context, int resource, List<T> objects)
    

    Second thing, if you are trying to add something to an ArrayAdapter, you cannot pass an array. You should pass a mutable list such as ArrayList.

    So in your case put all your strings in an ArrayList and then pass it in the constructor.

    myArrayAdapter = new ArrayAdapter <> (MainActivity.this,
            android.R.layout.simple_list_item_1, myStringTabArrayList);