Friday, June 3, 2011

custom listview in android

hello buddy,

you can download data base from here:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
   
   

   
 <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/btnext"
        android:text="Next" android:layout_alignParentBottom="true"
        />
<ListView android:layout_width="fill_parent"       
          android:layout_height="fill_parent"
          android:id="@+id/simpleListView"
          android:layout_alignParentTop="true"
           android:layout_above="@id/btnext"
           android:layout_toRightOf="@+id/bullet"
            >
</ListView>




</RelativeLayout>

info.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content" android:gravity="left|center"
 android:layout_width="wrap_content" android:paddingBottom="5px"
 android:paddingTop="5px" android:paddingLeft="5px">


 <TextView  android:id="@+id/tv"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView>

  <TextView  android:id="@+id/tv1"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView>

  <TextView android:id="@+id/tv2"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView>

</LinearLayout>

listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content" android:gravity="left|center"
 android:layout_width="wrap_content" android:paddingBottom="5px"
 android:paddingTop="5px" android:paddingLeft="5px">

 <ImageView
    android:id="@+id/imagelist"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon"></ImageView>
   

 <TextView android:text="@+id/TextView02" android:id="@+id/TextView02"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView>
</LinearLayout>


customlistview.java

package com.example.customlistview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
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 customlistview extends Activity {
   
    private SimpleDBAdapter mDbHelper;   
    private ListView list;
 
    public String[] values;

    /** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        list = (ListView) findViewById(R.id.simpleListView);

       
   
        mDbHelper = new SimpleDBAdapter(customlistview.this);
        mDbHelper.createDatabase();
        mDbHelper.open();
   
        list.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values));
            list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);           
           

           
        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();
               
                String str=values[position];       
            Log.v("log_tag", "string clocked: " + str);
                Intent intent=new Intent(customlistview.this,info.class);
            intent.putExtra("Name", str);
            startActivity(intent);                   
            }
        });                       
    }   

}


DataBaseHelper.java

package com.example.customlistview;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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 = "custom.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.");
    }
}

SimpleDBAdapter.java

package com.example.customlistview;

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 CUSTOM_TABLE = "customlist";
    public static String CUSTOM_ID="id";
    public static String CUSTOM_NAME = "name";
    public static String CUSTOM_ADD = "address";
    public static String CUSTOM_AGE="age";
   
    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(CUSTOM_TABLE, new String[] { CUSTOM_ID,
                CUSTOM_NAME,CUSTOM_ADD,CUSTOM_AGE },
                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, CUSTOM_TABLE, new String[]{CUSTOM_ID,CUSTOM_NAME,CUSTOM_ADD,CUSTOM_AGE}, null, null, null, null,
                CUSTOM_NAME, 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(CUSTOM_NAME));
            Log.v("name:", "" + values[i]);
            i++;
        }
       
        Log.v("log_tag","Count: " + cursor.getCount());
        cursor.close();
        return values;
   
    }
   

    //public Directory getreccordfromid(String name,String address,int age)
    public Directory getreccordfromid(String name)
    {
        Log.v("log_tag", "name: in database : " +name);

        Directory dir=new Directory();
        Cursor cur=mDb.query("customlist", new String[]{ CUSTOM_ID,CUSTOM_NAME,CUSTOM_ADD,CUSTOM_AGE }, CUSTOM_NAME + "='" + name + "'", null, null, null, null);
        for(cur.isBeforeFirst(); cur.moveToNext(); cur.isAfterLast())
        {
            String fname=cur.getString(cur.getColumnIndex(CUSTOM_NAME));
            Log.v("log_tag","firstname: database" +fname);
            dir.setname(cur.getString(cur.getColumnIndex(CUSTOM_NAME)));
            dir.setadd(cur.getString(cur.getColumnIndex(CUSTOM_ADD)));
            dir.setage(cur.getInt(cur.getColumnIndex(CUSTOM_AGE)));
       
        }
        cur.close();
        return dir;
    }
}


Directory.java

package com.example.customlistview;

public class Directory {
   
    //private int id,age;
    private int age;
    private String name,address;
   
    public Directory() {
    }

//    public Directory(int id, String name, String address, int age){
    public Directory(String name, String address, int age){   
    //    this.id=id;
        this.name=name;
        this.address=address;
        this.age=age;
       
    }

    public String getname()
    {
        return name;
    }
    public void setname(String name)
    {
        this.name=name;
    }
    public String getadd()
    {
        return address;
    }
    public void setadd(String address)
    {
        this.address=address;
    }
    public int getage()
    {
        return age;
    }
    public void setage(int age)
    {
        this.age=age;
    }

}

Info.java

package com.example.customlistview;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class info extends Activity{       
   
    String intentname;   
    private TextView tv,tv1,tv2;
    Directory singleRecord=new Directory();
   
    SimpleDBAdapter mdb;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);       
        if(getIntent().getExtras()!=null)
        {
            if(getIntent().getExtras().containsKey("Name"))
            {
                intentname=getIntent().getExtras().getString("Name");
            }
        }
        setContentView(R.layout.info);
        tv=(TextView)findViewById(R.id.tv);
        tv1=(TextView)findViewById(R.id.tv1);
        tv2=(TextView)findViewById(R.id.tv2);
        mdb=new SimpleDBAdapter(info.this);
        Log.v("log_tag","data come from list: " +intentname);
        mdb.open();   
   
        singleRecord=mdb.getreccordfromid(intentname);           
       
   
        String gotName = singleRecord.getname();
        String gotAdd=singleRecord.getadd();
        int gotAge=singleRecord.getage();
       
        mdb.close();
        Log.v("log_tag", "Got Name: " + gotName );
        Log.v("log_tag", "got address: " + gotAdd );
        Log.v("log_tag", "got age: " + gotAge );
       
        tv.setText("Name is : " + gotName);
        tv1.setText("Address is : " + gotAdd);
        tv2.setText("Age is : " + Integer.toString(gotAge));
       
       
    }
}

No comments:

Post a Comment