user3556657
user3556657

Reputation: 93

Display data from SQLite Database to Cardview

I have implemented the CardView showing dummy cards. But I have to display data to this cards from SQLite database i.e., from each row to each card. Also I want to implement deletion of a particular row when delete button is pressed in the card. How can I do this?

This is my card fragment code:

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();
}

}

Upvotes: 0

Views: 9124

Answers (2)

Nadeem
Nadeem

Reputation: 93

Use this method to get the context parameter of database

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();
}

Upvotes: 0

Omkar
Omkar

Reputation: 1553

FOLLOW THESE STEPS:

1) Create sqlite database for your application using DB Helper.

Example:

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);
    }
}

To access above class:

FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());

2) You need to insert your data in database. Important thing is you must have an id column in table.

// 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);

Now, you have data in your database. (You can use below POJO class too, to insert data in table)

3) Make an POJO object to fetch data from database.

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) Reading data from database in form of 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) Get data list List<Example> example in RecyclerView's onBindViewHolder method and set your data with UI reference. Also set onClickListener in here

@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();
        }
    });
}

Hope this helps you or try watching some videos for more clarifications.

Upvotes: 4

Related Questions