MainActivity作为来自SampleDataProvider.class的返回空数据

时间:2018-11-19 09:39:54

标签: android sqlite listview arraylist

  

我没有从SampleDataProvider获得数据项。返回null   清单。请帮助。

     

MainActivity

public class MainActivity extends AppCompatActivity {
TextView tvOut;
ListView lOut;
List<DataItem> dataItemList = SampleDataProvider.dataItemList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvOut = findViewById(R.id.out);
    tvOut.setText("");
    for (DataItem dataItem : dataItemList) {
         tvOut.append(dataItem.getItemName() + "\n");
     }
 } }

SampleDataProvider

public class SampleDataProvider {
public static List<DataItem> dataItemList;
public static Map<String, DataItem> dataItemMap;

private static void addItem(DataItem dataItem){
dataItemList.add(dataItem);
dataItemMap.put(dataItem.getItemId(),dataItem);
}
static {
        dataItemList = new ArrayList<>();
        dataItemMap = new HashMap<>();
        addItem(new DataItem(null, "My menu Item", "a cateogry","a descriptoin", 1,9.95,"apple_pie.jpg"));
        addItem(new DataItem(null, "Quinoa Salmon Salad", "Salads","Our quinoa salad is served with quinoa, tomatoes, cucumber, scallions, and smoked salmon. Served with your choice of
    dressing.", 1, 12, "quinoa_salad.jpg"));
        } 
}

2 个答案:

答案 0 :(得分:0)

我认为您在主要活动中对dataItemList的分配也必须是静态的。

static List<DataItem> dataItemList = SampleDataProvider.dataItemList;

但是这不是面向对象的!

答案 1 :(得分:0)

我刚刚在DataItem中发现了错误的代码“ addItem方法”。

private String itemId;
private String itemName;
private String description;
private String category;
private String sortPosition;
private String price;
private String image;

此代码应为

private String itemId;
private String itemName;
private String description;
private String category;
private int sortPosition;
private double price;
private String image;

SmapleDataItem

addItem(new DataItem(null, "butthry", "description","category",1, 12, "images.jpg"));