问题记录arraylist

时间:2012-01-29 03:53:47

标签: android arraylist

我正在尝试记录arraylist的内容。 arraylist包含一个带有4个参数的自定义对象。当我执行以下代码时,我得到以下日志。我想要的是一串[名字,班级,三十,九十],[名字,班级,三十,九十]等等

自定义对象类:

public class Data {
        String NAME;
        String CLASS;
        String THIRTY;//this is the thirty day supply
        String NINETY;//this is the ninety day supply

    public Data(){
        super();
    }
    public Data(String NAME, String CLASS, String THIRTY, String NINETY){
        super();
        this.NAME = NAME;
        this.CLASS = CLASS;
        this.THIRTY = THIRTY;
        this.NINETY = NINETY;
    }

    }

的活动:

ArrayList<Data> array = new ArrayList<Data>();

Cursor c = mDBHelper.getReadableDatabase().query(Constants.K_Table, null, Constants.Name +"=?", new String[] {SEARCH}, null, null, null);

            startManagingCursor(c);
            if (c.moveToFirst()){

            NAME = c.getString(c.getColumnIndex(Constants.Name));
            CLASS = c.getString(c.getColumnIndex(Constants.Class));
            THIRTY = c.getString(c.getColumnIndex(Constants.Month));
            NINETY = c.getString(c.getColumnIndex(Constants.Three_Month));

            array.add(new DrugData(NAME, CLASS, THIRTY, NINETY));
            Log.d(TAG, "array contains: "+ array.toArray().toString());
            }while(c.moveToNext());

日志:

01-28 22:31:44.742: D/Activity(23656): the array contains: [com.Data@40552050]

3 个答案:

答案 0 :(得分:1)

要实现打印对象字符串的目标,您必须在代码中执行两项操作。
1)覆盖toString方法。

@Override
public String toString() {
    return "Data [NAME=" + NAME + ", CLASS=" + CLASS + ", THIRTY=" + THIRTY
            + ", NINETY=" + NINETY + "]";
}

2)ArrayList<Data> array是Data对象的集合。您必须指定要打印的对象。你可以用两种方式做到这一点。

    int index = 0;// Index of object in the ArrayList
    Log.i("Data",array.get(index).toString());//Preferred Method to get object
    Log.i("Data",array.toArray()[index].toString());

您可以循环遍历数组以打印所有这些数据对象

    for (Data data : array) {
        Log.i("Data",data.toString());
    }

答案 1 :(得分:0)

toString()课程中添加Data方法。

像这样

public String toString() {
    return NAME + " " + CLASS + " " THIRTY + " " + NINETY;
}

答案 2 :(得分:0)

调用array.toArray().toString()调用Object类'toString方法,该方法在内存中打印阵列所在位置的哈希值。

我认为你想要的是这样的:

Log.d(TAG, "added "+ NAME + ":" + CLASS + ":" + THIRTY + ":" + NINETY + " to array";