.
Android Fragment SQLite 2
1) Startup
Continue from previous tutorial or download startup files here.
2) Create Database Helper
Package Name: add “.db”
File Name: DatabaseHelper.java
package com.notarazi.myviewpagertablayout1.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "employeedb";
private static final int DATABASE_VERSION = 1;
public static final String EMPLOYEE_TABLE = "employee";
public static final String ID_COLUMN = "id";
public static final String NAME_COLUMN = "name";
public static final String EMPLOYEE_DOB = "dob";
public static final String EMPLOYEE_SALARY = "salary";
public static final String CREATE_EMPLOYEE_TABLE = "CREATE TABLE "
+ EMPLOYEE_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY, "
+ NAME_COLUMN + " TEXT, " + EMPLOYEE_SALARY + " DOUBLE, "
+ EMPLOYEE_DOB + " DATE" + ")";
private static DataBaseHelper instance;
public static synchronized DataBaseHelper getHelper(Context context) {
if (instance == null)
instance = new DataBaseHelper(context);
return instance;
}
private DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_EMPLOYEE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
3) Create Database Data Access Object
Package Name: Add “.db”
File Name: EmployeeDBDAO.java
package com.notarazi.myviewpagertablayout1.db;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class EmployeeDBDAO {
protected SQLiteDatabase database;
private DataBaseHelper dbHelper;
private Context mContext;
public EmployeeDBDAO(Context context) {
this.mContext = context;
dbHelper = DataBaseHelper.getHelper(mContext);
open();
}
public void open() throws SQLException {
if(dbHelper == null)
dbHelper = DataBaseHelper.getHelper(mContext);
database = dbHelper.getWritableDatabase();
}
/*public void close() {
dbHelper.close();
database = null;
}*/
}
|
4) Create Data Model
Package Name: Add “.model”
File Name: Employee.java
package com.notarazi.myviewpagertablayout1.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Employee implements Parcelable {
private int id;
private String name;
private Date dateOfBirth;
private double salary;
public Employee() {
super();
}
private Employee(Parcel in) {
super();
this.id = in.readInt();
this.name = in.readString();
this.dateOfBirth = new Date(in.readLong());
this.salary = in.readDouble();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dateOfBirth="
+ dateOfBirth + ", salary=" + salary + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
return true;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(getId());
parcel.writeString(getName());
parcel.writeLong(getDateOfBirth().getTime());
parcel.writeDouble(getSalary());
}
public static final Parcelable.Creator<Employee> CREATOR = newParcelable.Creator<Employee>() {
public Employee createFromParcel(Parcel in) {
return new Employee(in);
}
public Employee[] newArray(int size) {
return new Employee[size];
}
};
}
|
5) Create Data Access Object File
Package Name: Add “.db”
File Name: EmployeeDAO.java
package com.notarazi.myviewpagertablayout1.db;
import android.content.ContentValues;
import android.content.Context;
import com.notarazi.myviewpagertablayout1.model.Employee;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class EmployeeDAO extends EmployeeDBDAO {
private static final SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd", Locale.ENGLISH);
public EmployeeDAO(Context context) {
super(context);
}
//...
public long save(Employee employee) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.NAME_COLUMN, employee.getName());
values.put(DataBaseHelper.EMPLOYEE_DOB,formatter.format(employee.getDateOfBirth()));
values.put(DataBaseHelper.EMPLOYEE_SALARY, employee.getSalary());
return database.insert(DataBaseHelper.EMPLOYEE_TABLE, null, values);
}
//....
}
|
6) Update Fragment Controller (Fragment 1)
File Name: Fragment1.java
package com.notarazi.myviewpagertablayout1;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.notarazi.myviewpagertablayout1.R;
import com.notarazi.myviewpagertablayout1.db.EmployeeDAO;
import com.notarazi.myviewpagertablayout1.model.Employee;
public class FragmentPage1 extends Fragment implements OnClickListener {
// UI references
private EditText empNameEtxt;
private EditText empSalaryEtxt;
private EditText empDobEtxt;
private Button addButton;
private Button resetButton;
private static final SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd", Locale.ENGLISH);
DatePickerDialog datePickerDialog;
Calendar dateCalendar;
Employee employee = null;
private EmployeeDAO employeeDAO;
private AddEmpTask task;
public static final String ARG_ITEM_ID = "emp_add_fragment";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
employeeDAO = new EmployeeDAO(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page1, container,
false);
findViewsById(rootView);
setListeners();
//For orientation change.
if (savedInstanceState != null) {
dateCalendar = Calendar.getInstance();
if (savedInstanceState.getLong("dateCalendar") != 0)
dateCalendar.setTime(new Date(savedInstanceState
.getLong("dateCalendar")));
}
return rootView;
}
private void setListeners() {
empDobEtxt.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(getActivity(),
new OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
dateCalendar = Calendar.getInstance();
dateCalendar.set(year, monthOfYear, dayOfMonth);
empDobEtxt.setText(formatter.format(dateCalendar
.getTime()));
}
}, newCalendar.get(Calendar.YEAR),
newCalendar.get(Calendar.MONTH),
newCalendar.get(Calendar.DAY_OF_MONTH));
addButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
protected void resetAllFields() {
empNameEtxt.setText("");
empSalaryEtxt.setText("");
empDobEtxt.setText("");
}
private void setEmployee() {
employee = new Employee();
employee.setName(empNameEtxt.getText().toString());
employee.setSalary(Double.parseDouble(empSalaryEtxt.getText()
.toString()));
if (dateCalendar != null)
employee.setDateOfBirth(dateCalendar.getTime());
}
@Override
public void onResume() {
//getActivity().setTitle(R.string.add_emp);
//getActivity().getActionBar().setTitle(R.string.add_emp);
super.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (dateCalendar != null)
outState.putLong("dateCalendar", dateCalendar.getTime().getTime());
}
private void findViewsById(View rootView) {
empNameEtxt = (EditText) rootView.findViewById(R.id.etxt_name);
empSalaryEtxt = (EditText) rootView.findViewById(R.id.etxt_salary);
empDobEtxt = (EditText) rootView.findViewById(R.id.etxt_dob);
empDobEtxt.setInputType(InputType.TYPE_NULL);
addButton = (Button) rootView.findViewById(R.id.button_add);
resetButton = (Button) rootView.findViewById(R.id.button_reset);
}
@Override
public void onClick(View view) {
if (view == empDobEtxt) {
datePickerDialog.show();
} else if (view == addButton) {
setEmployee();
task = new AddEmpTask(getActivity());
task.execute((Void) null);
} else if (view == resetButton) {
resetAllFields();
}
}
public class AddEmpTask extends AsyncTask<Void, Void, Long> {
private final WeakReference<Activity> activityWeakRef;
public AddEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected Long doInBackground(Void... arg0) {
long result = employeeDAO.save(employee);
return result;
}
@Override
protected void onPostExecute(Long result) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Employee Saved",
Toast.LENGTH_LONG).show();
}
}
}
}
|
7) Run
DOWNLOAD:
.
No comments:
Post a Comment