Android SQLite Database : INSERT SELECT DELETE – Swipe To Delete

Android SQLite Database : INSERT SELECT DELETE – Swipe To Delete







Our mission at ProgrammingWizards Youtube Channel  is to provide practical realworld examples.There is alot of theory on the web.But then its always easier to learn by doing.So we aim to fill that gap by providing quality examples,that you can easily extend and use in your app.
Today we talk about Swipe To Delete,of course from Swipe to Dismiss.We use ItemTouchHelper class,no third party library.We shall do these:

  •  INSERT,SELECT and DELETE to and from SQLite database.
  • To delete we shall use the Swipe to dismiss technique,in this case swipe to delete from database.
  • We then refresh our adapter for instant change notifications.

 

SQLite Swipe Delete Project Structure

SQLite Swipe Delete Project Structure

 

Lets jump straight in.We are going to have our SQlite database constants in one roof called Constants.Here it is :

 

package com.tutorials.hp.sqliteswipetodelete.mDataBase;
/**
 * Created by Oclemmy on 5/1/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class Constants {
    //COLUMNS
    static final String ROW_ID="id";
    static final String NAME="name";
    //DB PROPS
    static final String DB_NAME="ee_DB";
    static final String TB_NAME="ee_TB";
    static final int DB_VERSION=1;
    //CREATE TABLE
    static final String CREATE_TB="CREATE TABLE ee_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL);";
    //DROP TB
    static final String DROP_TB="DRP TABLE IF EXISTS "+TB_NAME;
}

 

Then all our CRUD SQLite operations,inserting data,selecting and updating we do inside our DBAdapter below :

 

package com.tutorials.hp.sqliteswipetodelete.mDataBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
 * Created by Oclemmy on 5/1/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class DBAdapter {
    Context c;
    SQLiteDatabase db;
    DBHelper helper;
    public DBAdapter(Context c) {
        this.c = c;
        helper=new DBHelper(c);
    }
    //OPEN DB
    public void openDB()
    {
        try {
            db=helper.getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //CLOSE DB
    public void closeDB()
    {
        try {
           helper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //INSERT/SAVE
    public boolean add(String name)
    {
        try {
        ContentValues cv=new ContentValues();
        cv.put(Constants.NAME, name);
         db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);
        return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    //SELECT/RETRIEVE
    public Cursor retrieve()
    {
        String[] columns={Constants.ROW_ID,Constants.NAME};
        return db.query(Constants.TB_NAME,columns,null,null,null,null,null);
    }
    //DELETE/REMOVE
    public boolean delete(int id)
    {
        try {
            int result=db.delete(Constants.TB_NAME,Constants.ROW_ID+" =?",new String[]{String.valueOf(id)});
            if(result>0) {
                return true;
            }
          } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

 

SQLite Swipe To Delete Insert Data Material Dialog

SQLite Swipe To Delete Insert Data Material Dialog

 

 

Our RecyclerView shall have an adapter class that's going to bind it data.This class shall derive from RecyclerView.Adapter :

 

package com.tutorials.hp.sqliteswipetodelete.mRecycler;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.tutorials.hp.sqliteswipetodelete.R;
import com.tutorials.hp.sqliteswipetodelete.mDataBase.DBAdapter;
import com.tutorials.hp.sqliteswipetodelete.mDataObject.Planet;
import java.util.ArrayList;
/**
 * Created by Oclemmy on 5/1/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
    Context c;
    ArrayList<Planet> planets;
    public MyAdapter(Context c, ArrayList<Planet> planets) {
        this.c = c;
        this.planets = planets;
    }
    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
        MyHolder holder=new MyHolder(v);
        return holder;
    }
    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
         holder.nametxt.setText(planets.get(position).getName());
    }
    @Override
    public int getItemCount() {
        return planets.size();
    }
    public void deletePlanet(int pos)
    {
        //GET ID
        Planet p=planets.get(pos);
        int id=p.getId();
        //DELETE FROM DB
        DBAdapter db=new DBAdapter(c);
        db.openDB();
        if(db.delete(id))
        {
            planets.remove(pos);
        }else
        {
            Toast.makeText(c,"Unable To Delete",Toast.LENGTH_SHORT).show();
        }
        db.closeDB();
        this.notifyItemRemoved(pos);
    }
}

 

We shall create a swipe helper class that's going to derive from ItemTouchHelper.SimpleCallback.Its going to take our Adapter reference and invoke the method for deleting data inside the onSwiped method :

 

package com.tutorials.hp.sqliteswipetodelete.mSwiper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import com.tutorials.hp.sqliteswipetodelete.mRecycler.MyAdapter;
/**
 * Created by Oclemmy on 5/1/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class SwipeHelper extends ItemTouchHelper.SimpleCallback {
   MyAdapter adapter;
    public SwipeHelper(int dragDirs, int swipeDirs) {
        super(dragDirs, swipeDirs);
    }
    public SwipeHelper( MyAdapter adapter) {
        super(ItemTouchHelper.UP | ItemTouchHelper.DOWN,ItemTouchHelper.LEFT);
        this.adapter = adapter;
    }
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        return false;
    }
    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
         adapter.deletePlanet(viewHolder.getAdapterPosition());
    }
}

 

 

Finally below is our MainActivity class :

 

package com.tutorials.hp.sqliteswipetodelete;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.tutorials.hp.sqliteswipetodelete.mDataBase.DBAdapter;
import com.tutorials.hp.sqliteswipetodelete.mDataObject.Planet;
import com.tutorials.hp.sqliteswipetodelete.mRecycler.MyAdapter;
import com.tutorials.hp.sqliteswipetodelete.mSwiper.SwipeHelper;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    RecyclerView rv;
    MyAdapter adapter;
    EditText nameEditText;
    Button saveBtn,retrieveBtn;
    ArrayList<Planet> planets=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter=new MyAdapter(this,planets);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayDialog();
            }
        });
        ItemTouchHelper.Callback callback=new SwipeHelper(adapter);
        ItemTouchHelper helper=new ItemTouchHelper(callback);
        helper.attachToRecyclerView(rv);
    }
    private void displayDialog()
    {
        Dialog d=new Dialog(this);
        d.setTitle("SQLite database");
        d.setContentView(R.layout.dialog_layout);
        nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
        saveBtn= (Button) d.findViewById(R.id.saveBtn);
        retrieveBtn= (Button) d.findViewById(R.id.retrieveBtn);
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 save(nameEditText.getText().toString());
            }
        });
        retrieveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPlanets();
            }
        });
        //SHOW DIALOG
        d.show();
    }
    //SAVE
    private void save(String name)
    {
        DBAdapter db=new DBAdapter(this);
        db.openDB();
        if(db.add(name))
        {
            nameEditText.setText("");
        }else
        {
            Toast.makeText(this,"Unable to save",Toast.LENGTH_SHORT).show();
        }
        db.closeDB();
    }
    //RETRIEVE
    private void getPlanets()
    {
        planets.clear();
        DBAdapter db=new DBAdapter(this);
        db.openDB();
        Cursor c=db.retrieve();
        while (c.moveToNext())
        {
            int id=c.getInt(0);
            String name=c.getString(1);
            Planet p=new Planet();
            p.setName(name);
            p.setId(id);
            planets.add(p);
        }
        db.closeDB();
        if(planets.size()>0)
        {
            rv.setAdapter(adapter);
        }
    }
}

 

RecyclerView Swipe To Delete

RecyclerView Swipe To Delete

 

Look,all the full source code is above ready for download.Download it,extract and import to your android studio.

 

 

 

If you prefer more explanations and also demo,then check the video tutorial below:

Android SQLite Database 07 : INSERT SELECT DELETE - Swipe To Delete [ItemTouchHelper]

 



    Leave a Reply

    Your email address will not be published. Required fields are marked *

    nine + 5 =

    COMMENTS