Monday 4 April 2011

how to get data in listview from assets folder data base in android

here are required java files 


package com.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ConnectDatabase extends Activity {
private SimpleDBAdapter mDbHelper;
private ListView list;
private Button btnnext;
private String[] values;
private String[] list1;
private int i=0,j=0;
/** 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);
btnnext=(Button)findViewById(R.id.btnnext);
mDbHelper = new SimpleDBAdapter(ConnectDatabase.this);
mDbHelper.createDatabase();
mDbHelper.open();
values = mDbHelper.getEditTextValue();
mDbHelper.close();
//int j=values.length;
//Log.v("log_tag", "values int"+j);
list1=new String[10];
for(i=0;i<10;i++)
{
list1[i]=values[i];
j++;
Log.v("log_tag","we got item in list " +i +" : " +list1[i]);
}
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list1));

 
Log.v("log_tag", "Value of j"+j);
//list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//list.setTextFilterEnabled(true);
btnnext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String[] list2=new String[10];
for(int i=j;i<j+10;i++)
{
list2[i]=values[i];
Log.v("log_tag", "list2  is "+i+list2[i] ); 
}
 
}
});
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();
/*for(int i=0;i<values.length;i++)
{
String templist=values[i];
list1[i]=templist;
 
}*/
String fname=values[position];
Log.v("log_tag", "The fname is"+ fname);
Intent intent=new Intent(ConnectDatabase.this, Userinfo.class);
intent.putExtra("FirstName",fname );
startActivity(intent);
}
});

// to remove the last comma
}
}

--------------------------------------------------------------------------------------------------------------
package com.android;

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 = "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.");
}
}
--------------------------------------------------------------------------------------------------------------
package com.android;

public class Infosetget {
int PhoneNo;
private String Address ,Age,FirstName,LastName;

public Infosetget(){
}
public Infosetget(int PhoneNo,String Address ,String Age,String FirstName,String LastName)
{
this.PhoneNo=PhoneNo;
this.Address=Address;
this.Age=Age;
this.FirstName=FirstName;
this.LastName=LastName;
}
public void setPhoneNo(int phoneNo) {
PhoneNo = phoneNo;
}

public int getPhoneNo() {
return PhoneNo;
}

public void setAddress(String address) {
Address = address;
}

public String getAddress() {
return Address;
}

public void setAge(String age) {
Age = age;
}

public String getAge() {
return Age;
}

public void setFirstName(String firstName) {
FirstName = firstName;
}

public String getFirstName() {
return FirstName;
}

public void setLastName(String lastName) {
LastName = lastName;
}

public String getLastName() {
return LastName;
}
}
-------------------------------------------------------------------------------------------------------------
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 static String Phone_no="PhoneNO";
public static String Age="Age";
public static String Address="Address";
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;
}
public Infosetget getEditTextValue1(String firstname){
Log.v("log_tag", "Get from userinfo"+firstname);
Infosetget info=new Infosetget();
Cursor cursor=mDb.query(true, SAMPLE_TABLE, new String[]{SAMPLE_FIRST,SAMPLE_LAST,Phone_no,Age,Address}, SAMPLE_FIRST+"='"+firstname+"'", null, null, null, null, null);
for(cursor.isBeforeFirst();cursor.moveToNext();cursor.isAfterLast())
{
info.setFirstName(cursor.getString(cursor.getColumnIndex(SAMPLE_FIRST)));
info.setAddress(cursor.getString(cursor.getColumnIndex(Address)));
info.setLastName(cursor.getString(cursor.getColumnIndex(SAMPLE_LAST)));
info.setAge(cursor.getString(cursor.getColumnIndex(Age)));
info.setPhoneNo(cursor.getInt(cursor.getColumnIndex(Phone_no)));
}
cursor.close();
//Cursor cursor=mDb.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
return info;
}
}

-----------------------------------------------------------------------------------------------------------
package com.android;

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


public class Userinfo extends Activity{
String firstname;
private String name,lastname,adds,age1;
private int phoneNo;
SimpleDBAdapter mDb;
Infosetget info=new Infosetget();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("FirstName")) {
firstname = getIntent().getExtras().getString("FirstName");
Log.v("log_tag", "data select: " + firstname);
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.userinfo);
TextView fname=(TextView)findViewById(R.id.fname);
TextView lname=(TextView)findViewById(R.id.lname);
TextView age=(TextView)findViewById(R.id.age);
TextView add=(TextView)findViewById(R.id.add);
TextView pno=(TextView)findViewById(R.id.pno);
mDb=new SimpleDBAdapter(Userinfo.this);
mDb.open();
info=mDb.getEditTextValue1(firstname);
mDb.close();
name=info.getFirstName();
lastname=info.getLastName();
adds=info.getAddress();
age1=info.getAge();
phoneNo=info.getPhoneNo();
Log.v("log_tag", "firstname"+name);
Log.v("log_tag", "lastname"+lastname);
Log.v("log_tag", "address"+adds);
fname.setText("Name is "+name);
lname.setText("LastName is"+lastname);
add.setText("Address is "+adds);
age.setText("Age is "+age1);
pno.setText("PhoneNo is "+Integer.toString(phoneNo));
}
}

-------------------------------------------------------------------------------------------------------
here i am not providing xml files so please is you want full project just mail me at mistrihimanshu@gmail.com

if any query fill free to ask 

No comments:

Post a Comment