Friday, June 3, 2011

Simple Custom Listview in Android

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:id="@+id/simpleListView"></ListView>
</LinearLayout>



ConnectDatabase.java


package com.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ConnectDatabase extends Activity {
    private SimpleDBAdapter mDbHelper;
    private ListView list;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list = (ListView) findViewById(R.id.simpleListView);
        mDbHelper = new SimpleDBAdapter(ConnectDatabase.this);
        mDbHelper.createDatabase();
        mDbHelper.open();
        String[] values = mDbHelper.getEditTextValue();
        for (int i = 0; i < values.length; i++) {
            // By using setAdpater method in listview we an add string array in
            // list.
            list.setAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, values));
        }
        mDbHelper.close();

        list.setTextFilterEnabled(true);

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(),
                        ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
            }
        });

        // to remove the last comma

    }
}


SimpleDBAdapter.java


package com.android;

import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class SimpleDBAdapter {
    protected static final String TAG = SimpleDBAdapter.class.getName();

    private final Context mCtx;
    private SQLiteDatabase mDb;
    private DataBaseHelper mDbHelper;

    private static String SAMPLE_TABLE = "Simple";

    public static String SAMPLE_FIRST = "FirstName";
    public static String SAMPLE_LAST = "LastName";
   
    public SimpleDBAdapter(Context ctx) {
        this.mCtx = ctx;
        mDbHelper = new DataBaseHelper(mCtx);
    }

    public SimpleDBAdapter createDatabase() throws SQLException {
        try
        {
            mDbHelper.createDataBase();
            Log.v(TAG, "database created");
        } catch (IOException ioe) {
            Log.v(TAG, ioe.toString() + "  Unable to create database.");
            throw new Error("Unable to create database");
        }
        return this;
    }

    public SimpleDBAdapter open() throws SQLException {
        // Create and open Database
        try {
            mDbHelper.openDataBase();
            mDbHelper.close();
            mDb = mDbHelper.getReadableDatabase();
        } catch (SQLException sqle) {
            Log.v(TAG, sqle.toString());
            throw sqle;
        }
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public Cursor fetchAllNotes() {

        return mDb.query(SAMPLE_TABLE, new String[] { SAMPLE_FIRST,
                SAMPLE_LAST },
                null, null, null, null, null);
    }

    public String[] getEditTextValue() {
        // Cursor c = mDb.query(NOTES_TABLE, new String[]{NOTES_NOTETEXT},
        // "ZQUESTIONID=" + queId, null, null, null,null);
        Cursor cursor = mDb.query(true, SAMPLE_TABLE, new String[]{SAMPLE_FIRST,SAMPLE_LAST}, null, null, null, null,
                SAMPLE_FIRST, null);
        //mDb.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
        String[] values = new String[cursor.getCount()];
        int i = 0;
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            values[i] = cursor.getString(cursor.getColumnIndex(SAMPLE_FIRST));
            Log.v("First Name:", "" + values[i]);
            i++;
        }
        Log.v("log_tag","Count: " + cursor.getCount());
        cursor.close();
        return values;
    }
}



DataBaseHelper.java


package com.android;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.PublicKey;

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

public class DataBaseHelper extends SQLiteOpenHelper
{
    private static String TAG = DataBaseHelper.class.getName();
    private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
    private static String DB_NAME = "sample.sqlite";
    private SQLiteDatabase myDataBase = null;
    private final Context myContext;

    public DataBaseHelper(Context context)
    {
        super(context, DB_NAME, null, 1);
        DB_PATH = "/data/data/" + context.getPackageName() +"/databases/";
        this.myContext = context;
        Log.v("log_tag", "DBPath: " + DB_PATH);
    }   

    public void createDataBase() throws IOException{
        boolean dbExist = checkDataBase();
        if(dbExist){
            Log.v("log_tag", "database does exist");
        }else{
            Log.v("log_tag", "database does not exist");
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private void copyDataBase() throws IOException{
        InputStream myInput = myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_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();
    }

    private boolean checkDataBase(){
        SQLiteDatabase checkDB = null;
        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        }catch(SQLiteException e){
            Log.v(TAG, e.toString() + "   database doesn't exists yet..");
        }
        if(checkDB != null){
            checkDB.close();
        }
        return checkDB != null;
    }

    public boolean openDataBase() throws SQLException
    {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return myDataBase != null;
    }

    @Override
    public synchronized void close()
    {
            if(myDataBase != null)
                myDataBase.close();
            super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {}

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.v(TAG, "Upgrading database, this will drop database and recreate.");
    }
}

No comments:

Post a Comment