Android编程之Sqlite数据库的建立与使用

主Activity:


package edu.hrbeu.SimplePreferenceDemo;



import edu.hrbue.SimplePreferenceDemo.R;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class SimplePreferenceDemoActivity extends Activity {


private EditText nameText;
private EditText classText;
private EditText numText;
private Button btnSTF;
private Button btnRF;
private Button btnSaveToSQL;
private Button btnshowAll;
private Button btnClear;
private Button btnDelAll;
private Button btnSearch;
private Button btnUpdate;
private Button btnDelete;

private TextView display;
private TextView idInput;
private DBAdapter adapter;


public static final String PREFERENCE_NAME = "SaveToFile";
protected static final String FileName = "fileDemo.txt";
@SuppressWarnings("deprecation")
public static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        nameText = (EditText)findViewById(R.id.name);
        classText = (EditText)findViewById(R.id.Class);
        numText = (EditText)findViewById(R.id.num);


        btnSTF = (Button)findViewById(R.id.btnSaveToFile);
        btnRF = (Button)findViewById(R.id.btnReadFile);
        btnSaveToSQL = (Button)findViewById(R.id.btnSaveToSQL);
        btnshowAll = (Button)findViewById(R.id.btnReadDB);
        btnClear = (Button)findViewById(R.id.btnClear);
        btnDelAll = (Button)findViewById(R.id.btnDelAll);
        btnSearch = (Button)findViewById(R.id.btnSearch);
        btnUpdate = (Button)findViewById(R.id.btnUpdate);
        btnDelete = (Button)findViewById(R.id.btnDel);
        
        display = (TextView)findViewById(R.id.display);
        idInput = (TextView)findViewById(R.id.idInput);
        
        adapter = new DBAdapter(this);
        adapter.open();


        //存储到本地文件
        OnClickListener btnSTFlistener = new OnClickListener(){
        public void onClick(View view){
        FileOutputStream fos = null;
        try{
        fos = openFileOutput(FileName,Context.MODE_APPEND);
        String text = "\n姓名:"+nameText.getText().toString()+"\n"+"班级:"+classText.getText().toString()+"\n"+"学号:"+numText.getText().toString();
        fos.write(text.getBytes());
        Toast.makeText(SimplePreferenceDemoActivity.this, "保存成功!", Toast.LENGTH_LONG).show();


        }catch(FileNotFoundException e){
        e.printStackTrace();
        } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        finally{
        if(fos!=null){
        try{
        fos.flush();
        fos.close();
        }catch(IOException e){
        e.printStackTrace();
        }
        }
        }


        }


        };
        btnSTF.setOnClickListener(btnSTFlistener);
        //读取文件
        OnClickListener btnRFlistener = new OnClickListener(){
        @Override
public void onClick(View v) {
// TODO Auto-generated method stub
        display.setText("");
        FileInputStream fis = null;
        try {
fis = openFileInput(FileName);
if(fis.available()==0) return;//available()函数返回字节流的长度
byte[] readBytes = new byte[fis.available()];
while(fis.read(readBytes)!=-1){
String Text = new String(readBytes);
display.setText(Text);
Toast.makeText(SimplePreferenceDemoActivity.this, "文件读取成功!", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


        };
        btnRF.setOnClickListener(btnRFlistener);
        //存储到数据库
        OnClickListener btnSTSlistener = new OnClickListener(){


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Student stu = new Student();
stu.name = nameText.getText().toString();
stu.Class = classText.getText().toString();
stu.num = numText.getText().toString();
long column = adapter.insert(stu);
if(column==-1){
Toast.makeText(SimplePreferenceDemoActivity.this, "存入数据库出错!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(SimplePreferenceDemoActivity.this, "存储成功!!", Toast.LENGTH_LONG).show();
}

}
        
        };
        btnSaveToSQL.setOnClickListener(btnSTSlistener);
        //全部显示
        OnClickListener showAllListener = new OnClickListener(){


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Student[] stu = adapter.queryAll();
if(stu == null){
Toast.makeText(SimplePreferenceDemoActivity.this, "数据库中没有数据!", Toast.LENGTH_LONG).show();
}else{
String msg = "";
for(int i=0;i<stu.length;i++){
msg += stu[i].toString();
}
display.setText(msg);
}
}
       
        };
        btnshowAll.setOnClickListener(showAllListener);
        //清除显示
        OnClickListener clearListener = new OnClickListener(){


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
display.setText("");
}
       
        };
        btnClear.setOnClickListener(clearListener);
        //全部删除
        OnClickListener delAllListener = new OnClickListener(){


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.deleteALL();
Toast.makeText(SimplePreferenceDemoActivity.this, "删除成功!", Toast.LENGTH_LONG).show();
Builder ad = new AlertDialog.Builder(SimplePreferenceDemoActivity.this).setTitle("提示").setMessage("是否删除本地文件中的数据?");
 
ad.setPositiveButton("确定", new DialogInterface.OnClickListener() {

@SuppressLint("SdCardPath")
@Override
public void onClick(DialogInterface dialog, int which) {
String path = "/data/data/edu.hrbue.SimplePreferenceDemo/files/fileDemo.txt";
File file = new File(path);
file.delete();
}
});
ad.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
ad.create();
ad.show();
}        
        };
        btnDelAll.setOnClickListener(delAllListener); 
        //ID查询
        OnClickListener btnSearchListener = new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(idInput.getText().toString()==""){
Toast.makeText(SimplePreferenceDemoActivity.this, "请输入需要查询的ID!", Toast.LENGTH_LONG).show();
}else{
int id = Integer.parseInt(idInput.getText().toString());
Student[] stu = adapter.queryOneData(id);
if(stu==null){Toast.makeText(SimplePreferenceDemoActivity.this, "数据库中没有该项!", Toast.LENGTH_LONG).show();}
else{
display.setText(stu[0].toString());
}
}

}      
        };
        btnSearch.setOnClickListener(btnSearchListener);
        //ID更新
        OnClickListener btnUpdateListener = new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = Integer.parseInt(idInput.getText().toString());
Student[] stu = adapter.queryOneData(id);
/*nameText.setText(""); //先置为空
classText.setText("");
numText.setText("");*/
stu[0].name = nameText.getText().toString();
stu[0].Class = classText.getText().toString();
stu[0].num = numText.getText().toString();
long ifsuccess = adapter.updateOneData(id, stu[0]);
if(ifsuccess==-1){
Toast.makeText(SimplePreferenceDemoActivity.this, "更新失败!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(SimplePreferenceDemoActivity.this, "更新成功!", Toast.LENGTH_LONG).show();
}
}      
        };
        btnUpdate.setOnClickListener(btnUpdateListener);
        //ID删除
        OnClickListener btnDelListener = new OnClickListener(){


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = Integer.parseInt(idInput.getText().toString());
long ifsuccess = adapter.deleteOneData(id);
if(ifsuccess==-1){Toast.makeText(SimplePreferenceDemoActivity.this, "删除失败!", Toast.LENGTH_LONG).show();}
else{Toast.makeText(SimplePreferenceDemoActivity.this, "删除成功!", Toast.LENGTH_LONG).show();}
}
       
        };
        btnDelete.setOnClickListener(btnDelListener);
    }
    @Override
    public void onStart(){
    super.onStart();
    loadSharedPreferences();
    }


    @Override
    public void onStop(){
    super.onStop();
    saveSharedPreferences();
    }


    private void loadSharedPreferences(){
     SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE);
     String name = sharedPreferences.getString("Name","zzg");
     String Class = sharedPreferences.getString("Class", "软件152");
     String num = sharedPreferences.getString("Num","2015012919");


     nameText.setText(name);
     classText.setText(Class);
     numText.setText(num);
    }


    private void saveSharedPreferences(){
     SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE);
     SharedPreferences.Editor editor = sharedPreferences.edit();


     editor.putString("Name", nameText.getText().toString());
     editor.putString("Class", classText.getText().toString());
     editor.putString("Num", numText.getText().toString());
     editor.commit();
    }

}


数据库适配器:

package edu.hrbeu.SimplePreferenceDemo;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


public class DBAdapter {
private static final String DB_NAME = "student.db";
private static final String DB_TABEL = "studentInfo";
private static final int DB_VERTION = 1;

public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_CLASS = "Class";
public static final String KEY_NUM = "num";

private SQLiteDatabase db;
private final Context context;
private DBOpenHelper dbOpenHelper;

/** 静态Helper类,用于建立、更新和打开数据库*/
private static class DBOpenHelper extends SQLiteOpenHelper{


public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub

}
private static final String DB_CREATE = "create table "+DB_TABEL+"("+KEY_ID+" integer primary key autoincrement, "+KEY_NAME+" text not null, "+KEY_CLASS+" text not null, "+KEY_NUM+" text not null);";
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB_CREATE);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+DB_TABEL);
onCreate(db); //只是删除表,并没有复制数据
}};
public DBAdapter(Context _context){
context = _context;
}
public void close(){
if(db!=null){
db.close();
db=null;
}
}
public void open(){
dbOpenHelper = new DBOpenHelper(context,DB_NAME,null,DB_VERTION);
try{
db = dbOpenHelper.getWritableDatabase();
}catch(SQLiteException e){
db = dbOpenHelper.getReadableDatabase();
}
}
public long insert(Student student){ //增
ContentValues newValue = new ContentValues();
newValue.put(KEY_NAME,student.name);
newValue.put(KEY_CLASS,student.Class);
newValue.put(KEY_NUM,student.num);
return db.insert(DB_TABEL, null, newValue);
}
public long deleteOneData(long id){ //删
return db.delete(DB_TABEL,KEY_ID+"="+id ,null);
}
public long deleteALL(){
return db.delete(DB_TABEL,null,null);
}
public long updateOneData(long id,Student student){ //改
ContentValues updateValue = new ContentValues();
updateValue.put(KEY_NAME, student.name);
updateValue.put(KEY_CLASS, student.Class);
updateValue.put(KEY_NUM,student.num);
return db.update(DB_TABEL, updateValue, KEY_ID+"="+id, null);
}
private Student[] ConvertToStudent(Cursor results) {
// TODO Auto-generated method stub
int resultCounts = results.getCount();
if(resultCounts==0||!results.moveToFirst()){return null;}
Student[] students = new Student[resultCounts];
for(int i=0;i<resultCounts;i++){
students[i] = new Student();
students[i].ID = results.getInt(0);
students[i].name = results.getString(results.getColumnIndex(KEY_NAME));
students[i].Class = results.getString(results.getColumnIndex(KEY_CLASS));
students[i].num = results.getString(results.getColumnIndex(KEY_NUM));
results.moveToNext();
}
return students;
}
public Student[] queryOneData(long id){ //查
Cursor results = db.query(DB_TABEL,new String[]{KEY_ID,KEY_NAME,KEY_CLASS,KEY_NUM},KEY_ID+"="+id,null,null,null,null);//7个参数
return ConvertToStudent(results);
}
public Student[] queryAll(){
Cursor results = db.query(DB_TABEL,new String[]{KEY_ID,KEY_NAME,KEY_CLASS,KEY_NUM},null,null,null,null,null);
return ConvertToStudent(results);
}

}

Student类:


package edu.hrbeu.SimplePreferenceDemo;


public class Student {
public int ID=-1;
public String name;
public String Class;
public String num;

@Override
public String toString(){
String result="";
result += "ID:"+this.ID+"\n";
result += "Ãû×Ö:"+this.name+"\n";
result += "°à¼¶:"+this.Class+"\n";
result += "ѧºÅ:"+this.num+"\n";
return result;
}

}

Layout:

<?xml version="1.0" encoding="UTF-8"?>


-<RelativeLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/RelativeLayout01" xmlns:android="http://schemas.android.com/apk/res/android">


<EditText android:layout_height="wrap_content" android:layout_width="280dip" android:id="@+id/name" android:text="" android:layout_marginLeft="10dip" android:layout_alignParentRight="true"> </EditText>


<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/name_label" android:text="姓名:" android:layout_toRightOf="@id/name" android:layout_alignParentLeft="true" android:layout_alignBaseline="@+id/name"> </TextView>


<EditText android:layout_height="wrap_content" android:layout_width="280dip" android:id="@+id/Class" android:text="" android:layout_marginLeft="10dip" android:layout_alignParentRight="true" android:layout_below="@id/name"> </EditText>


<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/class_label" android:text="班级:" android:layout_toRightOf="@id/Class" android:layout_alignParentLeft="true" android:layout_alignBaseline="@+id/Class"> </TextView>


<EditText android:layout_height="wrap_content" android:layout_width="280dip" android:id="@+id/num" android:layout_marginLeft="10dip" android:layout_alignParentRight="true" android:layout_below="@id/Class"> </EditText>


<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/num_label" android:text="学号:" android:layout_toRightOf="@id/num" android:layout_alignParentLeft="true" android:layout_alignBaseline="@+id/num"> </TextView>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnSaveToSQL" android:text="存储至数据库" android:layout_alignParentLeft="true" android:layout_below="@+id/btnSaveToFile" android:layout_toLeftOf="@+id/btnClear"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnSaveToFile" android:text="存储至文件" android:layout_alignParentLeft="true" android:layout_below="@+id/num" android:layout_toLeftOf="@+id/btnReadFile"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnUpdate" android:text="ID更新" android:layout_alignParentLeft="true" android:layout_below="@+id/btnSearch"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnDel" android:text="ID删除" android:layout_alignParentLeft="true" android:layout_below="@+id/btnUpdate"/>


<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/textView2" android:text="结果显示:" android:layout_below="@+id/btnDel" android:layout_alignRight="@+id/btnDel" android:layout_alignParentBottom="true"/>




-<ScrollView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/scrollView1" android:layout_toRightOf="@+id/btnSearch" android:layout_alignRight="@+id/btnDelAll" android:layout_alignParentBottom="true" android:layout_alignTop="@+id/btnSearch">




-<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical">


<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/display" android:text=""/>


</LinearLayout>


</ScrollView>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnSearch" android:text="ID查询" android:layout_alignParentLeft="true" android:layout_below="@+id/btnSaveToSQL" android:layout_marginTop="26dp"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnClear" android:text="清除显示" android:layout_below="@+id/btnReadDB" android:layout_toLeftOf="@+id/btnDelAll" android:layout_alignBottom="@+id/btnSaveToSQL"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnReadFile" android:text="读取文件" android:layout_toLeftOf="@+id/btnReadDB" android:layout_above="@+id/btnSaveToSQL"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnReadDB" android:text="全部显示" android:layout_alignParentRight="true" android:layout_above="@+id/btnSaveToSQL"/>


<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btnDelAll" android:text="全部删除" android:layout_alignParentRight="true" android:layout_below="@+id/btnReadDB" android:layout_alignBottom="@+id/btnClear"/>


<EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/idInput" android:layout_above="@+id/scrollView1" android:ems="10" android:layout_alignLeft="@+id/scrollView1"/>


<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/textView1" android:text="ID号:" android:layout_marginLeft="14dp" android:layout_alignLeft="@+id/textView2" android:layout_centerVertical="true"/>


</RelativeLayout>

猜你喜欢

转载自blog.csdn.net/did_you/article/details/78453409