Android Studio通过意外数据填充ListView

时间:2014-10-15 20:20:39

标签: android sqlite listview

我现在正在开展一个项目,这是我的第一个安卓项目。

我试图从SQLite数据库填充ListView。 问题是列表中填充了与对象相关的内容,而不是nameid,例如我想要的内容。 您可以在下面的日志示例中看到我的意思

Player Count﹕ Player count: 48

Name is here:﹕ Name is here: Teris

Td is here:﹕ Td is here: packageName.player@435f3ea8

来自 DatabaseHelper.class

getAllPlayers 功能

public List<player> getAllPlayers() {
List<player> players = new ArrayList<player>();
String selectQuery = "SELECT  * FROM " + TABLE_PLAYERS;

Log.e(LOG, selectQuery);

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (c.moveToFirst()) {
    do {
        player td = new player();
        td.setId(c.getInt((c.getColumnIndex(KEY_ID))));
        td.setName((c.getString(c.getColumnIndex(KEY_NAME))));
        // adding to player list
        Log.e("Name is here: ","Name is here: " + td.getName());
        Log.e("Td is here: ","Td is here: " + td);
        players.add(td);
    } while (c.moveToNext());
}
return players;

}

PlayersActivity.class

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);

db = new DatabaseHelper(getApplicationContext());

player player1 = new player("Teris");
long player1_id = db.createPlayer(player1);

Log.e("Player Count", "Player count: " + db.getPlayersCount());

lv = (ListView) findViewById(R.id.playersList);

your_array_list = db.getAllPlayers();

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        this,
        android.R.layout.simple_list_item_1,
        your_array_list );

lv.setAdapter(adapter);
db.closeDB();

}

我到底做错了什么?

1 个答案:

答案 0 :(得分:0)

ArrayAdapter<String>尝试将每个Player对象转换为String。默认实现返回类似“packageName.player@435f3ea8”的内容。
简易解决方案 - 在您的Player类中覆盖toString方法:

   @Override
    public String toString() {
        return name;
    }

这样每个Player对象都将表示为其名称。

(顺便看一下班级名称“玩家”的伤害。它应该从大写开始:))