Saturday, 11 August 2012

Android AutoCompleteTextView data binding based on another AutoCompleteTextView selection

Android - Bind data to an AutoCompleteTextView based on another AutoCompleteTextView selection

Hi friends, here I am going to explain how to load an AutoCompleteTextView based on the selection of another AutoCompleteTextView in Android.

Create screen layout xml file

Add following in layout xml file as station_input.xml

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

        <AutoCompleteTextView
            android:id="@+id/fromStation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:imeOptions="actionNext"
            android:inputType="text"
            android:singleLine="true"
            android:text="@string/From" >
            <requestFocus />
        </AutoCompleteTextView>

         <AutoCompleteTextView
             android:id="@+id/toStation"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:ems="10"
             android:imeOptions="actionDone"
            android:inputType="text"
            android:singleLine="true"
             android:text="@string/To" >
            <requestFocus />
        </AutoCompleteTextView>
    </LinearLayout>

Add list_station.xml to the project layout folder

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="14sp"
    android:textColor="#000">
</TextView>

Bind data to first AutoCompleteTextView

 // Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id. station_input);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View layout = layoutInflater.inflate(R.layout. station_input, viewGroup);

    
    // bind all stations to station auto complete
  AutoCompleteTextView fromStation = (AutoCompleteTextView) layout.findViewById(R.id.fromStation) ;
                   // Helper class for getting Stations list from Databse. 
  DatabaseHelper helper = new  DatabaseHelper();
  List<String> stationsList =helper.GetStations(context); 
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.list_station, stationsList);
  fromStation.setAdapter(adapter);
  fromStation.setText("");

  
  
  
  toStation = (AutoCompleteTextView) layout.findViewById(R.id.toStation) ;
  toStation.setText("");

setOnItemClickListener for first AutoCompleteTextView

//  add item click listener for fromStation AutocompleteTextView 
  fromStation.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3){
                                // get the clicked item in fromStation
String fromStationSelected = arg0.getItemAtPosition(arg2).toString().split("-")[1];

                                 // Helper class for getting Stations list from Databse.
DatabaseHelper  helper = new  DatabaseHelper();
  List<String> stationsList = helper.GetToStation(context,  fromStationSelected ); 
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.list_station, stationsList);
  toStation.setAdapter(adapter);
  toStation.setText("");
 
}
});
    
  toStation.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3){
  
  // to do what ever you want in item click of second AutoCompleteTextView (toStation)
          
}
});



If any better way, please feel free to comment.

Enjoy Coding. 

Friday, 3 August 2012

Build an Android app using existing SQLite database

Step by step guide to use existing sqlite database file in Android application.



Step 1.
Prepare the SqLite database file

Step 2.
Create a table android_metadata in the database,
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
Insert a record as follows
INSERT INTO "android_metadata" VALUES ('en_US')
Step 3.
Rename primary Id fields of existing tables as _Id. So that Android will know where to bind the id field of your tables.

Now the database is ready.

Step 4.
Simply copy and paste the database.db file to 'assets' folder of the android project.

Step 5.
Create a class MyDatabaseAdapter to access the our own database through project.
It will extend from SQLiteOpenHelper class, which is in android.database.sqlite namespace.
MyDatabaseAdapter class look like this.

public class MyDatabaseAdapter extends SQLiteOpenHelper {

    private Context mycontext;

    private String DB_PATH = "data/data/texkpot.package.app/databases/";
//dont forget to change your namespace.package.app
    private static String DB_NAME = "database.db";
    // the extension may be .sqlite or db
    public SQLiteDatabase myDataBase;

    public DatabaseAdapter(Context context) {
        super(context, DB_NAME, null, 1);
        this.mycontext = context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            System.out.println("Database doesn't exist");
            try {
                createdatabase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkdatabase() {
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch (SQLiteException e) {
            System.out.println("Database doesn't exist");
        }

        return checkdb;
    }

    private void copydatabase() throws IOException {

        // Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        @SuppressWarnings("unused")
        String outfilename = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(
                "data/data/test.test.test/databases/test");

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer)) > 0) {
            myoutput.write(buffer, 0, length);
        }

        // Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();

    }

    public void open() {
        // Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

    public synchronized void close() {
        myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}

thats it.

Step 6. 
Now we can create the instance of the MyDatabaseAdapter class to create and open the database.
The code will look like this


        DataBaseHelper myDbHelper = new DataBaseHelper();
        myDbHelper = new DataBaseHelper(this);
        try {
         myDbHelper.createDataBase();
  } catch (IOException ioe) {
  throw new Error("Unable to create database");
  }

  try {
  myDbHelper.openDataBase();
  }catch(SQLException ex){
  throw ex;
  }