显示从SQLite数据库到Cardview的数据

时间:2016-03-05 20:08:39

标签: android sqlite

我已经实现了显示虚拟卡的CardView。但我不得不 从SQLite数据库向这些卡显示数据,即从每行到 每张卡片。此外,我想在卡中按下删除按钮时删除特定行。我怎么能这样做?

这是我的卡片段代码:

public class UserAppFragment extends Fragment {

public UserAppFragment() {
    // Required empty public constructor
}

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


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

    //using recycle view cutomizing card views
    RecyclerView recyclerView = (RecyclerView) inflater.inflate(
            R.layout.recycler_view, container, false);
    ContentAdapter adapter = new ContentAdapter();
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Click action
            Toast.makeText(getContext(),"FAB",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getContext(), EventAdder.class);
            startActivity(intent);
        }
    });

    return recyclerView;
}
//view holder for cards data start
public static class ViewHolder extends RecyclerView.ViewHolder {
    public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.fragment_home_card_list, parent, false));
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = v.getContext();
                Intent intent = new Intent(context, EventAdder.class);
                context.startActivity(intent);
            }
        });


        ImageButton shareImageButton =
                (ImageButton) itemView.findViewById(R.id.share_button);
        shareImageButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Snackbar.make(v, "Added to Favorite",
                        Snackbar.LENGTH_LONG).show();
            }
        });

        ImageButton deleteImageButton = (ImageButton) itemView.findViewById(R.id.delete_button);
        deleteImageButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Snackbar.make(v, "Card deleted",
                        Snackbar.LENGTH_LONG).show();
            }
        });

    }
} //view holder end

// start recycleview.adapter wrapping viewholder created
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
    // Set numbers of List in RecyclerView.
    private static final int LENGTH = 15;
    public ContentAdapter(){


    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // no-op
    }

    @Override
    public int getItemCount() {
        return LENGTH;
    }
}
// end recycleview.adapter wrapping viewholder created

@Override
public void onDetach() {
    super.onDetach();
}

}

2 个答案:

答案 0 :(得分:4)

遵循这些步骤:

1)使用DB Helper为您的应用程序创建sqlite数据库。

示例:

public class FeedReaderDbHelper extends SQLiteOpenHelper {
    // If you change the database schema, you must increment the database version.
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "FeedReader.db";

    public FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }
}

要访问上述课程:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());

2)您需要在数据库中插入数据。重要的是,您必须在表格中包含 id 列。

// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
         FeedEntry.TABLE_NAME,
         FeedEntry.COLUMN_NAME_NULLABLE,
         values);

现在,您的数据库中有数据。 (您也可以使用以下POJO类,在表格中插入数据)

3)创建 POJO对象以从数据库中获取数据。

public class Example{

    int id;

    String title;

    String content;

    public Example() {

    }

    public Example(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }
}

4)以List<Example>

的形式从数据库中读取数据
SQLiteDatabase db = mDbHelper.getReadableDatabase();

String selectQuery = "SELECT  * FROM yourTableName";

Cursor c = database.rawQuery(selectQuery, null);

List<Example> example = new ArrayList<Example>();

if (cursor.moveToFirst()) { 
    do { 

        example.add(new Example(
            c.getInt(0),        // id
            c.getString(1),     // title
            c.getString(2)      // content
        ));

    } while (cursor.moveToNext()); 
}

5)在RecyclerView的 onBindViewHolder 方法中获取数据列表List<Example> example,并使用UI参考设置数据。也在这里设置onClickListener

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

    Example temp = example.get(position);

    holder.tvTitle.setText(temp.title);

    holder.tvContent.setText(temp.content);

    holder.deleteImageButton.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {

            // Define 'where' part of query.
            String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

            // Specify arguments in placeholder order.
            String[] selectionArgs = { String.valueOf(temp.id) };

            // Issue SQL statement.
            db.delete(table_name, selection, selectionArgs);

            // delete item from list
            example.remove(temp);

            // adapter must be in global scope.
            adapter.notifyDataSetChanged();

            Snackbar.make(v, "Card deleted",
                    Snackbar.LENGTH_LONG).show();
        }
    });
}

希望这可以帮助您或尝试观看一些视频以获得更多说明。

答案 1 :(得分:0)

使用此方法获取数据库的上下文参数

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

     CardView cardView = holder.cardView;

     Context context = cardView.getContext();
     YoupostDatabase youpostDatabase = new YoupostDatabase(context);
     SQLiteDatabase db = youpostDatabase.getReadableDatabase();
}