如何从android studio中的recycler视图将数据添加到SQLite数据库中

Posted

技术标签:

【中文标题】如何从android studio中的recycler视图将数据添加到SQLite数据库中【英文标题】:How to add data into SQLite database from recycler view in android studio 【发布时间】:2021-09-06 07:34:22 【问题描述】:

我正在编写代码以将回收站视图项目显示到收藏夹片段,但是当我选择收藏夹按钮时,它不会将数据插入数据库。请帮帮我。代码如下。

日志猫显示:(1)no such table: favorites in "INSERT INTO favorites(Contact,Type,name,image,Favorites_status,Budget) VALUES (?,?,?,?,?,?)"

另外,您能告诉我如何将共享首选项添加到收藏夹按钮。

db.insert 即将变为 -1。

我的收藏夹:


package com.example.bottom.Favorites;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

import java.nio.channels.SelectableChannel;

public class FavDB extends SQLiteOpenHelper 

    private static final String DB_NAME = "event.db";
    private static final String TABLE_NAME = "favorites";
    public static final String COL_ID = "ID";
    public static final String Venue_image = "image";
    public static final String Venue_name = "name";
    public static final String Venue_type = "Type";
    public static final String Venue_budget = "Budget";
    public static final String Venue_contact = "Contact";
    public static final String FAV_STATUS = "Favorites_status";


    public FavDB( Context context) 
        super(context, DB_NAME, null, 1);

    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL(" CREATE TABLE " +TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Venue_name + " TEXT, " +Venue_type+ " TEXT, " +Venue_budget+ " TEXT, "+Venue_image+ " TEXT, "+Venue_contact+ " TEXT, "+FAV_STATUS+ " TEXT)");

    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        db.execSQL(" drop table if exists " +TABLE_NAME);
        onCreate(db);

    


        'inserting the data into database'
     public boolean inserttVenueData(FavVenueItem favVenueItem) 
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(Venue_name, favVenueItem.getVenuename());
        cv.put(Venue_image, favVenueItem.getImageResourse());
        cv.put(Venue_type, favVenueItem.getType());
        cv.put(Venue_budget, favVenueItem.getBudget());
        cv.put(Venue_contact, favVenueItem.getContact());
        cv.put(FAV_STATUS, 1);
        long result=db.insert(TABLE_NAME, null, cv);

        if (result == -1)

            Log.d("not added","the venue was not added");
            return false;
        else 
            Log.d("added", "the venue was added");
            return true;
    

我的 VenueAdapter:

    package com.example.bottom.Favorites;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bottom.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import static android.content.Context.MODE_PRIVATE;

public class VenueAdapter  extends RecyclerView.Adapter<VenueAdapter.ViewHolder> 
    private ArrayList<FavVenueItem> VenueItemsList;
    private Context context;
    private FavDB favDB;


    public VenueAdapter(ArrayList<FavVenueItem> VenueItems, Context context) 
        this.VenueItemsList = VenueItems;
        this.context = context;
    

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        favDB = new FavDB(context);
      

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rows,
                parent, false);
        return new ViewHolder(view);
    

   
    @Override
    public void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position) 
        final FavVenueItem venueItem = VenueItemsList.get(position);

        holder.ImageView.setImageResource(VenueItemsList.get(position).getImageResourse());
        holder.Name.setText(VenueItemsList.get(position).getVenuename());
        holder.venuetype.setText(VenueItemsList.get(position).getType());
        holder.venuebudget.setText(VenueItemsList.get(position).getBudget());
        holder.venuecontact.setText(VenueItemsList.get(position).getContact());

    

    @Override
    public int getItemCount() 
        return VenueItemsList.size();
    

    public class ViewHolder extends RecyclerView.ViewHolder 


        ImageView ImageView;
        TextView Name, venuetype, venuebudget, venuecontact;
        Button favbtn;
//        FloatingActionButton fab1;


        public ViewHolder(@NonNull @NotNull View itemView) 
            super(itemView);

            ImageView = itemView.findViewById(R.id.venueimage);
            Name = itemView.findViewById(R.id.venunename);
            venuetype = itemView.findViewById(R.id.type);
            venuebudget = itemView.findViewById(R.id.budget);
            venuecontact = itemView.findViewById(R.id.contact);
            favbtn = itemView.findViewById(R.id.favbtn);


            favbtn.setOnClickListener(new View.OnClickListener() 

                @Override
                public void onClick(View view) 
                    int position = getAdapterPosition();
                    FavVenueItem venueItem = VenueItemsList.get(position);


                    if (venueItem.getFavStatus().equals("0")) 
                        venueItem.setFavStatus("1");
                        favDB.inserttVenueData(venueItem);
                        Log.d("clicked", "button clicked");


                       favbtn.setBackgroundResource(R.drawable.ic_baseline_favorite_24);


                     else 
                        venueItem.setFavStatus("0");
                        favbtn.setBackgroundResource(R.drawable.ic_baseline_favorite_border_24);

                    
                
            );

        
    


我的 FavVenueItem:(型号)

package com.example.bottom.Favorites;

public class FavVenueItem 
    private int imageResourse;
    private String venuename;
    private String type;
    private String budget;
    private String contact;
    private String favStatus;

    public FavVenueItem()

    public FavVenueItem(int imageResourse,String venuename, String favStatus, String type, String budget, String contact, String key_id)
        this.imageResourse=imageResourse;
        this.venuename=venuename;
        this.type=type;
        this.budget=budget;
        this.contact=contact;
        this.favStatus=favStatus;
    

    public int getImageResourse() 
        return imageResourse;
    

    public void setImageResourse(int imageResourse) 
        this.imageResourse = imageResourse;
    

    public String getVenuename() 
        return venuename;
    

    public void setVenuename(String venuename) 
        this.venuename = venuename;
    

    public String getType() 
        return type;
    

    public void setType(String type) 
        this.type = type;
    

    public String getBudget() 
        return budget;
    

    public void setBudget(String budget) 
        this.budget = budget;
    

    public String getContact() 
        return contact;
    

    public void setContact(String contact) 
        this.contact = contact;
    

    public String getFavStatus() 
        return favStatus;
    

    public void setFavStatus(String favStatus) 
        this.favStatus = favStatus;
    




我的片段:

package com.example.bottom;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bottom.Favorites.FavVenueItem;
import com.example.bottom.Favorites.VenueAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

public class VenueListFragment extends Fragment 
    private ArrayList<FavVenueItem> VenueItems = new ArrayList<>();
    FloatingActionButton fab1;

    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        View v = inflater.inflate(R.layout.venuelist, container, false);
        RecyclerView recyclerView = v.findViewById(R.id.vendors_list);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(new VenueAdapter(VenueItems,getActivity()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));



        setData();




        return v;


    

    private void setData() 

        VenueItems.add(new FavVenueItem(R.drawable.theritvaan, "The Ritvaan", "0", "Wedding venue", "1000/plate onwards", "1234567891", "0"));
        VenueItems.add(new FavVenueItem(R.drawable.theshaurya, "The Shaurya", "0", "Wedding venue", "2000/plate onwards", "1234567891", "1"));
        VenueItems.add(new FavVenueItem(R.drawable.diamondcrown, "Diamond Crown", "0", "Wedding venue", "1100/plate onwards", "1234567891", "2"));
        VenueItems.add(new FavVenueItem(R.drawable.theimperialboutique, "The Imperial Boutique", "0", "Wedding venue", "1000/plate onwards", "1234567891", "3"));

    



请帮帮我! 非常感谢!

【问题讨论】:

检查你正在查询/插入的表是否存在? 你能在按钮中记录你的 venuitem 点击像 Log.d("venuItem",new Gson().toJson(venueItem)); @DharmenderManral 我的 logcat 显示:2021-06-23 00:13:34.177 14472-14472/com.example.bottom D/未添加:未添加场地 2021-06-23 00 :13:34.205 14472-14472/com.example.bottom D/venuItem: "budget":"1000/plate onwards","contact":"1234567891","favStatus":"1","imageResourse":2131165335 ,"type":"婚礼场地","venuename":"The Ritvaan" @ShekharSuman logcat 说不存在这样的表,你能告诉我如何修复它吗? @NehaM。您可以在构造函数调用上使用 oncreate() 方法来解决此问题。如果您打算在复杂的应用程序中使用此数据库。我建议创建一个 DBManger 类,您可以使用它在一个地方创建和初始化应用程序的所有表。您可以在 GitHub 中找到许多 DBManager 类示例。 【参考方案1】:

尝试使用以下查询,您似乎在状态列中传递了 int 值。

   @Override
public void onCreate(SQLiteDatabase db) 
    db.execSQL(" CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Venue_name + " TEXT, " + Venue_type + " TEXT, " + Venue_budget + " TEXT, " + Venue_image + " TEXT, " + Venue_contact + " TEXT, " + FAV_STATUS + " INTEGER" + ")");


【讨论】:

在执行此查询之前从移动设备上卸载以前的应用 删除现有数据库有帮助,谢谢!

以上是关于如何从android studio中的recycler视图将数据添加到SQLite数据库中的主要内容,如果未能解决你的问题,请参考以下文章

我的应用程序的Recycler View问题中的Android Studio SearchView过滤器

Recycler视图在android studio中未显示一张卡片视图

Bitmap.recycle引发的血案

如何使用 youtube data api v3 中的 nextPageToken 在 android recycler 视图中加载更多视频

如何根据用户在Android Studio(Java)中输入的条件显示可绘制对象

Android Honeycomb 中的 Bitmap#recycle() 实际上做了啥?