«

使用SQLite数据库保存和处理数据

时间:2024-3-2 18:12     作者:韩俊     分类: Android


项目目的:

1. 使用SQLite数据库保存数据

2. 使用SQLite数据库的数据进行增删查改等操作。

3.学会使用SQLiteOpenHelper和SQLiteDatabase。


项目内容:

下面4图分别为主界面(1),按添加进行添加操作(2),点击listView的item进行修改操作(3),长按item进行删除操作(4)


项目结构为:


下面是代码:

Member.java

package android.ex08;

public class Member {
    private long ID=-1;
    private String name;
    private String phone;
    @Override
    public String toString(){
        String result="";
        result+="ID: "+this.ID+", ";
        result+="姓名: "+this.name+", ";
        result+="号码: "+this.phone;
        return result;
    }
    public long getID(){
        return ID;
    }
    public String getName(){
        return name;
    }
    public String getPhone(){
        return phone;
    }
    public void setID(long newID){
        ID=newID;
    }
    public void setName(String newName){
        name=newName;
    }
    public void setPhone(String newPhone){
        phone=newPhone;
    }
}

MemberDAO.java
package android.ex08;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MemberDAO extends SQLiteOpenHelper {
    private static final String DB_NAME="member.db";
    private static final int DB_VERSION=1;
    private static final String TABLE_NAME="member";  
    private static final String SQL_CREATE_TABLE="create table "+TABLE_NAME
            +"(_id integer primary key autoincrement,"
            +" name text not null , info text);"; 
    public MemberDAO(Context context){
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        //onCreate(db);
    }

    public long insert(Member entity){
        SQLiteDatabase db=getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("name",entity.getName());
        values.put("info",entity.getPhone());
        long rid=db.insert(TABLE_NAME, null, values);
        db.close();
        return rid;
    }
    public long update(Member entity){
        SQLiteDatabase db=getWritableDatabase();
        String whereClause="_id=?";
        String[] whereArgs={String.valueOf(entity.getID())};
        ContentValues values=new ContentValues();
        values.put("name",entity.getName());
        values.put("info",entity.getPhone());
        long rows=db.update(TABLE_NAME, values, whereClause, whereArgs);
        db.close();
        return rows;
    }
    public long delete(long ID){
        SQLiteDatabase db=getWritableDatabase();
        long rows=db.delete(TABLE_NAME, "_id=?", new String[]{String.valueOf(ID)});
        db.close();
        return rows;
    }
    public long deleteAll(){
        SQLiteDatabase db=getWritableDatabase();
        long rows=db.delete(TABLE_NAME, null, null);
        db.close();
        return rows;
    }
    public Member[] getAllData(){
        SQLiteDatabase db=getReadableDatabase();
        Cursor result=db.query(TABLE_NAME, null, null, null, null, null, null);
        return ConvertToMember(result);
    }

    private Member[] ConvertToMember(Cursor cursor){
        int resultCounts=cursor.getCount();
        if(resultCounts==0||!cursor.moveToFirst()){
            return null;
        }
        Member[] members=new Member[resultCounts];
        for(int i=0;i<resultCounts;i++){
            members[i]=new Member();
            members[i].setID(cursor.getInt(0));
            members[i].setName(cursor.getString(cursor.getColumnIndex("name")));
            members[i].setPhone(cursor.getString(cursor.getColumnIndex("info")));
            cursor.moveToNext();
        }
        return members;
    }
}

MainActivity.java

package android.ex08;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
    public MemberDAO memberDAO=new MemberDAO(this);
    public Member[] members;
    private Button insert;
    private ListView listView;
    private List<Map<String, String>> arrayList=new ArrayList<Map<String, String>>();
    private SimpleAdapter simpleAdapter;
    private void setData(){
        members=memberDAO.getAllData();
        Map<String, String> map;
        if(members==null){ 
            return;
        }
        int count=members.length;
        if(count!=0){
            for(int i=0;i<count;i++){
                map=new HashMap<String, String>();
                map.put("name", members[i].getName());
                map.put("info", members[i].getPhone());
                arrayList.add(map);
            }
        }
    } 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        insert=(Button)findViewById(R.id.button1);
        listView=(ListView)findViewById(R.id.listView1);
        setData();
        simpleAdapter=new SimpleAdapter(this, 
                arrayList, R.layout.list_item, new String[]{"name","info"},
                new int[]{R.id.listName,R.id.listInfo});
        listView.setAdapter(simpleAdapter);  
        insert.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
                MainActivity.this.finish();         
            }
        });
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent intent=new Intent(MainActivity.this, ThirdActivity.class);
                Bundle bundle=new Bundle();
                bundle.putLong("ID", id);
                intent.putExtras(bundle);
                startActivity(intent);
                MainActivity.this.finish(); 
            }
        });
        ItemOnLongClick();       
    }
    public void ItemOnLongClick() {
        //注:setOnCreateContextMenuListener是与下面onContextItemSelected配套使用的
        listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
                    menu.add(0, 0, 0, "删除");//设置弹出菜单的条目
            }
            });
        }
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int MID = (int) info.id;            //MID为listView中的数据序号,从0开始
        switch (item.getItemId()) {
        case 0:
            // 删除操作 ,修改数据库
            members=memberDAO.getAllData();
            long _id=members[MID].getID();
            memberDAO.delete(_id);
            arrayList.remove(MID);         //从链表中把该item移除
            simpleAdapter.notifyDataSetChanged();  //更新适配器              
            Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }
        return super.onContextItemSelected(item);
    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

SecondActivity.java

package android.ex08;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
//处理insert操作
public class SecondActivity extends Activity {

    public MemberDAO memberDAO=new MemberDAO(this);
    private EditText textName,textPhone;
    private Button confirm,cancel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insert_mem);
        textName=(EditText)findViewById(R.id.insert_editText1);
        textPhone=(EditText)findViewById(R.id.insert_editText2);
        confirm=(Button)findViewById(R.id.insert_button1);
        cancel=(Button)findViewById(R.id.insert_button2);
        confirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Member member=new Member();
                member.setName(textName.getText().toString());
                member.setPhone(textPhone.getText().toString());
                memberDAO.insert(member);
                Intent intent=new Intent(SecondActivity.this,MainActivity.class);
                startActivity(intent);
                SecondActivity.this.finish();   
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SecondActivity.this,MainActivity.class);
                startActivity(intent);
                SecondActivity.this.finish();   
            }
        });

    }

}

ThirdActivity.java
package android.ex08;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
//处理update操作
public class ThirdActivity extends Activity {
    public MemberDAO memberDAO=new MemberDAO(this);
    private EditText textName,textPhone;
    private Button confirm,cancel;
    private long bundle_ID;
    Member[] members=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_mem);
        textName=(EditText)findViewById(R.id.update_editText1);
        textPhone=(EditText)findViewById(R.id.update_editText2);
        confirm=(Button)findViewById(R.id.update_button1);
        cancel=(Button)findViewById(R.id.update_button2);
        Bundle bundle=ThirdActivity.this.getIntent().getExtras();       
        bundle_ID=bundle.getLong("ID");
        members=memberDAO.getAllData();
        textName.setText(members[(int)bundle_ID].getName());
        textPhone.setText(members[(int)bundle_ID].getPhone());
        confirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {   
                members[(int)bundle_ID].setName(textName.getText().toString());
                members[(int)bundle_ID].setPhone(textPhone.getText().toString());
                memberDAO.update(members[(int)bundle_ID]);
                Intent intent=new Intent(ThirdActivity.this,MainActivity.class);
                startActivity(intent);
                ThirdActivity.this.finish();

            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ThirdActivity.this,MainActivity.class);
                startActivity(intent);
                ThirdActivity.this.finish();    
            }
        });

    }

}

activity_main.xml
<LinearLayout 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:orientation="vertical"
    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="android.ex08.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/memberList"
        android:textSize="22sp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/insert" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

insert_mem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/insert_textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/insertMember"
        android:textSize="22sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/insert_textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="@string/name" />

        <EditText
            android:id="@+id/insert_editText1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="@string/enterName">

            <requestFocus />
        </EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/insert_textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="@string/phone"/>

        <EditText
            android:id="@+id/insert_editText2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="@string/enterPhone"
            android:inputType="phone" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="50dp" >

        <Button
            android:id="@+id/insert_button1"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/confirm"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_marginRight="50dp">

            <Button
                android:id="@+id/insert_button2"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:text="@string/cancel" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

update_mem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/update_textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/updateMember"
        android:textSize="22sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/update_textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="@string/name" />

        <EditText
            android:id="@+id/update_editText1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="@string/enterName">

            <requestFocus />
        </EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/update_textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="@string/phone"/>

        <EditText
            android:id="@+id/update_editText2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="@string/enterPhone"
            android:inputType="phone" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="50dp" >

        <Button
            android:id="@+id/update_button1"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/confirm"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_marginRight="50dp">

            <Button
                android:id="@+id/update_button2"
                android:layout_width="80dp"
                android:layout_height="wrap_content"
                android:text="@string/cancel" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

list_item.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/listName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textSize="22sp"/>

    <TextView
        android:id="@+id/listInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="@string/phone"/>

</LinearLayout>

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">EX08</string>    
    <string name="app_name1">SecondActivity</string>  
    <string name="app_name2">ThirdActivity</string>    
    <string name="action_settings">Settings</string>
    <string name="insert">添加</string>
    <string name="memberList">成员列表</string>
    <string name="insertMember">添加新成员</string>
    <string name="updateMember">修改成员</string>
    <string name="name">姓名:</string>
    <string name="phone">号码:</string>
    <string name="confirm">确定</string>
    <string name="cancel">取消</string>
    <string name="enterName">请输入姓名</string>
    <string name="enterPhone">请输入号码</string>

</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.ex08"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"
             android:label="@string/app_name1">

        </activity>
        <activity android:name=".ThirdActivity"
            android:label="@string/app_name2">

        </activity>
    </application>

</manifest>


标签: android

热门推荐