The best way to create a database application in android is , using an exteranal database . ie, we can create database using tools like Navicat , SQLite Browser and copy this database into our application .This method is more flexible and easy than creating a database in our application .
This is a simple application using external database file.Application will insert data into database and show data from the database in a customized list view.
Screenshots of this application are
MainActivity
This is the first activity of this application . When Register Here button is pressed it will start Registration Activity
Editing of the entries can be done with a Long Click on the listView items.
you can download the source code of this project from google drive https://drive.google.com/folderview?id=0BySLpWhqmbbdY3JHMkZRZFN0bEE&usp=sharing
click on the above link ->sign into your google account ->add this to your google drive -> open it in google drive and download it.
if you crate a database file using SQlite browser it will look like this
you can download the sample database file from here
https://drive.google.com/file/d/0BySLpWhqmbbdeG55d0dtbmNabnc/view?usp=sharing
Atfer creating a database file paste it into the assets folder of your project directory.
The main class of this project is DatabaseHeiper.java this class will copy the database file in the Assets folder into the appliction.
The functions public static Cursor rawQuery(String query) is used for select database operation,
The mainAcitivy is the first activity of this sample aplication Which shows a list of registered employees.
This is a simple application using external database file.Application will insert data into database and show data from the database in a customized list view.
Screenshots of this application are
MainActivity
Editing of the entries can be done with a Long Click on the listView items.
you can download the source code of this project from google drive https://drive.google.com/folderview?id=0BySLpWhqmbbdY3JHMkZRZFN0bEE&usp=sharing
click on the above link ->sign into your google account ->add this to your google drive -> open it in google drive and download it.
if you crate a database file using SQlite browser it will look like this
you can download the sample database file from here
https://drive.google.com/file/d/0BySLpWhqmbbdeG55d0dtbmNabnc/view?usp=sharing
Atfer creating a database file paste it into the assets folder of your project directory.
The main class of this project is DatabaseHeiper.java this class will copy the database file in the Assets folder into the appliction.
package com.arun.externaldatabsedemo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class DataBaseHelper extends SQLiteOpenHelper { private static SQLiteDatabase sqliteDb; private static DataBaseHelper instance; private static final int DATABASE_VERSION = 1; private Context context; static Cursor cursor = null; DataBaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); this.context = context; } private static void initialize(Context context, String databaseName) { if (instance == null) { if (!checkDatabase(context, databaseName)) { try { copyDataBase(context, databaseName); } catch (IOException e) { System.out.println( databaseName + " does not exists "); } } instance = new DataBaseHelper(context, databaseName, null, DATABASE_VERSION); sqliteDb = instance.getWritableDatabase(); System.out.println("instance of " + databaseName + " created "); } } public static final DataBaseHelper getInstance(Context context, String databaseName) { initialize(context, databaseName); return instance; } public SQLiteDatabase getDatabase() { return sqliteDb; } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } private static void copyDataBase(Context aContext, String databaseName) throws IOException { InputStream myInput = aContext.getAssets().open(databaseName); String outFileName = getDatabasePath(aContext, databaseName); File f = new File("/data/data/" + aContext.getPackageName() + "/databases/"); if (!f.exists()) f.mkdir(); 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(); System.out.println(databaseName + " copied"); } public static boolean checkDatabase(Context aContext, String databaseName) { SQLiteDatabase checkDB = null; try { String myPath = getDatabasePath(aContext, databaseName); checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); checkDB.close(); } catch (SQLiteException e) { System.out.println(databaseName + " does not exists"); } return checkDB != null ? true : false; } private static String getDatabasePath(Context aContext, String databaseName) { return "/data/data/" + aContext.getPackageName() + "/databases/" + databaseName; } public static Cursor rawQuery(String query) { try { if (sqliteDb.isOpen()) { sqliteDb.close(); } sqliteDb = instance.getWritableDatabase(); cursor = null; cursor = sqliteDb.rawQuery(query, null); } catch (Exception e) { System.out.println("DB ERROR " + e.getMessage()); e.printStackTrace(); } return cursor; } public static void execute(String query) { try { if (sqliteDb.isOpen()) { sqliteDb.close(); } sqliteDb = instance.getWritableDatabase(); sqliteDb.execSQL(query); } catch (Exception e) { System.out.println("DB ERROR " + e.getMessage()); e.printStackTrace(); } } }
The functions public static Cursor rawQuery(String query) is used for select database operation,
public static Cursor rawQuery(String query) { try { if (sqliteDb.isOpen()) { sqliteDb.close(); } sqliteDb = instance.getWritableDatabase(); cursor = null; cursor = sqliteDb.rawQuery(query, null); } catch (Exception e) { System.out.println("DB ERROR " + e.getMessage()); e.printStackTrace(); } return cursor; }public static void execute(String query) is used for insert. update, delete operations.
public static void execute(String query) { try { if (sqliteDb.isOpen()) { sqliteDb.close(); } sqliteDb = instance.getWritableDatabase(); sqliteDb.execSQL(query); } catch (Exception e) { System.out.println("DB ERROR " + e.getMessage()); e.printStackTrace(); } }MainActivity.java
The mainAcitivy is the first activity of this sample aplication Which shows a list of registered employees.
package com.arun.externaldatabsedemo; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.ListView; public class MainActivity extends Activity { private DataBaseHelper dataBaseHelper; private ListView lvEmployee; private Button btRegister; private static final String DB_NAME = "EMPLOYEE_DB"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dataBaseHelper = DataBaseHelper.getInstance(this, DB_NAME); lvEmployee = (ListView) findViewById(R.id.lv_employee); btRegister = (Button) findViewById(R.id.btn_register); showEmployeeDetails(); lvEmployee.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { EmployeeListItems listItems = (EmployeeListItems) arg0 .getItemAtPosition(position); String employeeId = listItems.getEmpId(); Bundle passData = new Bundle(); passData.putString("empID", employeeId); Intent Editintent = new Intent(MainActivity.this, EmployeEdit.class); Editintent.putExtras(passData); startActivity(Editintent); return false; } }); btRegister.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, EmployeeRegistration.class); startActivity(intent); } }); } private void showEmployeeDetails() { ArrayList<EmployeeListItems> employeeList = new ArrayList<EmployeeListItems>(); employeeList.clear(); String query = "SELECT * FROM employe"; Cursor c1 = DataBaseHelper.rawQuery(query); if (c1 != null && c1.getCount() != 0) { if (c1.moveToFirst()) { do { EmployeeListItems employeeListItems = new EmployeeListItems(); employeeListItems.setEmpId(c1.getString(c1 .getColumnIndex("employee_id"))); employeeListItems.setFirstName(c1.getString(c1 .getColumnIndex("first_name"))); employeeListItems.setLastName(c1.getString(c1 .getColumnIndex("last_name"))); employeeListItems.setPhoneNO(c1.getString(c1 .getColumnIndex("phone_no"))); employeeList.add(employeeListItems); } while (c1.moveToNext()); } } c1.close(); EmployeeListAdapter employeeListAdapter = new EmployeeListAdapter( MainActivity.this, employeeList); lvEmployee.setAdapter(employeeListAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Customized ListView is used here so Customized Adapter class(EmployeeListAdapter.java) and a bean class(EmployeeListItems.java) is used
EmployeeListAdapter.java
EmployeeListItems.java
EmployeeListAdapter.java
package com.arun.externaldatabsedemo; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class EmployeeListAdapter extends BaseAdapter { Context context; ArrayList<EmployeeListItems> employeeList; public EmployeeListAdapter(Context context, ArrayList<EmployeeListItems> employeeList) { this.context = context; this.employeeList = employeeList; } @Override public int getCount() { return employeeList.size(); } @Override public Object getItem(int position) { return employeeList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { EmployeeListItems employeeListItems = employeeList.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.employee_list_row, null); } TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno); tvSlNo.setText(employeeListItems.getEmpId()); TextView tvFirstName = (TextView) convertView .findViewById(R.id.tv_first_name); tvFirstName.setText(employeeListItems.getFirstName()); TextView tvLastName = (TextView) convertView .findViewById(R.id.tv_last_name); tvLastName.setText(employeeListItems.getLastName()); TextView tvPhone = (TextView) convertView.findViewById(R.id.tv_phone); tvPhone.setText(employeeListItems.getPhoneNO()); return convertView; } }
EmployeeListItems.java
package com.arun.externaldatabsedemo; public class EmployeeListItems { private String EmpId; private String FirstName; private String LastName; private String PhoneNO; public String getEmpId() { return EmpId; } public void setEmpId(String empId) { EmpId = empId; } public String getFirstName() { return FirstName; } public void setFirstName(String firstName) { FirstName = firstName; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public String getPhoneNO() { return PhoneNO; } public void setPhoneNO(String phoneNO) { PhoneNO = phoneNO; } }
EmployeeRegistration.java
This class is used for new employee registration . The activity is loaded when Register Here button is clicked
package com.arun.externaldatabsedemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class EmployeeRegistration extends Activity { private Button btSubmit; private Button btCancel; private EditText etEmpId; private EditText etfirstName; private EditText etlastaName; private EditText etPhone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_registration); btSubmit = (Button) findViewById(R.id.bt_submit); btCancel = (Button) findViewById(R.id.bt_reg_cancel); etEmpId = (EditText) findViewById(R.id.et_id); etfirstName = (EditText) findViewById(R.id.et_first_name); etlastaName = (EditText) findViewById(R.id.et_last_name); etPhone = (EditText) findViewById(R.id.et_phone); btSubmit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String insertQuery = "INSERT INTO employe VALUES('" + etEmpId.getText().toString() + "'," + "'" + etfirstName.getText().toString() + "','" + etlastaName.getText().toString() + "','" + etPhone.getText().toString() + "')"; DataBaseHelper.execute(insertQuery); Intent intent = new Intent(EmployeeRegistration.this, MainActivity.class); startActivity(intent); } }); btCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }EmployeEdit.java
This Class is used to edit employee details . By Long clicking ListView items we can edit it.
package com.arun.externaldatabsedemo; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class EmployeEdit extends Activity { private Button btCancel; private Button btDone; private EditText etfirstName; private EditText etlastaName; private EditText etPhone; private String employeeId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_employee); btDone = (Button) findViewById(R.id.bt_done); btCancel = (Button) findViewById(R.id.bt_cancel); etfirstName = (EditText) findViewById(R.id.et_edit_first_name); etlastaName = (EditText) findViewById(R.id.et_edit_last_name); etPhone = (EditText) findViewById(R.id.et_edit_phone); Bundle getData = getIntent().getExtras(); employeeId = getData.getString("empID"); setEditTextFields(); btDone.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String UpdateQuery = " UPDATE employe set first_name='" + etfirstName.getText().toString() + "' ," + "last_name='" + etlastaName.getText().toString() + "' , phone_no='" + etPhone.getText().toString() + "' where employee_id='" + employeeId + "' "; DataBaseHelper.execute(UpdateQuery); Intent intent = new Intent(EmployeEdit.this, MainActivity.class); startActivity(intent); } }); btCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void setEditTextFields() { String query = "SELECT * FROM employe where employee_id='" + employeeId + "' "; Cursor c1 = DataBaseHelper.rawQuery(query); if (c1 != null && c1.getCount() != 0) { if (c1.moveToFirst()) { do { etfirstName.setText(c1.getString(c1 .getColumnIndex("first_name"))); etlastaName.setText(c1.getString(c1 .getColumnIndex("last_name"))); etPhone.setText(c1.getString(c1.getColumnIndex("phone_no"))); } while (c1.moveToNext()); } } c1.close(); } }
Layout files are the following
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" > <TextView android:layout_width="50dp" android:layout_height="wrap_content" android:text="slno" android:textColor="#000" /> <TextView android:layout_width="80dp" android:layout_height="wrap_content" android:text="FirstName" android:textColor="#000" /> <TextView android:layout_width="80dp" android:layout_height="wrap_content" android:text="Lastname" android:textColor="#000" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="phoneNo" android:textColor="#000" /> </LinearLayout> <ListView android:id="@+id/lv_employee" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:layout_marginLeft="10dp" > </ListView> <Button android:id="@+id/btn_register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@string/register" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/emp_id" /> <EditText android:id="@+id/et_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" > <requestFocus /> </EditText> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="First Name" /> <EditText android:id="@+id/et_first_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Last Name" /> <EditText android:id="@+id/et_last_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phone" /> <EditText android:id="@+id/et_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> </TableLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" > <Button android:id="@+id/bt_submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="70dp" android:text="@string/submit" /> <Button android:id="@+id/bt_reg_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginRight="31dp" android:layout_toLeftOf="@+id/bt_submit" android:text="cancel" /> </RelativeLayout> </LinearLayout>
edit_employee.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="First Name" /> <EditText android:id="@+id/et_edit_first_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Last Name" /> <EditText android:id="@+id/et_edit_last_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phone" /> <EditText android:id="@+id/et_edit_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> </TableRow> </TableLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" > <Button android:id="@+id/bt_done" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="24dp" android:text="@string/done" /> <Button android:id="@+id/bt_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginRight="33dp" android:layout_toLeftOf="@+id/bt_done" android:text="@string/cancel" /> </RelativeLayout> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:orientation="horizontal" > <TextView android:id="@+id/tv_slno" android:layout_width="50dp" android:layout_height="wrap_content" android:text="slno" android:textColor="#000" /> <TextView android:id="@+id/tv_first_name" android:layout_width="80dp" android:layout_height="wrap_content" android:text="TextView" android:textColor="#000" /> <TextView android:id="@+id/tv_last_name" android:layout_width="80dp" android:layout_height="wrap_content" android:text="TextView" android:textColor="#000" /> <TextView android:id="@+id/tv_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="TextView" android:textColor="#000" /> </LinearLayout>
https://drive.google.com/folderview?id=0BySLpWhqmbbdY3JHMkZRZFN0bEE&usp=sharing
ReplyDeleteDOWNLOADED THIS FILES BUT HOW TO OPEN THIS PROJECT IN ANDROID STUDIO 2.0
The sample code is done in eclipse so it will show issues in android studio. Use this below link
Deletehttp://developer.android.com/sdk/installing/migrate.html