【问题标题】:how to put data from List<Object> to String array Android?如何将数据从 List<Object> 到 String 数组 Android?
【发布时间】:2014-12-20 14:23:27
【问题描述】:

这是我要插入到数组中的对象。 getter 和 setter 都已定义。

public class Task {

private int id;
private String title;
private String description;

public Task(){}

public Task(String title, String description) {
    super();
    this.title = title;
    this.description = description;
}

//getters & setters
}

这里是 getAllTask​​s 方法,它将我的数据库中的数据转换为任务对象,然后将对象转换为列表。

public List<Task> getAllTasks() {
    List<Task> tasks = new LinkedList<Task>();

    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_TASKS;

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build task and add it to list
    Task task = null;
    if (cursor.moveToFirst()) {
        do {
            task = new Task();
            task.setId(Integer.parseInt(cursor.getString(0)));
            task.setTitle(cursor.getString(1));
            task.setDescription(cursor.getString(2));

            // Add task to tasks
            tasks.add(task);
        } while (cursor.moveToNext());
    }

    Log.d("getAllTasks()", tasks.toString());

    // return tasks
    return tasks;
}

这就是我想要执行的操作:

我想在字符串数组taskList中插入对象。

MySQLiteHelper db = new MySQLiteHelper(this);
    List<Task> tasks = db.getAllTasks();
    String [] taskList = new String[tasks.size()];
    int index = 0;
    for (Task value : tasks) {
        taskList[index] = String.valueOf( value );
        index++;
    }

【问题讨论】:

  • 你真的需要一个字符串数组吗?似乎您的数据表明您需要独立的两个字符串,这是一个糟糕的假设吗?如果您确实需要它们,您可能需要考虑一个字符串数组的数组,或者一个字符串数组的列表。
  • 我不明白你的代码的确切目的。但是您必须覆盖 youc 类中的 toString 方法才能获得对象的有意义的字符串表示形式。但是除了打印它之外,那个字符串数组对你没有用。如果你能解释你的目的是什么,那么也许我们可以帮助你
  • 我正在尝试使用 arrayAdapter 中的字符串数组 taskList 将其输出到 ListView

标签: java android arrays object android-arrayadapter


【解决方案1】:

您需要重写 Task 类的 Object toString 方法。

例子:

public String toString() {
    return "Task [id=" + id + ", title=" + title + ", description=" + description + "]";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2018-09-22
    • 2019-06-20
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多