Thursday, November 5, 2015

Android Fragment SQLite 3


.

Android Fragment SQLite 3
1) Startup
2) Add getEmployees Method to EmployeeDAO
File Name: EmployeeDAO.java
package com.notarazi.myviewpagertablayout1.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ParseException;
import com.notarazi.myviewpagertablayout1.model.Employee;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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_TABLEnull, values);
   }
   //Get all records from the database
   public ArrayList<Employee> getEmployees() {
       ArrayList<Employee> employees = new ArrayList<Employee>();
       Cursor cursor = database.query(DataBaseHelper.EMPLOYEE_TABLE,
               new String[] { DataBaseHelper.ID_COLUMN,
                       DataBaseHelper.NAME_COLUMN,
                       DataBaseHelper.EMPLOYEE_DOB,
                       DataBaseHelper.EMPLOYEE_SALARY }, nullnullnull,
               nullnull);
       while (cursor.moveToNext()) {
           Employee employee = new Employee();
           employee.setId(cursor.getInt(0));
           employee.setName(cursor.getString(1));
           try {
               employee.setDateOfBirth(formatter.parse(cursor.getString(2)));
           } catch (ParseException e) {
               employee.setDateOfBirth(null);
           } catch (java.text.ParseException e) {
               e.printStackTrace();
           }
           employee.setSalary(cursor.getDouble(3));
           employees.add(employee);
       }
       return employees;
   }
}
3) Create Adapter for Employee Model
package com.notarazi.myviewpagertablayout1.model;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.notarazi.myviewpagertablayout1.R;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
public class EmpListAdapter extends ArrayAdapter<Employee> {
   private Context context;
   List<Employee> employees;
   private static final SimpleDateFormat formatter new SimpleDateFormat(
           "yyyy-MM-dd", Locale.ENGLISH);
   public EmpListAdapter(Context context, List<Employee> employees) {
       super(context, R.layout.list_item, employees);
       this.context = context;
       this.employees = employees;
   }
   private class ViewHolder {
       TextView empIdTxt;
       TextView empNameTxt;
       TextView empDobTxt;
       TextView empSalaryTxt;
   }
   @Override
   public int getCount() {
       return employees.size();
   }
   @Override
   public Employee getItem(int position) {
       return employees.get(position);
   }
   @Override
   public long getItemId(int position) {
       return 0;
   }
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
       ViewHolder holder = null;
       if (convertView == null) {
           LayoutInflater inflater = (LayoutInflater) context
                   .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
           convertView = inflater.inflate(R.layout.list_itemnull);
           holder = new ViewHolder();
           holder.empIdTxt = (TextView) convertView
                   .findViewById(R.id.txt_emp_id);
           holder.empNameTxt = (TextView) convertView
                   .findViewById(R.id.txt_emp_name);
           holder.empDobTxt = (TextView) convertView
                   .findViewById(R.id.txt_emp_dob);
           holder.empSalaryTxt = (TextView) convertView
                   .findViewById(R.id.txt_emp_salary);
           convertView.setTag(holder);
       } else {
           holder = (ViewHolder) convertView.getTag();
       }
       Employee employee = (Employee) getItem(position);
       holder.empIdTxt.setText(employee.getId() + "");
       holder.empNameTxt.setText(employee.getName());
       holder.empSalaryTxt.setText(employee.getSalary() + "");
       holder.empDobTxt.setText(formatter.format(employee.getDateOfBirth()));
       return convertView;
   }
   @Override
   public void add(Employee employee) {
       employees.add(employee);
       notifyDataSetChanged();
       super.add(employee);
   }
   @Override
   public void remove(Employee employee) {
       employees.remove(employee);
       notifyDataSetChanged();
       super.remove(employee);
   }
}
4) Update Fragment Controller (Fragment 2)
File Name: Fragment2.java
(Orange highlighted statements are commented at the moment. They will be used at later steps)
package com.notarazi.myviewpagertablayout1;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.notarazi.myviewpagertablayout1.db.EmployeeDAO;
import com.notarazi.myviewpagertablayout1.model.EmpListAdapter;
import com.notarazi.myviewpagertablayout1.model.Employee;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class FragmentPage2 extends Fragment implements OnItemClickListener,
       OnItemLongClickListener {
   public static final String ARG_ITEM_ID "employee_list";
   Activity activity;
   ListView employeeListView;
   ArrayList<Employee> employees;
   EmpListAdapter employeeListAdapter;
   EmployeeDAO employeeDAO;
   private GetEmpTask task;
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       activity = getActivity();
       employeeDAO new EmployeeDAO(activity);
   }
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment_page2, container,
               false);
       findViewsById(view);
       task new GetEmpTask(activity);
       task.execute((Void) null);
       employeeListView.setOnItemClickListener(this);
       employeeListView.setOnItemLongClickListener(this);
       // Employee e = employeeDAO.getEmployee(1);
       // Log.d("employee e", e.toString());
       return view;
   }
   private void findViewsById(View view) {
       employeeListView = (ListView) view.findViewById(R.id.list_emp);
   }
   @Override
   public void onResume() {
       //getActivity().setTitle(R.string.app_name);
       //getActivity().getActionBar().setTitle(R.string.app_name);
       super.onResume();
   }
   @Override
   public void onItemClick(AdapterView<?> list, View arg1, int position,
                           long arg3) {
       Employee employee = (Employee) list.getItemAtPosition(position);
       if (employee != null) {
           Bundle arguments = new Bundle();
           arguments.putParcelable("selectedEmployee", employee);
           //**CustomEmpDialogFragment customEmpDialogFragment = new CustomEmpDialogFragment();
           //**customEmpDialogFragment.setArguments(arguments);
           //**customEmpDialogFragment.show(getFragmentManager(),
           //**        CustomEmpDialogFragment.ARG_ITEM_ID);
       }
   }
   @Override
   public boolean onItemLongClick(AdapterView<?> parent, View view,
                                  int position, long arg3) {
       Employee employee = (Employee) parent.getItemAtPosition(position);
       // Use AsyncTask to delete from database
       //**employeeDAO.delete(employee);
       //**employeeListAdapter.remove(employee);
       return true;
   }
   public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Employee>> {
       private final WeakReference<Activity> activityWeakRef;
       public GetEmpTask(Activity context) {
           this.activityWeakRef new WeakReference<Activity>(context);
       }
       @Override
       protected ArrayList<Employee> doInBackground(Void... arg0) {
           ArrayList<Employee> employeeList = employeeDAO.getEmployees();
           return employeeList;
       }
       @Override
       protected void onPostExecute(ArrayList<Employee> empList) {
           if (activityWeakRef.get() != null
                   && !activityWeakRef.get().isFinishing()) {
               Log.d("employees", empList.toString());
               employees = empList;
               if (empList != null) {
                   if (empList.size() != 0) {
                       employeeListAdapter new EmpListAdapter(activity,
                               empList);
                       employeeListView.setAdapter(employeeListAdapter);
                   } else {
                       Toast.makeText(activity"No Employee Records",
                               Toast.LENGTH_LONG).show();
                   }
               }
           }
       }
   }
   /*
    * This method is invoked from MainActivity onFinishDialog() method. It is
    * called from CustomEmpDialogFragment when an employee record is updated.
    * This is used for communicating between fragments.
    */
   public void updateView() {
       task new GetEmpTask(activity);
       task.execute((Void) null);
   }
}
5) RUN
DOWNLOAD:

.

No comments:

Post a Comment