首页 > 代码库 > Android · SQLite

Android · SQLite

 

package com.manhua.sqlitetest;import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.os.AsyncTask;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.BaseAdapter;import android.widget.EditText;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements        AdapterView.OnItemClickListener {    private DatabaseHelper mDB;    private Cursor mCursor;    private EditText edit_Name;    private EditText edit_Info;    private ListView lv;    private ListAdapter adapter = null;    private int ID = 0;    protected final static int MENU_ADD = Menu.FIRST;    protected final static int MENU_DELETE = Menu.FIRST + 1;    protected final static int MENU_UPDATE = Menu.FIRST + 2;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                mDB = new DatabaseHelper(this);        mCursor = mDB.select();        edit_Name = (EditText) findViewById(R.id.editText1);        edit_Info = (EditText) findViewById(R.id.editText2);        lv = (ListView) findViewById(R.id.listView1);        adapter = new ListAdapter(this, mCursor);        lv.setAdapter(adapter);        lv.setOnItemClickListener(this);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        super.onCreateOptionsMenu(menu);        menu.add(Menu.NONE, MENU_ADD, 0, "ADD");        menu.add(Menu.NONE, MENU_DELETE, 0, "DELETE");        menu.add(Menu.NONE, MENU_UPDATE, 0, "UPDATE");        return true;    }    public boolean onOptionsItemSelected(MenuItem item) {        super.onOptionsItemSelected(item);        switch (item.getItemId()) {        case MENU_ADD:            add();            break;        case MENU_DELETE:            delete();            break;        case MENU_UPDATE:            update();            break;        }        return true;    }    public void add() {        String name = edit_Name.getText().toString();        String info = edit_Info.getText().toString();                if (name.equals("") || info.equals("")) {            return;        }        mDB.insert(name, info);//        mCursor.requery();        new RefreshList().execute();        edit_Name.setText("");        edit_Info.setText("");        Toast.makeText(this, "Add Successed!", Toast.LENGTH_SHORT).show();    }    public void delete() {        if (ID == 0) {            return;        }        mDB.delete(ID);//        mCursor.requery();        new RefreshList().execute();        edit_Name.setText("");        edit_Info.setText("");        Toast.makeText(this, "Delete Successed!", Toast.LENGTH_SHORT).show();    }    public void update() {        String name = edit_Name.getText().toString();        String info = edit_Info.getText().toString();        // 书名和作者都不能为空,或者退出        if (name.equals("") || info.equals("")) {            return;        }        mDB.update(ID, name, info);//        mCursor.requery();        new RefreshList().execute();        edit_Name.setText("");        edit_Info.setText("");        Toast.makeText(this, "Update Successed!", Toast.LENGTH_SHORT).show();    }    @Override    public void onItemClick(AdapterView<?> parent, View view, int position,            long id) {        mCursor.moveToPosition(position);        ID = mCursor.getInt(0);        edit_Name.setText(mCursor.getString(1));        edit_Info.setText(mCursor.getString(2));    }    public class ListAdapter extends BaseAdapter {        private Context mContext;        private Cursor mCursor;        public ListAdapter(Context context, Cursor cursor) {            mContext = context;            mCursor = cursor;        }        @Override        public int getCount() {            return mCursor.getCount();        }        @Override        public Object getItem(int position) {            return null;        }        @Override        public long getItemId(int position) {            return 0;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {            TextView mTextView = new TextView(mContext);            mCursor.moveToPosition(position);            mTextView.setText(mCursor.getString(1) + "___"                    + mCursor.getString(2));            return mTextView;        }    }        //步骤1:通过后台线程AsyncTask来读取数据库,放入更换Cursor    private class RefreshList extends AsyncTask<Void, Void ,Cursor>{        //步骤1.1:在后台线程中从数据库读取,返回新的游标newCursor        protected Cursor doInBackground(Void... params) {            Cursor newCursor =  mDB.select();            return newCursor;        }        //步骤1.2:线程最后执行步骤,更换adapter的游标,并奖原游标关闭,释放资源          protected void onPostExecute(Cursor newCursor) {            adapter.mCursor=newCursor;            mCursor.close();            mCursor = newCursor;            lv.invalidateViews();        }             }}

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.manhua.sqlitetest.MainActivity" >    <EditText        android:id="@+id/editText1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:ems="10"        android:hint="name" />    <EditText        android:id="@+id/editText2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="62dp"        android:ems="10"        android:hint="phone" />    <ListView        android:id="@+id/listView1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/editText2"        android:layout_centerHorizontal="true"        android:layout_marginTop="14dp" >    </ListView></RelativeLayout>

 

 

package com.manhua.sqlitetest;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;// http://www.ibm.com/developerworks/cn/opensource/os-cn-sqlite/index.htmlpublic class DatabaseHelper extends SQLiteOpenHelper {    private final static String DATABASE_NAME = "test.db";    private final static int DATABASE_VERSION = 1;    private final static String TABLE_NAME = "Friends";    public final static String ID = "id";    public final static String NAME = "name";    public final static String INFO = "info";    public DatabaseHelper(Context context) {        // TODO Auto-generated constructor stub        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    // 创建table    @Override    public void onCreate(SQLiteDatabase db) {        String sql = "CREATE TABLE " + TABLE_NAME + " (" + ID                + " INTEGER primary key autoincrement, " + NAME                + " text, " + INFO + " text);";        db.execSQL(sql);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;        db.execSQL(sql);        onCreate(db);    }    public Cursor select() {        SQLiteDatabase db = this.getReadableDatabase();        Cursor cursor = db                .query(TABLE_NAME, null, null, null, null, null, null);        return cursor;    }    // 增加操作    public long insert(String name, String info) {        SQLiteDatabase db = this.getWritableDatabase();        /* ContentValues */        ContentValues cv = new ContentValues();        cv.put(NAME, name);        cv.put(INFO, info);        long row = db.insert(TABLE_NAME, null, cv);        return row;    }    // 删除操作    public void delete(int id) {        SQLiteDatabase db = this.getWritableDatabase();        String where = ID + " = ?";        String[] whereValue = { Integer.toString(id) };        db.delete(TABLE_NAME, where, whereValue);    }    // 修改操作    public void update(int id, String name, String info) {        SQLiteDatabase db = this.getWritableDatabase();        String where = ID + " = ?";        String[] whereValue = { Integer.toString(id) };        ContentValues cv = new ContentValues();        cv.put(NAME, name);        cv.put(INFO, info);        db.update(TABLE_NAME, cv, where, whereValue);    }}

 

Android · SQLite