简体   繁体   中英

Android SQLite cursor returning junk

My database is definitely being populated correctly (<3 SQLite Database Browser), but when I try to list all the records in a view, I get the following:

com.example.AppName.ObjectName@4055e8c6
com.example.AppName.ObjectName@3456e789
com.example.AppName.ObjectName@4563e5b0

I am using simple_list_item_1 and an ArrayAdapter.

Create statement in my activity class:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_objects);

    datasource = new ObjectsDatabase(this);
    datasource.open();

    List<Object> values = datasource.getSavedObjects();

    ArrayAdapter<ObjectName> adapter = new ArrayAdapter<ObjectName>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
}

XML layout for above activity class:

<LinearLayout
    android:id="@+id/group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onButton1Click"
        android:text="@string/menu_back" />

</LinearLayout>

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

Any thoughts?

In my opinion you are trying to see the value of Object class , which returns you a correct value as

com.example.AppName.ObjectName@4055e8c6
com.example.AppName.ObjectName@3456e789
com.example.AppName.ObjectName@4563e5b0

Try to return String not Object and create List<String> . You can always create your own type of element , get that custom class object and return the String value of it.

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_saved_objects);

    datasource = new ObjectsDatabase(this);
    datasource.open();

    List<String> values = datasource.getSavedObjects();

    ArrayAdapter<ObjectName> adapter = new ArrayAdapter<ObjectName>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);
}

What you're seeing is the default implementation of toString() for your ObjectName objects.

Override toString() in your ObjectName class to produce a string representation for display purposes.

It's also worth considering to use a cursor adapter instead of array adapter since the data apparently comes from a database query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM