Wednesday 15 May 2013

Data Base how to use

1)Database Helper class

package com.surgeryflashcard.DB;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class databasehelper extends SQLiteOpenHelper {
    private static String DATABASE_NAME = "dbSurgeryFlashCard.sqlite";
    private SQLiteDatabase myDataBase;
    private Context myContext;
    @SuppressWarnings("unused")
    private String TAG = this.getClass().getSimpleName();
    private String path = "/data/data/com.surgeryflashcard/databases/";

    public databasehelper(Context context) {

        super(context, DATABASE_NAME, null, 2);
        this.myContext = context;
    }

    // ---Create the database---
    public void createDataBase() throws IOException {

        // ---Check whether database is already created or not---
        boolean dbExist = checkDataBase();

        if (!dbExist) {
            this.getReadableDatabase();
            try {
                // ---If not created then copy the database---
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
            this.close();
        }

    }

    // --- Check whether database already created or not---
    private boolean checkDataBase() {
        try {
            String myPath = path + DATABASE_NAME;
            File f = new File(myPath);
            if (f.exists())
                return true;
            else
                return false;
        } catch (SQLiteException e) {
            e.printStackTrace();
            return false;
        }

    }

    // --- Copy the database to the output stream---
    private void copyDataBase() throws IOException {

        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

        String outFileName = path + DATABASE_NAME;

        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException {

        // --- Open the database---
        String myPath = path + DATABASE_NAME;

        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
        myDataBase.setLockingEnabled(false);
    }

    @Override
    public synchronized void close() {

        if (myDataBase != null)
            myDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        //arg0.execSQL("CREATE TABLE Msg (id text,title text,body text,date1 text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void update_delete_insertquery(String s) {
        //myDataBase.execSQL(s);
    }

    public Cursor selectquery(String s) {
        return myDataBase.rawQuery(s, null);
    }


   
    public ArrayList<CatagoryDB> getCatagoey() {
        ArrayList<CatagoryDB> loc_infos = new ArrayList<CatagoryDB>();
        openDataBase();
        Cursor c = myDataBase
        .rawQuery(
                "SELECT DISTINCT(categoryName),categoryID FROM tblCategory  ORDER BY lower(categoryName) ASC", null);
        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    CatagoryDB loc = new CatagoryDB();
                    loc.categoryName = c.getString(0).trim();
                    loc.categoryID = c.getString(1).trim();
                   
                    loc_infos.add(loc);
                } while (c.moveToNext());
            }
        }
        c.close();
        myDataBase.close();
        SQLiteDatabase.releaseMemory();
        return loc_infos;
    }
   

    public ArrayList<SubCatagoryDB> getSubCatagoey(String where) {
        ArrayList<SubCatagoryDB> loc_infos = new ArrayList<SubCatagoryDB>();
        openDataBase();
        Cursor c = myDataBase
        .rawQuery(
                "SELECT DISTINCT subCategoryID,categoryID,(subCategoryName) FROM tblSubCategory WHERE categoryID =  "+where, null);
        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    SubCatagoryDB loc = new SubCatagoryDB();
                    loc.subCategoryID = c.getString(0).trim();
                    loc.categoryID = c.getString(1).trim();
                    loc.subCategoryName = c.getString(2).trim();
                   
                    loc_infos.add(loc);
                } while (c.moveToNext());
            }
        }
        c.close();
        myDataBase.close();
        SQLiteDatabase.releaseMemory();
        return loc_infos;
    }

   
    public ArrayList<CardDB> getCard(String where) {
        ArrayList<CardDB> loc_infos = new ArrayList<CardDB>();
        openDataBase();
        Cursor c = myDataBase
        .rawQuery(
                "SELECT * FROM tblCards WHERE subCategoryID =  "+where, null);
        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    CardDB loc = new CardDB();
                    loc.cardID = c.getString(2).trim();
                    loc.cardDetail = c.getString(3).trim();
                   
                   
                    loc_infos.add(loc);
                } while (c.moveToNext());
            }
        }
        c.close();
        myDataBase.close();
        SQLiteDatabase.releaseMemory();
        return loc_infos;
    }
}
2)Db addepter
package com.surgeryflashcard.DB;


import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter {

    private  final String DATABASE_NAME = "dbSurgeryFlashCard.sqlite";

    private  final int DATABASE_VERSION = 1;
    private  Context context;
    private DatabaseHelper DBHelper;
    //private static SQLiteDatabase db;
    public DBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
    public  class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            // db.execSQL(DATABASE_CREATE);
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //onCreate(db);
        }
    }
    // ---opens the database---
    @SuppressWarnings("unused")
    public DBAdapter open() throws SQLException {
        SQLiteDatabase db = DBHelper.getWritableDatabase();
        return this;
    }
    // ---closes the database---
    public void close() {
        DBHelper.close();
    }
}
3)MainActivity

package com.surgeryflashcard;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.surgeryflashcard.DB.CatagoryDB;
import com.surgeryflashcard.DB.databasehelper;

public class ListActivity extends Activity
{
   
    databasehelper db;
    ArrayList<CatagoryDB> arr_cat;
   
    ListView list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        db = new databasehelper(this);
        try {
            db.createDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        list = (ListView) findViewById(R.id.list);
        new GetData().execute();
       
       
    }
    //________________Methods______________________________
   
    private class GetData extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog pd;
        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(ListActivity.this);
            pd.setMessage("Loading...");
            pd.show();
            super.onPreExecute();
        }
        @Override
        protected Void doInBackground(Void... params) {
            arr_cat = db.getCatagoey();
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            //if(pd.isShowing())
            pd.dismiss();
            list.setAdapter(new ItemsAdapter());
            list.invalidate();
            super.onPostExecute(result);
        }

    }
   
   
    public class ItemsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arr_cat.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View resultListView, ViewGroup parent) {

            ViewHolder holder = null;
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (resultListView == null) {
                resultListView = inflater.inflate(R.layout.lyt_home_left, null);
                holder = new ViewHolder();
               
               
                holder.txt_name = (TextView) resultListView.findViewById(R.id.lyt_txt_leftlist);
               
                resultListView.setTag(holder);
               
            } else {
                holder = (ViewHolder) resultListView.getTag();
            }
            final CatagoryDB babyname = arr_cat.get(position);

           
            holder.txt_name.setText("" + babyname.categoryName);
           
            resultListView.setOnClickListener(new OnClickListener() {
               
                @Override
                public void onClick(View arg0) {
                   
                   
                }
            });

   
            return resultListView;
        }
        class ViewHolder {
            TextView txt_name;
           
        }
    }

}

No comments:

Post a Comment