Android SQLite Database : INSERT SELECT DELETE – ContextMenu Delete

Android RSS : GridView- Downlaod,Parse,Show Headlines With Images and Text
Read-only properties in JavaFX 8
IDG Contributor Network: The top 5 Java 8 features for developers

Android SQLite Database : INSERT SELECT DELETE – ContextMenu Delete







Yes,we continue with the Android SQlite database tutorials.Our mission on the web is to provide quality realworld,practical examples.There is alot of theory on books but not very practical examples.That's our aim at ProgrammingWizards.
Today we see how to insert data to sqlite database from an input dialog,select that data and show it in a RecyclerView.
We shall also see how to delete.Now for deleting we shall use a ContextMenu.
User longclicks/long presses a RecyclerView card,then selects the action to perform.
In short :

  •  INSERT,SELECT and DELETE data to and from SQlite database.
  •  When uses longpresses,he gets presented with a ContextMenu to select the action to perform.
  • If he selects "New" we show an input dialog.While if he selects "Delete",we delete the data from our database.

 

SQLite CRUD ContextMenu Project Structure

SQLite CRUD ContextMenu Project Structure

 

We shal jump into the deep end straight way.

Here's our Constants SQlite database class.Its purpose is to hold our database constants in one roof :

 

package com.tutorials.hp.sqlitecontextmenudelete.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="ff_DB";
    static final String TB_NAME="ff_TB";
    static final int DB_VERSION=1;
    //CREATE TB
    static final String CREATE_TB="CREATE TABLE ff_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL);";
    //TABLE DROP STMT
    static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;
}

 

Then in our DBAdapter class,we shall carry out all our CRUD operations : INSERTING,SELECTING and DELETING.

 

package com.tutorials.hp.sqlitecontextmenudelete.mDataBase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
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
    public void openDB()
    {
        try
        {
           db=helper.getWritableDatabase();
        }catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
    //CLOSE DB
    public void closeDB()
    {
        try
        {
            helper.close();
        }catch (SQLException 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 (SQLException e)
        {
            e.printStackTrace();
        }
        return false;
    }
    //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 (SQLException e)
        {
            e.printStackTrace();
        }
        return false;
    }
}

 

SQLite CRUD Insert data Material Dialog

SQLite CRUD Insert data Material Dialog

 

Remember we shall be using using  a RecyclerView as our component,therefore here's our adapter class :

 

package com.tutorials.hp.sqlitecontextmenudelete.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.sqlitecontextmenudelete.R;
import com.tutorials.hp.sqlitecontextmenudelete.mDataBase.DBAdapter;
import com.tutorials.hp.sqlitecontextmenudelete.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;
    int selectedPos;
    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());
        holder.setLongClickListener(new MyLongClickListener() {
            @Override
            public void onLongClick(int pos) {
                selectedPos=pos;
            }
        });
    }
    @Override
    public int getItemCount() {
        return planets.size();
    }
    //DELETE PLANET
    public void deletePlanet()
    {
        //GET ID
        Planet p=planets.get(selectedPos);
        int id=p.getId();
        //DELETE IT FROM DB
        DBAdapter db=new DBAdapter(c);
        db.openDB();
        if(db.delete(id))
        {
            //DELETE ALSO FROM ARRAYLIST
            planets.remove(selectedPos);
        }else {
            Toast.makeText(c,"Unable To Delete",Toast.LENGTH_SHORT).show();
        }
        db.closeDB();
        this.notifyItemRemoved(selectedPos);
    }
}

 

With contextmenu we simply mean you longclick and you are then presented with a menu where you can select a menu item.Therefore we need to implement the OnLongClickListener.But first lets define its signature :

 

package com.tutorials.hp.sqlitecontextmenudelete.mRecycler;
/**
 * Created by Oclemmy on 5/1/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public interface MyLongClickListener {
    void onLongClick(int pos);
}

 

The above LongClickListener interface shall get implemented by our ViewHolder class.Take note that also we implement the OnCreateContextMenuListener interface as well :

 

package com.tutorials.hp.sqlitecontextmenudelete.mRecycler;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import com.tutorials.hp.sqlitecontextmenudelete.R;
/**
 * Created by Oclemmy on 5/1/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class MyHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener,View.OnCreateContextMenuListener {
    TextView nameTxt;
    MyLongClickListener longClickListener;
    public MyHolder(View itemView) {
        super(itemView);
        this.nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
        itemView.setOnLongClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }
    public void setLongClickListener(MyLongClickListener longClickListener)
    {
        this.longClickListener=longClickListener;
    }
    @Override
    public boolean onLongClick(View v) {
        this.longClickListener.onLongClick(getLayoutPosition());
        return false;
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        //OUR CONTEXT MENU
        menu.setHeaderTitle("ACTION : ");
        menu.add(0,0,0,"New");
        menu.add(0,1,0,"Delete");
    }
}

 

Finally we have our MainActivity as below :

 

package com.tutorials.hp.sqlitecontextmenudelete;
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.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.sqlitecontextmenudelete.mDataBase.DBAdapter;
import com.tutorials.hp.sqlitecontextmenudelete.mDataObject.Planet;
import com.tutorials.hp.sqlitecontextmenudelete.mRecycler.MyAdapter;
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 view) {
                displayDialog();
            }
        });
    }
    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();
            }
        });
        d.show();
    }
    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();
        //REFRESH
        getPlanets();
    }
    private void getPlanets()
    {
        planets.clear();
        DBAdapter db=new DBAdapter(this);
        db.openDB();
        Planet p=null;
        Cursor c=db.retrieve();
        while (c.moveToNext())
        {
            int id=c.getInt(0);
            String name=c.getString(1);
            p=new Planet();
            p.setId(id);
            p.setName(name);
            planets.add(p);
        }
        db.closeDB();
        if(planets.size()>0)
        {
            rv.setAdapter(adapter);
        }
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(item.getTitle()=="New")
        {
            displayDialog();
        }else if(item.getTitle()=="Delete")
        {
            adapter.deletePlanet();
        }
        return super.onContextItemSelected(item);
    }
}

 

 

 

SQLite RecyclerView ContextMenu

SQLite RecyclerView ContextMenu

 

If you prefer more explanations or want to watch the demo then the complete video is below :

Android SQLite Database 06 : INSERT SELECT DELETE - ContextMenu Delete [RecylcerView]

 



    Leave a Reply

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

    seven + 4 =

    COMMENTS