SQLite

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLite相关的知识,希望对你有一定的参考价值。

主界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cn.edu.niit.sqlite.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/add"
            android:text="增加新纪录"/>
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/del"
            android:text="删除一条记录"/>
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lv"></ListView>

</LinearLayout>

 新建一个item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

</LinearLayout>

  封装相关信息

package cn.edu.niit.sqlite;

import java.io.Serializable;

/**
 * Created by 10403 on 2017/5/16.
 */

public class Person implements Serializable {
    private int _id;
    private String name;


    public  Person() {
    }
    public Person(String name){
        this.name=name;
    }
    public int get_id() {
        return _id;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

  创建数据库

package cn.edu.niit.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by 10403 on 2017/5/16.
 */

public class MyDBHelper extends SQLiteOpenHelper {
    //person表的创建语句,字段包括:自增关键字id、姓名name
    private String sql = "create table person(_id integer primary key autoincrement, " +
            "name text not null)";

    public MyDBHelper(Context context) {
        super(context, "personInfo", null, 1);
    }

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists person");
        onCreate(db);
    }
}

  加载listview

package cn.edu.niit.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * Created by 10403 on 2017/5/16.
 */

public class MyCursorAdapter extends CursorAdapter {
    public MyCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }
    // 加载listView的item的布局
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return LayoutInflater.from(context).inflate(R.layout.item,viewGroup,false);
    }
    //给item的每个主键赋值
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView name=(TextView)view.findViewById(R.id.name);

        name.setText(cursor.getString(cursor.getColumnIndex("name")));

    }
}

  插入数据

package cn.edu.niit.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by 10403 on 2017/5/16.
 */

public class PersonDAO {
    private Context context;//Activity上下文
    private MyDBHelper helper;//创建、升级、打开数据库
    private SQLiteDatabase db;//对表进行CRUD

    public PersonDAO(Context context) {
        helper = new MyDBHelper(context);
    }

    public void insert(Person person){
        //1. 打开数据库
        db = helper.getWritableDatabase();
        // 2. 生成数据集合
        String sql = "insert into person(name) values(?)";
        db.execSQL(sql,new Object[]{person.getName()});

    }


    public Cursor selectAll() {
        db = helper.getReadableDatabase();
        Cursor cursor = db.query("person",null,null,null,null,null,null);
        return cursor;
    }
    public void delete(int id){
        db = helper.getWritableDatabase();
        db.delete("person", "_id=?", new String[] {String.valueOf(id)});

        String sql = "delete from person where _id=?";
        db.execSQL(sql, new Object[]{id});

    }
}

  MainActivity

package cn.edu.niit.sqlite;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText writer;
    private ListView personList;
    private Button btnadd;
    private Button btndel;
    private PersonDAO personDAO;
    private MyCursorAdapter adapter;
    private Person person;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        personList=(ListView)findViewById(R.id.lv);
        btnadd=(Button)findViewById(R.id.add);
        btnadd.setOnClickListener(this);
        btndel=(Button)findViewById(R.id.del);
        btndel.setOnClickListener(this);
        writer=(EditText)findViewById(R.id.et) ;

        //创建adapter
        personDAO=new PersonDAO(this);
        Cursor cursor=personDAO.selectAll();
        if (cursor!=null){
            adapter=new MyCursorAdapter(this,cursor);
            personList.setAdapter(adapter);
        }
        //ListView的item点击事件
        personList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Cursor cursor = (Cursor) adapterView.getItemAtPosition(i);
                if(cursor != null) {
                    cursor.moveToPosition(i);
                    person=new Person();
                    person.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
                    person.setName(cursor.getString(cursor.getColumnIndex("name")));

        }
    }
});
    }
        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.add:
                    String name = writer.getText().toString();
                    if (TextUtils.isEmpty(name)) {
                        Toast.makeText(this, "姓名不能为空", Toast.LENGTH_LONG).show();
                        return;
                    }else {
                        personDAO = new PersonDAO(this);
                        person = new Person(name);
                        personDAO.insert(person);
                        cursor=personDAO.selectAll();
                        adapter.changeCursor(cursor);
                        personList.setAdapter(adapter);
                        Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.del:
                    if(person != null){
                        personDAO.delete(person.get_id());
                        personDAO=new PersonDAO(this);
                        cursor = personDAO.selectAll();
                        adapter = new MyCursorAdapter(this, cursor);
                        adapter.changeCursor(cursor);
                        personList.setAdapter(adapter);
                        Toast.makeText(this,"删除成功",Toast.LENGTH_LONG).show();
                    }
            }
        }

  技术分享

技术分享

 

以上是关于SQLite的主要内容,如果未能解决你的问题,请参考以下文章

java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.database.sqlite异常(代码片段

SQLite 片段函数实现不会在 TextView 中将文本格式化为 HTML

当我从用户获取数据并将其保存到 SQLite 数据库中时,我应该怎么做才能使列表视图在片段中工作

Android 逆向使用 DB Browser 查看并修改 SQLite 数据库 ( 从 Android 应用数据目录中拷贝数据库文件 | 使用 DB Browser 工具查看数据块文件 )(代码片段

Android 逆向使用 DB Browser 查看并修改 SQLite 数据库 ( 从 Android 应用数据目录中拷贝数据库文件 | 使用 DB Browser 工具查看数据块文件 )(代码片段

如果我想从另一个片段中添加书签,为啥我的书签单词没有保存到 sqlite 数据库?