首先,我要描述有关我的问题的一些解释, 我有两个片段名称为“ Main Fragment”,第二个为“ Cart Fragment”
1 ==> Main Fragment-包含recyclerview,其中数据来自Firestore并在recyclerview中设置,当用户单击“添加”或“删除”按钮时,将在sqlite中输入和更新数据。
2 ==>购物车片段-包含recyclerview,其中数据来自SQLITE,并设置在recycelerview中。
我的问题是,当我从购物车片段导航至主片段时,首先检查是否有任何商品已经保存在sqlite中,如果存在,则从该商品的购物车片段中获取商品的总数量(包括名称,价格等其他数据)等等)并设置在主fragmnet中。
这里是主片段适配器的代码
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.TV_OFF.setText(_mylistdata.get(position).getDiscount()+"% OFF");
//"Rs "+
holder.TV_CURNT_PRICE.setText(_mylistdata.get(position).getCurr_price());
holder.TV_OLD_PRICE.setText(_mylistdata.get(position).getOld_price());
holder.TV_NAME.setText(_mylistdata.get(position).getName());
holder.TV_OFFER_DES.setText(_mylistdata.get(position).getOffers_des());
holder.TV_UNIT.setText(_mylistdata.get(position).getUnit_products()+" Unit");
Picasso.get().load(_mylistdata.get(position).getImgId()).placeholder(R.drawable.no_image_find).into(holder.imageView);
holder.add_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(context, "pos="+prd_id, Toast.LENGTH_SHORT).show();
holder.add_btn.setVisibility(View.GONE);
holder.TV_REMOVEITEM.setVisibility(View.VISIBLE);
holder.TV_TOTALITEM.setVisibility(View.VISIBLE);
holder.TV_ADDITEM.setVisibility(View.VISIBLE);
count_value=1;
holder.TV_TOTALITEM.setText(Integer.toString(count_value));
// get data from views
getDataFromViews(position);
total_qty_pro= (String) holder.TV_TOTALITEM.getText();
//qty_pro=_mylistdata.get(position).getUnit_products();
qty_new=qty_pro+" Unit";
saveData_To_SQLITE(new_name,qty_new,price_pro,price_old,total_qty_pro,image_id,context);
}
});
holder.TV_REMOVEITEM.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
//productId= (int) getItemId(position);
count_value--;
if (count_value<1)
{
Log.d(TAG,"Remove button is pressed");
holder.add_btn.setVisibility(View.VISIBLE);
holder.TV_REMOVEITEM.setVisibility(View.GONE);
holder.TV_TOTALITEM.setVisibility(View.GONE);
holder.TV_ADDITEM.setVisibility(View.GONE);
count_value=1;
String prdct_name= _mylistdata.get(position).getName();
delete_record(prdct_name,context);
}else {
//Data_parsing.setCountText(count_value);
holder.TV_TOTALITEM.setText(Integer.toString(count_value));
total_qty_pro= (String) holder.TV_TOTALITEM.getText();
String prdct_name= _mylistdata.get(position).getName();
UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);
}
}
});
holder.TV_ADDITEM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG,"Add button is pressed");
count_value++;
//Data_parsing.setCountText(count_value);
holder.TV_TOTALITEM.setText(Integer.toString(count_value));
total_qty_pro= (String) holder.TV_TOTALITEM.getText();
String prdct_name= _mylistdata.get(position).getName();
UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);
}
});
}
这是我的SQLite类,其中定义了用于保存,更新和删除sqlite中数据的静态方法
公共类SQLITE_RUD {
// Save data to sqlite
public static void saveData_To_SQLITE(String name_pro, String qty_pro, String price_pro,String price_old, String total_qty_pro, String image_id, Context context) {
DBAdapter db = new DBAdapter(context);
db.openDB();
long result = db.add(name_pro, qty_pro, price_pro,price_old, total_qty_pro, image_id);
if (result > 0) {
Toast.makeText(context, "Data is saved succeffuly", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Unable to save", Toast.LENGTH_SHORT).show();
}
db.closeDB();
}
// update data in sqlite
public static void UPDATE_SQL_DATA(String p_name, String total_qty_pro, Context context)
{
DBAdapter db=new DBAdapter(context);
db.openDB();
try {
long result=db.update_DB(p_name,total_qty_pro);
if(result>0)
{
Toast.makeText(context, "Updated Sucesfully", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "Unable to update", Toast.LENGTH_SHORT).show();
}
}catch (Exception e)
{
Log.d("MyListAdapter","error_update="+e);
}
db.closeDB();
}
// Delete data from SQlite
public static void delete_record(String prdct_name,Context context) {
//
DBAdapter db=new DBAdapter(context);
db.openDB();
try {
long result=db.Delete_DB(prdct_name);
if(result>0)
{
Toast.makeText(context, "Deleted Sucesfully", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "Unable to Delete", Toast.LENGTH_SHORT).show();
}
}catch (Exception e)
{
Log.d("MyListAdapter","error_delete="+e);
}
db.closeDB();
}
}
在这里,我创建了类名称广告DBAdapter,其中定义了保存,更新和检索需求的方法。
public class DBAdapter {
Context c;
SQLiteDatabase db;
DbHelper database_helper; // on create and on upgrade is defined
public DBAdapter(Context c) {
this.c = c;
database_helper=new DbHelper(c);
}
//OPEN DB
public void openDB()
{
try {
db=database_helper.getWritableDatabase();
db=database_helper.getReadableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
//CLOSE DB
public void closeDB()
{
try {
database_helper.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//INSERT/SAVE
public long add(String P_name,String P_qty,String P_price,String P_OldPrice,String P_Total_qty, String P_Image)
{
try {
ContentValues cv=new ContentValues();
// cv.put(KEY_ItemID, P_id);
cv.put(KEY_ProductName, P_name);
cv.put(KEY_ProductQuantity, P_qty);
cv.put(KEY_ProductPrice, P_price);
cv.put(KEY_OldPrice, P_OldPrice);
cv.put(KEY_ProductTotal, P_Total_qty);
cv.put(KEY_ProductImage,P_Image);
return db.insert(Table_name, KEY_RowID, cv);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public long update_DB(String name_prdct, String prdct_TOTAL_QTY)
{
try
{
ContentValues cv=new ContentValues();
cv.put(KEY_ProductTotal,prdct_TOTAL_QTY);
return db.update(Table_name,cv,KEY_ProductName +" =?",new String[]{String.valueOf(name_prdct)});
//return;
}catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
//DELETE
public long Delete_DB(String prdct_name)
{
try
{
return db.delete(Table_name,KEY_ProductName+" =?",new String[]{String.valueOf(prdct_name)});
}catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
//SELECT/RETRIEVE
public Cursor retrieve() {
String[] columns = {KEY_RowID,KEY_ProductName,KEY_ProductQuantity, KEY_ProductPrice,KEY_OldPrice, KEY_ProductTotal, KEY_ProductImage};
return db.query(Constants.Table_name, columns, null, null, null, null, null);
}
}
这是我的购物车片段
public class CartFragment extends Fragment {
private static final String Tag ="CartFragment" ;
FragmentManager fragmentManager;
RecyclerView recyclerView;
RelativeLayout proceedBtn;
TextView finalprice_bottom, finalprice_upper;
Adapter_chart adapter;
View view;
ArrayList<Chart_getter_setter> chartGetterSetters = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_cart, container, false);
recyclerView = view.findViewById(R.id.chart_recyclerview);
proceedBtn=view.findViewById(R.id.bottomChart);
finalprice_upper=view.findViewById(R.id.price);
finalprice_bottom =view.findViewById(R.id.FinalPrice_TV);
proceedBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(savedInstanceState==null) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container, ProceedFragment.newInstance()).addToBackStack(null).commit();
}
}
});
adapter = new Adapter_chart(getActivity(), fragmentManager, chartGetterSetters);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
//RETRIEVE
retrieve_data();
getActivity().setTitle("Final chart");
return view;
}
private void retrieve_data() {
DBAdapter db = new DBAdapter(getContext());
db.openDB();
chartGetterSetters.clear();
//RETRIEVE
Cursor c = db.retrieve();
while (c.moveToNext())
{
int index_id=c.getColumnIndex(Constants.KEY_RowID);
int index_name=c.getColumnIndex(Constants.KEY_ProductName);
int index_qty=c.getColumnIndex(Constants.KEY_ProductQuantity);
int index_price=c.getColumnIndex(Constants.KEY_ProductPrice);
int index_oldprice=c.getColumnIndex(Constants.KEY_OldPrice);
int index_total=c.getColumnIndex(Constants.KEY_ProductTotal);
int index_image=c.getColumnIndex(Constants.KEY_ProductImage);
int id=c.getInt(index_id);
String name=c.getString(index_name);
String qty=c.getString(index_qty);
String price=c.getString(index_price);
String oldPrice=c.getString(index_oldprice);
String total=c.getString(index_total);
String IMAGE=c.getString(index_image);
Chart_getter_setter p=new Chart_getter_setter(name,qty,price,oldPrice,total,IMAGE);
//ADD TO ARRAYLIS
chartGetterSetters.add(p);
//CHECK IF ARRAYLIST ISNT EMPTY
if(chartGetterSetters.size()>0)
{
int totalPrice = 0;
int total_qty=0;
for(int j = 0 ; j < chartGetterSetters.size(); j++) {
totalPrice += Integer.parseInt(chartGetterSetters.get(j).getPrice_prdct())*Integer.parseInt(chartGetterSetters.get(j).getTotal_quantity()) ;
total_qty += Integer.parseInt(chartGetterSetters.get(j).getTotal_quantity());
}
String tProice=String.valueOf(totalPrice);
finalprice_upper.setText("Rs "+tProice);
finalprice_bottom.setText(String.valueOf(total_qty));//totelPriceTV.setText(tProice);
recyclerView.setAdapter(adapter);
}
}
}
}
这是我的转接车
public class Adapter_chart extends RecyclerView.Adapter<ViewHolder_chart> {
private static final String TAG ="Adapater_chart" ;
ArrayList<Chart_getter_setter> _chartdata;
Context context;
FragmentManager fragmentManager;
String total = "";
public Adapter_chart(Context context, FragmentManager fragmentManager,
ArrayList<Chart_getter_setter> _chartdata) {
this.context = context;
this.fragmentManager = fragmentManager;
this._chartdata = _chartdata;
_chartdata = new ArrayList<>();
}
@NonNull
@Override
public ViewHolder_chart onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.chart_single_item, viewGroup, false);
ViewHolder_chart viewHolder = new ViewHolder_chart(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder_chart viewHolder_chart, final int i) {
viewHolder_chart.p_name_CHART_tv.setText(_chartdata.get(i).getName_prdct()); // set name of product
//Replace these two methods
viewHolder_chart.p_price_CHART_tv.setText(_chartdata.get(i).getPrice_prdct()); // set quantity
viewHolder_chart.p_quantity_Chart_tv.setText(_chartdata.get(i).getUnit_prdct()); // set price
////////////////////////////////
viewHolder_chart.p_totalITem_CHART_tv.setText(_chartdata.get(i).getTotal_quantity());
Log.d("Adapter_chart", "bitmap=" + _chartdata.get(i).getImage_prdct());
//viewHolder_chart.p_img_CHART.setImageBitmap(_chartdata.get(i).getImage_prdct());
Picasso.get().load(_chartdata.get(i).getImage_prdct()).placeholder(R.drawable.no_image_find).into(viewHolder_chart.p_img_CHART);
viewHolder_chart.p_add_CHART_tv.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
Log.d(TAG,"Add button is pressed");
int count_value= Integer.parseInt((String) viewHolder_chart.p_totalITem_CHART_tv.getText());
count_value++;
viewHolder_chart.p_totalITem_CHART_tv.setText(Integer.toString(count_value));
String total_qty_pro= (String) viewHolder_chart.p_totalITem_CHART_tv.getText();
String prdct_name= (String) _chartdata.get(i).getName_prdct();
UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);
}
});
viewHolder_chart.p_remove_CHART_tv.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
int count_value= Integer.parseInt((String) viewHolder_chart.p_totalITem_CHART_tv.getText());
count_value--;
if (count_value<1)
{
Log.d(TAG,"Remove button is pressed");
String name_prdct= (String) viewHolder_chart.p_name_CHART_tv.getText();
delete_record(name_prdct,context);
_chartdata.remove(i);
notifyDataSetChanged();
}else {
viewHolder_chart.p_totalITem_CHART_tv.setText(Integer.toString(count_value));
String total_qty_pro= (String) viewHolder_chart.p_totalITem_CHART_tv.getText();
String prdct_name= (String) _chartdata.get(i).getName_prdct();
UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);
}
}
viewHolder_chart.item_remove_imageview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name_prdct= (String) viewHolder_chart.p_name_CHART_tv.getText();
delete_record(name_prdct,context);
_chartdata.remove(i);
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return _chartdata.size();
}
}
答案 0 :(得分:0)
SQLite替换语句适合您。
REPLACE INTO table_name(col1,col2)VALUES(val1,val2);
替换将 -如果不存在则插入db -更新数据库(如果已经存在)
答案 1 :(得分:0)
最简单的方法是将Room与LiveData一起使用。使用这些组件,您可以在数据库表中添加,删除甚至编辑一行时获得更新的值。您可以从这里学习这些组件。 LiveData-Room,您也可以阅读此google codelab。 但是,如果您不想使用这些组件(我强烈建议您使用它们),我认为您可以在活动onResum()方法中获取数据库中的所有行,并使用新数据更新RecyclerView。