convert ArrayList<Class> to string[]

大城市里の小女人 提交于 2019-12-20 06:38:28

问题


I have class Person

class person{
int ID ;
sting FirstName ;
string Last Name ;
String Telephone ;

}

and I have ArrayList<person> ;

now I want to display simple list view containing just FirstName + "," + "LastName"

so I can use code like

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");

ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);

builder.setView(modeList);
final Dialog dialog = builder.create();

dialog.show();

so how to cconvert the ArrayList to string[] that contains the format FirstName + "," + "LastName"

I can loop , but Is there any good way or simple way to do that , because I tried to use adapter but it failed to appear in the dialoge


回答1:


Make your ArrayAdapter to use the type person and not String (also, just pass the ArrayList<person> instead of an array) like this:

ArrayAdapter<person> modeAdapter = new ArrayAdapter<person>(this, android.R.layout.simple_list_item_1, android.R.id.text1, theArrayList);

and then override the person's class toString method:

class person {
        int ID;
        String FirstName;
        String LastName;
        String Telephone;

        @Override
        public String toString() {          
            return "Whatever " + FirstName + " and Whatever  " + LastName;
        }

    }



回答2:


Better to use Custom Adapter. Here you do not need to convert ArrayList to String ArrayList. You able to set data via array-list position.

link

Thanks



来源:https://stackoverflow.com/questions/11281147/convert-arraylistclass-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!