recyclerView不会显示我列表项的“真实”数据

问题描述 投票:0回答:1

我已经实现了recyclerView和SQLite数据库来保存/检索recylerview的数据,但是我在recyclerView上获得的数据不是应该显示的数据。没有SQLite数据库,recyclerView可以正常工作。

enter image description here

单击加号时,将弹出一个对话框,其中包含editext字段,用户可以在其中键入信息:

这里是DialogFragment类,用户应在其中编写其信息:

public class DialogAdd extends DialogFragment {

private Button okButton;
private EditText name, quantity, location, normalPrice, offerPrice;
private List<ShopListItem> shopListItem;
private Context context;
DatabaseHelper dbHelper;


@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    dbHelper = new DatabaseHelper(getContext());

    shopListItem = new ArrayList<>();
    context = getActivity();
}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.add_productdialog,container, false);
    getDialog().setCanceledOnTouchOutside(false);
    getDialog().setTitle("Add to shoplist");




    name = (EditText) rootView.findViewById(R.id.dialog_productname);
    quantity = (EditText) rootView.findViewById(R.id.dialog_qantity);
    location = (EditText) rootView.findViewById(R.id.dialog_location);
    normalPrice = (EditText) rootView.findViewById(R.id.dialog_normalPrice);
    offerPrice = (EditText) rootView.findViewById(R.id.dialog_offerPrice);

    okButton = (Button) rootView.findViewById(R.id.dialog_okButton);
    okButton.getBackground().setColorFilter(Color.parseColor("#2fbd4b"), PorterDuff.Mode.MULTIPLY);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (name.getText().toString().isEmpty()) {
                Toast.makeText(context, "You must add a name", Toast.LENGTH_LONG).show();
            } else {

              dbHelper.insertData(name.toString() ,quantity.toString(),location.toString(),normalPrice.toString(),offerPrice.toString());
                getDialog().dismiss();
            }


        }
    });

    return rootView;

}

这是mainActivity类,我在其中创建recylerview,适配器和数据库:

public class MainActivity extends AppCompatActivity{


private ImageButton addbutton;
private DialogAdd dialogAdd;
public static RecyclerView recyclerView;
private List<ShopListItem> shopListItems;
private SQLiteDatabase db;
private Cursor cursor;
private DatabaseHelper databaseHelper;
private ShoplistAdapter adapter;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.shoppinglist_mainactivity);


    databaseHelper = new DatabaseHelper(this);

    addbutton = (ImageButton) findViewById(R.id.addbtn);
    addbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialogAdd = new DialogAdd();
            dialogAdd.show(getSupportFragmentManager(), "addDialog");
        }
    });



    //RecyclerView
    recyclerView = (RecyclerView)findViewById(R.id.rv_shoppinglist);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(App.getAppContex());
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(linearLayoutManager);



    initializeData();
    adapter = new ShoplistAdapter(shopListItems);
    recyclerView.setAdapter(adapter);


}


private void initializeData(){

    shopListItems = new ArrayList<>();
    Cursor resultset = databaseHelper.getAllData();

    if (resultset.moveToFirst()){
        while(!resultset.isAfterLast()){

            shopListItems.add(new ShopListItem(resultset.getString(1), resultset.getString(2), resultset.getString(3), resultset.getString(4), resultset.getString(5)));

            resultset.moveToNext();
        }
    }
    resultset.close();


    shopListItems.add(new ShopListItem("Potato", "2 KG", "MALL", "7 kr", ""));
}

此类是定义数据库的位置:

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME ="dbshoplist.db";
public static final String TABLE_NAME ="product_table";

public static final String COL_ID = "ID";
public static final String COL_NAME ="NAME";
public static final String COL_QTY ="QUANTITY";
public static final String COL_LOCATION ="LOCATION";
public static final String COL_PRICE1 ="PRICE1";
public static final String COL_PRICE2 ="PRICE2";


/*
This constructor creates the database
 */
public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    SQLiteDatabase db = this.getWritableDatabase();
}


@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,QUANTITY TEXT,LOCATION TEXT,PRICE1 TEXT,PRICE2 TEXT)");


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}


public boolean insertData(String name, String qty, String location, String price1, String price2){


    SQLiteDatabase db = this.getWritableDatabase();

    // content value is a row, and we fill it with the put();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_NAME, name);
    contentValues.put(COL_QTY, qty);
    contentValues.put(COL_LOCATION, location);
    contentValues.put(COL_PRICE1, price1);
    contentValues.put(COL_PRICE2, price2);


    long result = db.insert(TABLE_NAME, null,contentValues);

    if(result == -1) {
        return false;
    }else{
        return true;
        }
    }


public Cursor getAllData(){

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursorResults = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return cursorResults;

}

我的recyclerView适配器类:

 public class ShoplistAdapter extends RecyclerView.Adapter<ShoplistAdapter.ViewHolder>{

List<ShopListItem> shopListItems;
public ShoplistAdapter(List<ShopListItem> shopListItems) {
    this.shopListItems = shopListItems;
}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);
    View shoplist_itemView = inflater.inflate(R.layout.shop_list_item, parent, false);
    ViewHolder viewHolder = new ViewHolder(shoplist_itemView);

    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {


    holder.location.setText(shopListItems.get(position).location.toString());
    holder.normalPrice.setText(shopListItems.get(position).normalprice.toString());
    holder.offerPrice.setText(shopListItems.get(position).offerprice.toString());

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(shopListItems.get(position).quantity + "  " + shopListItems.get(position).name);
    holder.productname.setText(stringBuilder);

    if(!shopListItems.get(position).offerprice.toString().isEmpty()){
        holder.normalPrice.setPaintFlags(holder.normalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

    }

    if(shopListItems.get(position).normalprice.isEmpty()){
        holder.normalPrice.setVisibility(View.GONE);
    }


    holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(isChecked == true){
                holder.productname.setPaintFlags(holder.productname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.productname.setTextColor(Color.parseColor("#40000000"));
            }else{
                holder.productname.setPaintFlags(0 | Paint.ANTI_ALIAS_FLAG);
                holder.productname.setTextColor(Color.BLACK);
            }
        }
    });
}

@Override
public int getItemCount() {
    return shopListItems.size();
}


public static class ViewHolder extends RecyclerView.ViewHolder{


    private CheckBox checkBox;
    private TextView productname, quantity, location, normalPrice, offerPrice;
    private ImageButton edit_icon, delete_icon;

    public ViewHolder(View itemView) {
        super(itemView);

        productname = (TextView)itemView.findViewById(R.id.product_name);
        location = (TextView)itemView.findViewById(R.id.product_location);
        normalPrice = (TextView)itemView.findViewById(R.id.product_price);
        offerPrice = (TextView)itemView.findViewById(R.id.product_offer_price);
        edit_icon = (ImageButton)itemView.findViewById(R.id.editShopItem_Icon);
        delete_icon = (ImageButton)itemView.findViewById(R.id.shopitem_delete_icon);
        checkBox = (CheckBox) itemView.findViewById(R.id.bought_checkbox);

    }
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}
android sqlite
1个回答
0
投票

发生这种情况是因为您正在调用ShopListItem对象的字段的toString()方法:shopListItems.get(position).location.toString()

相反,为ShopListItem类的字段创建吸气剂方法,例如

public getLocation() {
   return location;
}

并且只需调用它们即可获取数据。

© www.soinside.com 2019 - 2024. All rights reserved.