2012-01-29 77 views
0

我想記錄一個數組列表的內容。 arraylist包含一個具有4個參數的自定義對象。當我執行下面的代碼時,我得到以下日誌。我想是的[姓名,班級,三十九十],[姓名,班級,三十九十]等問題logging arraylist

自定義對象類的字符串:

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: [[email protected]] 

回答

1

爲了達到你的目標,以打印對象的字符串,你必須做兩件事情在你的代碼。
1)重寫toString方法。

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

2)ArrayList<Data> array是數據對象的集合。您必須指定要打印的對象。你可以用兩種方法來做到這一點。

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()); 
    } 
+0

感謝狀,偉大工程!優秀的解釋 – benbeel 2012-01-29 16:04:01

0

添加toString()方法您Data類。

這樣

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

調用array.toArray().toString()調用ObjecttoString方法,打印其中陣列位於存儲器中的位置的散列。

我想你想要的是這樣的:

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