Search code examples
javaandroidandroid-studiosugarorm

Sugar ORM: How to display values


I use Sugar ORM for Android Development via Android Studio.

But I think I have a quite similar question. How can I display one/multiple result queries as String or int? My entity looks like this:

public class PersonsDatabase extends SugarRecord<PersonsSelection>{
String adultText, childText;
int adultCount, childCount;

public PersonsDatabase()
{

}
public PersonsDatabase(String adultText, String childText, int adultCount, int childCount)
{
    this.adultText = adultText;
    this.childText = childText;

    this.adultCount = adultCount;
    this.childCount = childCount;

    this.save();
}

}

It saves correctly. But when I want to display like this:

public class PersonsSelection extends Activity {

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

    PersonsDatabase personsDatabase = new PersonsDatabase("1 Adult","No Childs",1,0);
    List<PersonsDatabase> personsList = PersonsDatabase.findWithQuery(PersonsDatabase.class,"Select adult_Text from PERSONS_DATABASE");

    list = (ListView)findViewById(R.id.listView);
    list.setAdapter(new ArrayAdapter<PersonsDatabase>(this, android.R.layout.simple_list_item_1, personsList));
}

}

I get something like: PACKAGENAME.PersonsDatabase@4264c038 But I want the values that I wrote in the constructor.

Thanks for help.


Solution

  • From the docs on ArrayAdapter:

    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.

    In short: just override the toString() method in your PersonsDatabase class to return the desired textual respresentation.

    Alternatively:

    To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

    (again from the docs). Plenty of examples out there on how to go about doing that.