Home Android Swipe Tabbed SQLite – Fragments With GridView

Android Swipe Tabbed SQLite – Fragments With GridView

Android Swipe Tabbed SQLite – Fragments With GridView




  • Here we see how to categorize SQLite data in swipeable tabs.
  • Each fragment shall have a unique dataset bound on a GridView.
  • The tabs and fragments are clickable and swipeable respectively.
  • We shall display a dialog to insert data.
  • The data shall be categorized according to categories.
  • The categories as well as data shall be fetched from the database.
  • The component of choice is GridView.
Android Project Structure

Android Project Structure

Below are some of our important classes.Take note its important you view the full source code to know how to use the following classes :

Constants

  • Hold database tabel column constants.
  • Define table creation as well deletion statement.

 

package com.tutorials.hp.tabbedsqlite.mDB;

/**
 * Created by Oclemy on 9/27/2016 for ProgrammingWizards Channel and http://www.camposha.info.
 */
public class Constants {
    /*
  COLUMNS
   */
    static final String ROW_ID="id";
    static final String NAME="name";
    static final String CATEGORY="category";

    /*
    DB PROPERTIES
     */
    static final String DB_NAME="spg_DB";
    static final String TB_NAME="spg_TB";
    static final int DB_VERSION=1;

    /*
    TABLE CREATION STATEMENT
     */
    static final String CREATE_TB="CREATE TABLE spg_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL,category TEXT NOT NULL);";


    /*
    TABLE DELETION STMT
     */
    static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;

}

 

 DBAdapter class

  • Perform CRUD operations.
  • OPen connection,Insert data,Retrieve data according to selected category,close connection.

 

package com.tutorials.hp.tabbedsqlite.mDB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Space;

import com.tutorials.hp.tabbedsqlite.mModel.Spacecraft;

import java.util.ArrayList;

/**
 * Created by Oclemy on 9/27/2016 for ProgrammingWizards Channel and http://www.camposha.info.
 */
public class DBAdapter {

    Context c;
    SQLiteDatabase db;
    DBHelper helper;

    /*
    1. INITIALIZE DB HELPER AND PASS IT A CONTEXT

     */
    public DBAdapter(Context c) {
        this.c = c;
        helper = new DBHelper(c);
    }


    /*
    SAVE DATA TO DB
     */
    public boolean saveSpacecraft(Spacecraft spacecraft) {
        try {
            db = helper.getWritableDatabase();

            ContentValues cv = new ContentValues();
            cv.put(Constants.NAME, spacecraft.getName());
            cv.put(Constants.CATEGORY, spacecraft.getCategory());

            long result = db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);
            if (result > 0) {
                return true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            helper.close();
        }

        return false;
    }

    /*
     1. RETRIEVE SPACECRAFTS FROM DB AND POPULATE ARRAYLIST
     2. RETURN THE LIST
     */
    public ArrayList<Spacecraft> retrieveSpacecrafts(String category) {
        ArrayList<Spacecraft> spacecrafts=new ArrayList<>();

        try {
            db = helper.getWritableDatabase();


           Cursor c=db.rawQuery("SELECT * FROM "+Constants.TB_NAME+" WHERE "+Constants.CATEGORY+" = '"+category+"'",null);

            Spacecraft s;
            spacecrafts.clear();

            while (c.moveToNext())
            {
                String s_name=c.getString(1);
                String s_category=c.getString(2);

                s=new Spacecraft();
                s.setName(s_name);
                s.setCategory(s_category);

                spacecrafts.add(s);
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            helper.close();
        }

        return spacecrafts;
    }


}

 

INSERT DATA SQLITE

INSERT DATA SQLITE

 

 

 

MainActivity

 

package com.tutorials.hp.tabbedsqlite;

import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.tutorials.hp.tabbedsqlite.mAdapter.MyPagerAdapter;
import com.tutorials.hp.tabbedsqlite.mDB.DBAdapter;
import com.tutorials.hp.tabbedsqlite.mFragments.InterGalactic;
import com.tutorials.hp.tabbedsqlite.mFragments.InterPlanetary;
import com.tutorials.hp.tabbedsqlite.mFragments.InterStellar;
import com.tutorials.hp.tabbedsqlite.mModel.Spacecraft;

public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {

    private TabLayout tab;
    private ViewPager vp;
    int currentPos=0;

    EditText nameEditText;
    Button saveBtn;
    Spinner sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //VIEWS
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);


        //VIEWPAGER AND TABS
        vp = (ViewPager) findViewById(R.id.viewpager);
        addPages();

        //SETUP TAB
        tab = (TabLayout) findViewById(R.id.tabs);
        tab.setTabGravity(TabLayout.GRAVITY_FILL);
        tab.setupWithViewPager(vp);
        tab.addOnTabSelectedListener(this);
    }



    /*
    DISPLAY INPUT DIALOG
    SAVE
     */
    private void displayDialog()
    {
        Dialog d=new Dialog(this);
        d.setTitle("SQLITE DATA");
        d.setContentView(R.layout.dialog_layout);

        //INITIALIZE VIEWS
        nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
        saveBtn= (Button) d.findViewById(R.id.saveBtn);
        sp = (Spinner) d.findViewById(R.id.category_SP);

        //SPINNER ADAPTER
        String[] categories = {InterPlanetary.newInstance().toString(),
                InterStellar.newInstance().toString(),
                InterGalactic.newInstance().toString()};
        sp.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, categories));

       //SAVE
        saveBtn.setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View v) {

                                           Spacecraft s = new Spacecraft();
                                           s.setName(nameEditText.getText().toString());
                                           s.setCategory(sp.getSelectedItem().toString());

                                           if (new DBAdapter(MainActivity.this).saveSpacecraft(s)) {
                                               nameEditText.setText("");
                                               sp.setSelection(0);
                                           } else {
                                               Toast.makeText(MainActivity.this, "Not Saved", Toast.LENGTH_SHORT).show();
                                           }
                                       }
                                   });

          //SHOW DIALOG
            d.show();


    }


    //FILL TAB PAGES
    private void addPages()
    {
        MyPagerAdapter myPagerAdapter=new MyPagerAdapter(getSupportFragmentManager());
        myPagerAdapter.addPage(InterPlanetary.newInstance());
        myPagerAdapter.addPage(InterStellar.newInstance());
        myPagerAdapter.addPage(InterGalactic.newInstance());

        vp.setAdapter(myPagerAdapter);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        vp.setCurrentItem(currentPos=tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.addMenu) {
            displayDialog();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

Android SQLite GridView Tabs

Android SQLite GridView Tabs

 

 

    Leave a Reply

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

    Leave a Comment