0

in my android project, i am getting a list of data in arraylist

ArrayList<Items> item = db.getAllMenu();

but now i want to add this data into listview, i tried as,

ListView lv=(ListView)findViewById(R.id.list_view_inside_nav);
String[] lv_arr = {};
         lv_arr = (String[]) item.toArray();
        lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, lv_arr));

but its giving error.because i am trying to convert arratlist to string.. anyone plz help me, how to convert the arraylist to string[]

here are my some files... items.java (getter and setter methods)

public class Items {
    //private variables

    String _name;
    // Empty constructor
    public Items(){
    }

    // constructor
    public Items(String name){

        this._name = name;

    }

    // getting name
    public String getName(){
        return this._name;
    }
    // setting name
    public void setName(String name){
        this._name = name;
    }


}

and i am using this code to get data from database

public ArrayList<Items> getAllMenu() {
    ArrayList<Items> passList = new ArrayList<Items>();
    // Select All Query
    String selectQuery = "SELECT * FROM " + CATEGOTY_TABLE_NAME;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Items menu = new Items();

            menu.setName(cursor.getString(0));

    // Adding category to list
            passList.add(menu);
        } while (cursor.moveToNext());
    }
    // return category list
    return passList;
}
varsha valanju
  • 801
  • 1
  • 9
  • 27

4 Answers4

0

Wrong. Items class cannot convert to a String class. You need to convert each Items to String object.

Example :

Say your class Item

class Items{
    public String itemName;
}

In your code change

String[] lv_arr = new String[items.size()];

for(int i=0;i<items.size();i++){
    lv_arr[i]=item.get(i);
}

lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, lv_arr));
AxelH
  • 14,325
  • 2
  • 25
  • 55
noobEinstien
  • 3,147
  • 4
  • 24
  • 42
0

Your problem here is that you are trying to convert a List into an Array, this can't be done with a cast but methods exist.

The easiest would be to convert the list into an Array using the methods List.toArray(E[]).

ArrayList<Items> items = db.getAllMenu();
Items[] itemsArray = new Items[items.size()]; //Create the array to the correct size, 
itemsArray = items.toArray(itemsArray); //Fill the array with the list data
//you could cast into Item[] directly but this is cleaner

Help to use here : Convert ArrayList<String> to String[] array

The array need to be an array of Items

Then, if you have override the toString methods of your Item class to return the String like you want.

public class Items {
   ...

   @Override
   public String toString(){ 
       this.getName() //Just an example ;)
   }
   ...
}

This will work like a charm. The adapter use this method to get the String to print.

EDIT :

After some research, you don't even need to create an array. ArrayAdapter accept an List so you only need to override Items.toString()

https://developer.android.com/reference/android/widget/ArrayAdapter.html

You can see here the need to override the toString

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

And here is the constructor to use

ArrayAdapter (Context context, int resource, List objects)

So just create your adapter like this :

new ArrayAdapter<Items>(MainActivity.this,
            android.R.layout.simple_list_item_1, item);
Community
  • 1
  • 1
AxelH
  • 14,325
  • 2
  • 25
  • 55
  • @varshavalanju You were close, I didn't even realise that you tried to do exactly what the ArrayAdapter propose until I reopen this question. Remember that this is quite common for GUI to use toString() to visualize an Object (not always but almost). – AxelH Oct 25 '16 at 09:14
0

You have to make arraylist of object to do such thing here is a piece of my code that i use

My ArrayList

private ArrayList<Mediafileinfo> songList = new ArrayList<Mediafileinfo>();

Adding data in the arraylist object.

  Mediafileinfo info = new Mediafileinfo();
                    info.setFile_uri(Uri.parse(audioCursor.getString(audiodata)));
                    info.setName(audioCursor.getString(audioTitle));
                    info.setDuration(audioCursor.getLong(audioduration));
                    info.setAlbum(audioCursor.getString(audioalbum));
                   info.setAlbum_Art_uri(ContentUris.withAppendedId(albumArtUri, audioCursor.getLong(audioalbumid)));
                    songList.add(info);

Make a class with getter and setter

public class Mediafileinfo {
private String name,album,artist;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAlbum() {
    return album;
}

public void setAlbum(String album) {
    this.album = album;
}

public String getArtist() {
    return artist;
}

public void setArtist(String artist) {
    this.artist = artist;
}
}

And call in your arraylist adapter like this

 Mediafileinfo mediafileinfo = (Mediafileinfo) getItem(position);
    TextView textView = (TextView) view.findViewById(R.id.textView);
    textView.setText(mediafileinfo.getAlbum());

and rest will be the same you can set the arraylist in your adapter like this

new CustomAdapter(this,songlist) Hope this will help you.For more info

Community
  • 1
  • 1
Neelay Srivastava
  • 1,041
  • 3
  • 15
  • 46
0

let listobj be a list of object you want toset for your listView and Lv be your listview use following code:

 LV.setAdapter(new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1 ,sensors));


update

if you want each item of your LisView represent a specific object you could also populate it with a custom adaptor like this : first in your java files define new javaclass that extends BaseAdaptor

public class SensorAdaptor extends BaseAdapter{
    private final Context context;
    private final List<Sensor> sensors;

    public SensorAdaptor(Context context , List<Sensor> sensors){
        this.context = context;
        this.sensors = sensors;
    }

    @Override
    public int getCount() {
        return sensors.size();
    }

    @Override
    public Object getItem(int position) {
        return sensors.get(position);
    }

    @Override
    public long getItemId(int position) {
        return sensors.get(position).getType();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.list_sensors, null);
        } else {
            view = convertView;
        }
        TextView listName = view.findViewById(R.id.txtSensorList);
        listName.setText(sensors.get(position).getName());
        return view;
    }
}

attention in my case i want each item of listView represent a Sensor object then in layout file in res/layout define a layout for this adaptor to use

<?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">

    <TextView
        android:id="@+id/**txtSensorList**"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

and then in yor activity

List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);


LV.setAdapter(new SensorAdaptor(getContext(),sensors));

attention in my case i want to show a list of sensor Object

Ghazaleh Javaheri
  • 1,829
  • 19
  • 25