如何在泛型类型List <model>中添加StringBuffer?

时间:2017-03-01 18:41:40

标签: java android generics collections

如何在泛型list<Model>中添加StringBuffer。我想在List<Model>中添加StringBuffer,但android studio强制我将通用更改为List<Stringbuffer>

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;
}

2 个答案:

答案 0 :(得分:0)

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

相反,在循环中创建一个新的DataModel对象,并将其添加到data列表中,也在循环内。

此外,请务必在完成Cursor后关闭try-with-resources,最好使用https://github.com/ngrx/example-app

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 :(得分:-1)

如果要在方法中返回List,则无法添加StringBuffer。 一种可能的解决方案是将其保存到类中的私有成员。