为组创建脱机SQLite数据库

时间:2014-06-10 13:52:11

标签: android sqlite

我正在尝试在我的应用程序中为组页面创建数据库。但我不知道如何创造这个。 此页面包含两个文本组。那是我的小组和我的二级小组。这两个组中的每一个都包含用于选择电子邮件ID的微调器。通过选择特定的电子邮件ID,有两个添加和删除按钮。 当我选择一个Id并点击添加按钮然后它保存在服务器端。在点击下方的另一个文本视图点击我可以看到ID被添加。如果我想要添加的这个选择的ID已经存在然后消息display.same for delete按钮。和我的二级组相同。现在我只想知道如何为这个页面创建和存储SQLite数据库,以便从SQLite而不是Web服务器获取数据。

**Fragmentgroups.java**



    public class FragmentGroups extends Fragment {

         private SharedPreferences pref;
         Cursor cursor;
         ArrayList<member> membr,membr2;
         ListView list1 ;
         ListView list2 ;
         Button add,delete,add2,delete2;
         TextView gp1,gp2;
         GroupAdapter groupadapter;
         private Typeface ftype;
         SendJobDataBase db;
         FragmentDialog dialog ;
         ArrayList<String> emailArray = new ArrayList<String>();
         String memail;
         private String login_token;
         ArrayAdapter<String> adapter ;
         Spinner e1,e2;
         String emails[];

         public FragmentGroups(){}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.group_fragment, container, false);
            e1=(Spinner) rootView.findViewById(R.id.eemail);
            e2=(Spinner) rootView.findViewById(R.id.eemail2); 
                     new Members().execute();
             add =(Button) rootView.findViewById(R.id.add);
             add2 =(Button) rootView.findViewById(R.id.add2);
             delete =(Button) rootView.findViewById(R.id.delete);
             delete2 =(Button) rootView.findViewById(R.id.delete2);
             gp1  =(TextView) rootView.findViewById(R.id.viewm);
             gp2  =(TextView) rootView.findViewById(R.id.views);
             pref=this.getActivity().getSharedPreferences("Driver", getActivity().MODE_WORLD_READABLE);
             login_token = pref.getString("login_token","login_token"); 

            add.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                    new AddMembers().execute(); 
                    }           
                });

            add2.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                        new AddMembers2().execute();    
                        }           
                    });

            delete.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                        new DeleteMembers().execute();  
                        }           
                    });
            delete2.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                        new DeleteMembers2().execute(); 
                        }           
                    });

            gp1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intent =new Intent(getActivity() ,viewgroup.class);
                    startActivity(intent);
                        }           
                    });

            gp2.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent intent2 =new Intent(getActivity() ,viewsecgroup.class);
                    startActivity(intent2);
                        }           
                    });

             return rootView;
           }

        private class Members extends AsyncTask<String, String, String[]> {


            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    try 
                    {
                        JSONObject job= new JSONObject();
                         job.put("status_key","2");
                         job.put("method","driver_emails");
                         job.put("login_token",login_token);
                         System.out.print(login_token);


                      StringEntity se = new StringEntity(job.toString());
                      HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                      httppost.setEntity(se);

                      HttpResponse response = httpclient.execute(httppost);
                      String data = EntityUtils.toString(response.getEntity());

                      JSONObject jo = new JSONObject(data);
                      Log.d("response", jo.toString(4));

                        JSONArray jArray = jo.getJSONArray("all_driver_email_Ids");  
                          for (int i=0; i < jArray.length(); i++)
                        {
                            System.out.println("please print my name...for....");
                            try {
                                JSONObject jsob = jArray.getJSONObject(i);
                                emailArray.add(jsob.getString("Email").toString());

                                 adapter = new ArrayAdapter<String>(getActivity(), R.layout.listrow, emailArray);           
                          } catch (JSONException e) {

                            } 
                        }

                        }
                catch (Exception e) 
                    {
                        e.printStackTrace();
                    }
                }

                return params;

            }             

            @SuppressLint("NewApi")
            @Override
            protected void onPostExecute(String[] result) 
            {

                super.onPostExecute(result);
                e1.setAdapter(adapter); 
                e2.setAdapter(adapter);
            }
            }   

        private class AddMembers extends AsyncTask<String, String, String[]> {
            ProgressDialog pDialog = new ProgressDialog(getActivity());
            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    try 
                    {
                    JSONObject job= new JSONObject();

                        memail= e1.getSelectedItem().toString();
                        System.out.println(memail);
                        memail.replace("" ,"%20");
                         job.put("email",memail);

                         job.put("status_key","2");
                         job.put("method","add_emails");
                         job.put("login_token",login_token);

                        StringEntity se = new StringEntity(job.toString());
                        HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                        httppost.setEntity(se);
                        HttpResponse response = httpclient.execute(httppost);
                        String data = EntityUtils.toString(response.getEntity());
                           Log.i("response", data);

                            System.out.println("response "+data);
                                    String call;
                                    call = data;

                                    System.out.println("print me............."+call);

                                    JSONObject jo = new JSONObject(data);
                                    Log.d("response", jo.toString(4));

                                    if(jo.getString("err-code").equals("0"))
                                    {
                                        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert!!!");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) 
                                            {
                                                pDialog.dismiss();
                                    dialog.dismiss();


                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() {
                                            public void run() {
                                                alert.show();
                                            }
                                        });
                                    }
                                    else
                                    {
                                final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert !");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                                dialog.dismiss();

                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() 
                                        {
                                            public void run() 
                                            {
                                                pDialog.dismiss();

                                                alert.show();
                                            }
                                        });
                                    }

                                }
                                catch (Exception e) 
                                {
                                    e.printStackTrace();
                                }
                            }
                            return params;
                        }
                        @Override
                        protected void onPostExecute(String[] result) 
                        {

                            super.onPostExecute(result);
                        }       
            }   


        private class DeleteMembers extends AsyncTask<String, String, String[]> {
            ProgressDialog pDialog = new ProgressDialog(getActivity());
            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    try 
                    {
                    JSONObject job= new JSONObject();

                        memail= e1.getSelectedItem().toString();
                        System.out.println("email is " +memail);
                        memail.replace("" ,"%20");
                         job.put("email",memail);
                         job.put("status_key","2");
                         job.put("method","delete_groupemails");
                         job.put("login_token",login_token);

                        StringEntity se = new StringEntity(job.toString());
                        HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                        httppost.setEntity(se);
                        HttpResponse response = httpclient.execute(httppost);
                        String data = EntityUtils.toString(response.getEntity());
                           Log.i("response", data);

                            System.out.println("response "+data);
                                    String call;
                                    call = data;

                                    System.out.println("print me............."+call);

                                    JSONObject jo = new JSONObject(data);
                                    Log.d("response", jo.toString(4));

                                    if(jo.getString("err-code").equals("0"))
                                    {
                                        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert!!!");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) 
                                            {
                                                pDialog.dismiss();
                                    dialog.dismiss();


                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() {
                                            public void run() {
                                                alert.show();
                                            }
                                        });
                                    }
                                    else
                                    {
                                final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert !");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                                dialog.dismiss();

                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() 
                                        {
                                            public void run() 
                                            {
                                                pDialog.dismiss();

                                                alert.show();
                                            }
                                        });
                                    }

                                }
                                catch (Exception e) 
                                {
                                    e.printStackTrace();
                                }
                            }
                            return params;
                        }
                        @Override
                        protected void onPostExecute(String[] result) 
                        {

                            super.onPostExecute(result);
                        }

        }   


        private class AddMembers2 extends AsyncTask<String, String, String[]> {
            ProgressDialog pDialog = new ProgressDialog(getActivity());
            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    try 
                    {
                    JSONObject job= new JSONObject();

                        memail= e2.getSelectedItem().toString();
                        System.out.println(memail);
                        memail.replace("" ,"%20");
                         job.put("email",memail);
                         job.put("status_key","2");
                         job.put("method","add_myscndryemails");
                         job.put("login_token",login_token);

                        StringEntity se = new StringEntity(job.toString());
                        HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                        httppost.setEntity(se);
                        HttpResponse response = httpclient.execute(httppost);
                        String data = EntityUtils.toString(response.getEntity());
                           Log.i("response", data);

                            System.out.println("response "+data);
                                    String call;
                                    call = data;

                                    System.out.println("print me............."+call);

                                    JSONObject jo = new JSONObject(data);
                                    Log.d("response", jo.toString(4));

                                    if(jo.getString("err-code").equals("0"))
                                    {
                                        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert!!!");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) 
                                            {
                                                pDialog.dismiss();
                                    dialog.dismiss();


                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() {
                                            public void run() {
                                                alert.show();
                                            }
                                        });
                                    }
                                    else
                                    {
                                final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert !");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                                dialog.dismiss();

                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() 
                                        {
                                            public void run() 
                                            {
                                                pDialog.dismiss();

                                                alert.show();
                                            }
                                        });
                                    }

                                }
                                catch (Exception e) 
                                {
                                    e.printStackTrace();
                                }
                            }
                            return params;
                        }
                        @Override
                        protected void onPostExecute(String[] result) 
                        {

                            super.onPostExecute(result);
                        }       
                   }    

        private class DeleteMembers2 extends AsyncTask<String, String, String[]> {
            ProgressDialog pDialog = new ProgressDialog(getActivity());
            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    try 
                    {
                    JSONObject job= new JSONObject();

                        memail= e2.getSelectedItem().toString();
                        System.out.println("email is " +memail);
                        memail.replace("" ,"%20");
                         job.put("email",memail);

                         job.put("status_key","2");
                         job.put("method","delete_scndryemails");
                         job.put("login_token",login_token);

                        StringEntity se = new StringEntity(job.toString());
                        HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/mobileapp_now/webservice.php");
                        httppost.setEntity(se);
                        HttpResponse response = httpclient.execute(httppost);
                        String data = EntityUtils.toString(response.getEntity());
                           Log.i("response", data);

                            System.out.println("response "+data);
                                    String call;
                                    call = data;

                                    System.out.println("print me............."+call);

                                    JSONObject jo = new JSONObject(data);
                                    Log.d("response", jo.toString(4));

                                    if(jo.getString("err-code").equals("0"))
                                    {
                                        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert!!!");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) 
                                            {
                                                pDialog.dismiss();
                                    dialog.dismiss();
                                        }
                                        });
                                        getActivity().runOnUiThread(new Runnable() {
                                            public void run() {
                                                alert.show();
                                            }
                                        });
                                    }
                                    else
                                    {
                                final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                                        alert.setTitle("Alert !");
                                        alert.setMessage(jo.getString("message"));
                                        alert.setPositiveButton("Ok",
                                                new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                                dialog.dismiss();

                                            }
                                        });
                                        getActivity().runOnUiThread(new Runnable() 
                                        {
                                            public void run() 
                                            {
                                                pDialog.dismiss();

                                                alert.show();
                                            }
                                        });
                                    }

                                }
                                catch (Exception e) 
                                {
                                    e.printStackTrace();
                                }
                            }
                            return params;
                        }
                        @Override
                        protected void onPostExecute(String[] result) 
                        {

                            super.onPostExecute(result);
                        }

        }   

    }




**GroupAdapter.java**



package com.sunmobile.navigationdrawer;

import java.util.ArrayList;
import com.sunmobileappnow.mobileappnow.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;



public class GroupAdapter extends ArrayAdapter<member> {


    GroupAdapter gdb;
    Activity activity;
    int layoutResourceId;
    member user;
    ArrayList<member> data = new ArrayList<member>();
    ListView l1;
    SendJobDataBase db;
   FragmentGroups fg;




public GroupAdapter(Activity act, int layoutResourceId,
            ArrayList<member> data) {
            super(act, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.activity = act;
            this.data = data;
            notifyDataSetChanged();
        }



    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        MemberHolder holder = null;

        if (row == null) {
        LayoutInflater inflater = LayoutInflater.from(activity);

        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new MemberHolder();
        holder.name = (TextView) row.findViewById(R.id.user_name_txt);
        holder.delete = (Button) row.findViewById(R.id.btn_delete);
        row.setTag(holder);
       } else {
    holder = (MemberHolder) row.getTag();
        }
       user = data.get(position);

        holder.name.setText(user.getName());




      holder.delete.setOnClickListener(new OnClickListener() {

        public void onClick(final View v) {


            AlertDialog.Builder adb = new AlertDialog.Builder(activity);
            adb.setTitle("Delete?");
            adb.setMessage("Are you sure you want to delete ");
            final int user_id = Integer.parseInt(v.getTag().toString());
            adb.setNegativeButton("Cancel", null);
            adb.setPositiveButton("Ok",
                new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog,
                    int which) {
                    // MyDataObject.remove(positionToRemove);
                    SendJobDataBase dBHandler = new SendJobDataBase(
                        activity.getApplicationContext());
                   dBHandler.Delete_Contact(user_id);


                }
                });    


            adb.show();
        }

        });  
        return row;

    }

    class MemberHolder {
        TextView name;
       Button delete;
    }

    }

1 个答案:

答案 0 :(得分:2)

我用于SQLite数据库交互的模板如下:

创建数据库的助手:

public class DatabaseHelper extends SQLiteOpenHelper
{
   private static final String DATABASE_NAME = "database.db";
   private static final int DATABASE_VERSION = 1;

   public DatabaseHelper(Context context)
   {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

   @Override
   public void onCreate(SQLiteDatabase database)
   {
      Table1.onCreate(database);
      Table2.onCreate(database);
      Table3.onCreate(database);
   }

   @Override
   public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
   {
      Table1.onUpgrade(database, oldVersion, newVersion);
      Table2.onUpgrade(database, oldVersion, newVersion);
      Table3.onUpgrade(database, oldVersion, newVersion);
   }
}

以表格为例:

public class Table1
{
    public static final String TABLE_TABLE1 = "table1";

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_PHONENUMBER = "phoneNumber";
    public static final String COLUMN_EMAIL = "email";

    private static final String DATABASE_CREATE = "create table " + TABLE_TABLE1 + "(" 
    + COLUMN_ID + " integer primary key autoincrement, " 
    + COLUMN_NAME + " text not null, "
    + COLUMN_PHONENUMBER + " text not null, "
    + COLUMN_EMAIL + " text not null, "
    + ");";

    public static void onCreate(SQLiteDatabase database)
    {
       database.execSQL(DATABASE_CREATE);
    }

    public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
    {
       Log.w(Table1.class.getName(), "Upgrading from version " + oldVersion + " to " + newVersion);
       database.execSQL("DROP TABLE IF EXISTS " + TABLE_TABLE1);
       onCreate(database);
    }
}

表格的操作:

public class Table1DataSource
{
    // Database fields
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private String[] allColumns = { Table1.COLUMN_ID, Table1.COLUMN_NAME,
            Table1.COLUMN_PHONENUMBER, Table1.COLUMN_EMAIL };

    public Table1DataSource(Context context)
    {
        dbHelper = new DatabaseHelper(context);
    }

    public void open() throws SQLException
    {
        database = dbHelper.getWritableDatabase();
    }

    public void close()
    {
        dbHelper.close();
    }

    private EmployeeDB cursorToEmployee(Cursor cursor)
    {
        EmployeeDB Employee = new EmployeeDB();
        Employee.setId(cursor.getLong(0));
        Employee.setName(cursor.getString(1));
        Employee.setPhoneNumber(cursor.getString(2));
        Employee.setEmail(cursor.getString(3));
        return Employee;
    }

    public EmployeeDB createEmployee(String name, String phoneNumber, String email)
    {
        ContentValues values = new ContentValues();new
        values.put(Table1.COLUMN_NAME, name);
        values.put(Table1.COLUMN_PHONENUMBER, phoneNumber);
        values.put(Table1.COLUMN_EMAIL, email);
        long insertId = database.insert(Table1.TABLE_TABLE1, null, values);
        Cursor cursor = database.query(Table1.TABLE_TABLE1, allColumns, Table1.COLUMN_ID
                + " = " + insertId, null, null, null, null);
        cursor.moveToFirst();
        EmployeeDB newEmployee = cursorToEmployee(cursor);
        cursor.close();
        return newEmployee;
    }

    public void updateEmployee(EmployeeDB employee)
    {
        ContentValues values = new ContentValues();
        values.put(Table1.COLUMN_NAME, name);
        values.put(Table1.COLUMN_PHONENUMBER, phoneNumber);
        values.put(Table1.COLUMN_EMAIL, email);
        database.update(Table1.TABLE_TABLE1, values, Table1.COLUMN_ID + " = ?", new String[]{""+employee.getId()});
    }

    public void deleteEmployee(EmployeeDB Employee)
    {
        long id = Employee.getId();
        database.delete(EmployeeTable.TABLE_EMPLOYEE, EmployeeTable.COLUMN_ID + " = " + id, null);
    }

    public Cursor getAllEmployees()
    {
        return database.query(EmployeeTable.TABLE_EMPLOYEE, allColumns, null, null, null, null, null);
    }

    public EmployeeDB findEmployeeById(long id)
    {
        EmployeeDB employee = null;
        Cursor cursor = database.query(EmployeeTable.TABLE_EMPLOYEE, allColumns, EmployeeTable.COLUMN_ID + " = ?", new String[] {""+id}, null, null, null);
        if(cursor.moveToFirst())
        {
            employee = cursorToEmployee(cursor);
        }
        return employee;
    }

    public List<EmployeeDB> getAllEmployeesList()
    {
        List<EmployeeDB> Employees = new ArrayList<EmployeeDB>();

        Cursor cursor = getAllEmployees();

        if (cursor.moveToFirst())
        {
            do
            {
                EmployeeDB Employee = cursorToEmployee(cursor);
                Employees.add(Employee);
            }
            while (cursor.moveToNext());
        }
        cursor.close();
        return Employees;
    } 
}


编辑:稍微更新一些版本(在2017-04-29中重访):

public class DatabaseManager
        extends SQLiteOpenHelper {
    public interface Table {
        String getTableName();

        Fields[] getFields();

        void onCreate(SQLiteDatabase database);

        void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion);
    }

    public interface Fields {
        String getFieldName();

        String getFieldType();

        String getFieldAdditional();
    }

    public interface QueryDefinition {
        Cursor query(SQLiteDatabase database, Table table, String[] allFields);
    }

    private static final String DATABASE_NAME = "database.db";

    private static final int DATABASE_VERSION = 1;

    private final List<Table> tables;

    private SQLiteDatabase database;

    public DatabaseManager(Context appContext, List<Table> tables) {
        super(appContext, DATABASE_NAME, null, DATABASE_VERSION);
        this.tables = tables;
        this.database = getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        for(Table table : tables) {
            table.onCreate(database);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        for(Table table : tables) {
            table.onUpgrade(database, oldVersion, newVersion);
        }
    }

    public interface Transaction {
        void execute(SQLiteDatabase sqLiteDatabase);
    }

    public interface Mapper<T> {
        T from(Cursor cursor);

        ContentValues from(ContentValues contentValues, T t);
    }

    public void executeTransaction(Transaction transaction) {
        try {
            database.beginTransaction();
            transaction.execute(database);
            database.setTransactionSuccessful();
        } finally {
            if(database.inTransaction()) {
                database.endTransaction();
            }
        }
    }

    public <T> List<T> findAll(Table table, Mapper<T> mapper) {
        return findAll(table,
                mapper, (database, _table, allFields) -> database.query(_table.getTableName(), allFields, null, null, null, null, null));
    }

    public <T> List<T> findAll(Table table, Mapper<T> mapper, QueryDefinition queryDefinition) {
        String[] allFields = extractFieldsFromTable(table);
        Cursor cursor = queryDefinition.query(database, table, allFields);
        List<T> list = collectObjectFromCursor(mapper, cursor);
        cursor.close();
        return list;
    }

    private <T> List<T> collectObjectFromCursor(Mapper<T> mapper, Cursor cursor) {
        List<T> list = new LinkedList<>();
        if(cursor.moveToFirst()) {
            do {
                T object = mapper.from(cursor);
                list.add(object);
            } while(cursor.moveToNext());
        }
        return new ArrayList<>(list);
    }

    @NonNull
    private String[] extractFieldsFromTable(Table table) {
        Fields[] _fields = table.getFields();
        String[] fields = new String[_fields.length];
        int i = 0;
        for(Fields field : _fields) {
            fields[i++] = field.getFieldName();
        }
        return fields;
    }
}


public abstract class BaseTable
        implements DatabaseManager.Table {
    @Override
    public void onCreate(SQLiteDatabase database) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("CREATE TABLE ");
        stringBuilder.append(getTableName());
        stringBuilder.append("(");
        DatabaseManager.Fields[] fields = getFields();
        int size = fields.length;
        int i = 0;
        for(DatabaseManager.Fields field : fields) {
            stringBuilder.append(field.getFieldName());
            stringBuilder.append(" ");
            stringBuilder.append(field.getFieldType());
            stringBuilder.append(" ");
            if(field.getFieldAdditional() != null) {
                stringBuilder.append(field.getFieldAdditional());
            }
            if(i < size - 1) {
                stringBuilder.append(",");
            }
            i++;
        }
        stringBuilder.append(");");
        database.execSQL(stringBuilder.toString());
    }

    @Override // TODO: implement migration
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        Log.w("Table[" + getTableName() + "]", "Upgrading from version " + oldVersion + " to " + newVersion);
        database.execSQL("DROP TABLE IF EXISTS " + getTableName());
        onCreate(database);
    }
}

public enum Tables {
    CAT(new CatTable());

    private DatabaseManager.Table table;

    Tables(DatabaseManager.Table table) {
        this.table = table;
    }

    public <T extends DatabaseManager.Table> T getTable() {
        //noinspection unchecked
        return (T) table;
    }

    public static List<DatabaseManager.Table> getTables() {
        Tables[] _tables = Tables.values();
        List<DatabaseManager.Table> tables = new ArrayList<>(_tables.length);
        for(Tables table : _tables) {
            tables.add(table.table);
        }
        return tables;
    }
}

public class CatTable
        extends BaseTable {
    public static final String NAME = "cat";

    public enum Fields
            implements DatabaseManager.Fields {
        ID("_id", "text", "primary key"), //"integer", "primary key autoincrement"),
        URL("url", "text", "not null"),
        SOURCE_URL("sourceUrl", "text", "not null");

        private String fieldName;
        private String fieldType;
        private String fieldAdditional;

        Fields(String fieldName, String fieldType, String fieldAdditional) {
            this.fieldName = fieldName;
            this.fieldType = fieldType;
            this.fieldAdditional = fieldAdditional;
        }

        public String getFieldName() {
            return fieldName;
        }

        public String getFieldType() {
            return fieldType;
        }

        public String getFieldAdditional() {
            return fieldAdditional;
        }
    }

    @Override
    public String getTableName() {
        return NAME;
    }

    @Override
    public DatabaseManager.Fields[] getFields() {
        return Fields.values();
    }
}

public class CatMapper
        implements DatabaseManager.Mapper<Cat> {
    @Override
    public Cat from(Cursor cursor) {
        return Cat.create(cursor.getString(0), cursor.getString(1), cursor.getString(2));
    }

    @Override
    public ContentValues from(ContentValues contentValues, Cat cat) {
        contentValues.put(CatTable.Fields.ID.getFieldName(), cat.id());
        contentValues.put(CatTable.Fields.URL.getFieldName(), cat.url());
        contentValues.put(CatTable.Fields.SOURCE_URL.getFieldName(), cat.sourceUrl());
    }
}

public class CatDao {
    CatTable catTable;

    CatMapper catMapper;

    DatabaseManager databaseManager;

    public CatDao(CatTable catTable, CatMapper catMapper, DatabaseManager databaseManager) {
        this.catTable = catTable;
        this.catMapper = catMapper;
        this.databaseManager = databaseManager;
    }

    public List<Cat> findAll() {
        return databaseManager.findAll(catTable, catMapper);
    }

    public void insert(List<Cat> cats) {
        databaseManager.executeTransaction(sqLiteDatabase -> {
            ContentValues contentValues = new ContentValues();
            for(Cat cat : cats) {
                contentValues = mapper.from(contentValues, cat);
                sqLiteDatabase.insertWithOnConflict(catTable.getTableName(), null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
            }
        });
    }
}

@AutoValue
public abstract class Cat {
    public abstract String id();

    public abstract String url();

    public abstract String sourceUrl();

    public static Cat create(String id, String url, String sourceUrl) {
        return new AutoValue_Cat.Builder().setId(id).setUrl(url).setSourceUrl(sourceUrl).build();
    }

    public Builder toBuilder() {
        return new AutoValue_Cat.Builder(this);
    }

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setId(String id);

        public abstract Builder setUrl(String url);

        public abstract Builder setSourceUrl(String sourceUrl);

        public abstract Cat build();
    }
}