Skip to content Skip to sidebar Skip to footer

How To Create Android Database Application?

I am new to Databases and do not know if this would be the best way to do what I want to achieve. I want to create a custom list of restaurants around me, then search them, and sor

Solution 1:

Yes, you definitely want to use a database. If you use a database local to the phone, you need to use an SQLite database. Here is a good place to start.

If you want a database that is preloaded in the phone, put it in your assets folder. Here is an example of a database helper class with the database packaged with the phone:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;


import android.content.ContentValues;
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;
import android.util.Log;

publicclassDataBaseHelperextendsSQLiteOpenHelper{

privatestaticfinalStringTAG="DataBaseHelper";

//The Androids default system path of your application database.privatestaticStringDB_PATH="/data/data/yourpackage/databases/";

privatestaticStringDB_NAME="DatabaseName";

public SQLiteDatabase myDataBase; 

privatefinal Context myContext;


    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */publicDataBaseHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }   

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */publicvoidcreateDataBase()throws IOException{

        booleandbExist= checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path//of your application so we are gonna be able to overwrite that database with our database.this.getWritableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                thrownewError("Error copying database");

            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesnt
     */privatebooleancheckDataBase(){

        SQLiteDatabasecheckDB=null;

        try{
            StringmyPath= DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

        }catch(SQLiteException e){

            //database doest exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */privatevoidcopyDataBase()throws IOException{



        //Open your local db as the input streamInputStreammyInput= myContext.getAssets().open(DB_NAME);

        Log.d(TAG, "found the database");
        // Path to the just created empty dbStringoutFileName= DB_PATH + DB_NAME;


        //Open the empty db as the output streamOutputStreammyOutput=newFileOutputStream(outFileName);


        //transfer bytes from the inputfile to the outputfilebyte[] buffer = newbyte[2048];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    publicvoidopenDataBase()throws SQLException{

        //Open the databaseStringmyPath= DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Overridepublicsynchronizedvoidclose() {

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

            super.close();

    }

    @OverridepublicvoidonCreate(SQLiteDatabase db) {

    }

    @OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

        // Add your public helper methods to access and get content from the database.// You could return cursors by doing "return myDataBase.query(....)" so itd be easy// to you to create adapters for your views.

Solution 2:

What you want to do is create a Web Service, this lives in the "cloud" on the Internets somewhere. Then you have your mobile app periodically contact the web service and request restaurant data perhaps based on the users current location, so the app passes the gps coordinates to the web service and the Web Service checks its database for restaurants within X distance of that location, then the Web Service returns the list to the app in a format such as Json or XML, the App parses this info and displays it to the user.

Ideally you would also have a database on the phone that would store results on the device this reduces the amount of requests you have to pull from the server, saving on battery, data and server resources. This gets a little complicated as you have to decide what to ask for intelligently and the server has to decide what to send you.

There was a Google I/O talk on how to do this. http://www.youtube.com/watch?v=xHXn3Kg2IQE

Post a Comment for "How To Create Android Database Application?"