2017-03-01 66 views
-4

如何在通用類型list<Model>中添加StringBuffer。我想在List<Model>中添加StringBuffer,但android studio強制我將通用更改爲List<Stringbuffer>如何在通用類型列表中添加StringBuffer列表<Model>?

public List<DataModel> getdata(){ 
    DataModel dataModel = new DataModel(); 
    List<DataModel> data=new ArrayList<>(); 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor cursor = db.rawQuery("select * from "+TABLE+" ;",null); 
    StringBuffer stringBuffer = new StringBuffer(); 

    while (cursor.moveToNext()) { 
     String name = cursor.getString(cursor.getColumnIndexOrThrow("name")); 
     String country = cursor.getString(cursor.getColumnIndexOrThrow("country")); 
     String city = cursor.getString(cursor.getColumnIndexOrThrow("city")); 
     dataModel.setName(name); 
     dataModel.setCity(city); 
     dataModel.setCounty(country); 
     stringBuffer.append(dataModel); 


    } 
    data.add(stringBuffer); 

    Log.i("Hello",""+data); 
    return data; 
} 
+1

你爲什麼使用StringBuffer?如果有的話,你應該使用'StringBuilder'。但是,在這裏你應該既不使用。相反,在循環內部創建一個新的'DataModel'對象,並將其添加到循環內部的'data'列表中。此外,請記住在完成時關閉「光標」。 – Andreas

+0

另外,'List '拼寫錯誤。但@Andreas是對的,你不應該使用'StringBuffer',至少在過去的12或13年內不會。 –

回答

0

由於mentioned in a comment,您不希望在此代碼中使用StringBuffer(或更好的StringBuilder)。

取而代之,在循環內創建一個新的DataModel對象,並將其添加到data列表中,也在循環中。

此外,請記住在完成時關閉Cursor,最好使用try-with-resources

public List<DataModel> getdata(){ 
    List<DataModel> data = new ArrayList<>(); 
    SQLiteDatabase db = this.getWritableDatabase(); 
    try (Cursor cursor = db.rawQuery("select * from "+TABLE+" ;", null)) { 
     int nameIdx = cursor.getColumnIndexOrThrow("name"); 
     int cityIdx = cursor.getColumnIndexOrThrow("city"); 
     int countryIdx = cursor.getColumnIndexOrThrow("country"); 
     while (cursor.moveToNext()) { 
      DataModel dataModel = new DataModel(); 
      dataModel.setName(cursor.getString(nameIdx)); 
      dataModel.setCity(cursor.getString(cityIdx)); 
      dataModel.setCountry(cursor.getString(countryIdx)); 
      data.add(dataModel); 
     } 
    } 
    Log.i("Hello", data.toString()); 
    return data; 
} 
-1

如果你想在方法返回一個列表,你可以不加StringBuffer的。 可能的解決方案是將其保存到類中的私有成員。

+0

爲什麼該方法需要私人領域?這是沒有意義的。 – Andreas

相關問題