yuanopen

----------------------------------

Android中SQLite的使用(简单数据存入与读取)
一,概要

先看demo,最后又讲解。

二,小demo
     效果图:

          

     实现:

               视图层:

        testsqlite.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_w"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="155dp"
        android:text="写入" />

    <Button
        android:id="@+id/btn_r"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/btn_w"
        android:layout_centerVertical="true"
        android:text="查询" />

</RelativeLayout>

write.xml:

        

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

    <EditText
        android:id="@+id/et_name"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="100dp"
        android:hint="姓名"
        android:inputType="textPersonName" />

<RadioGroup
    android:layout_marginTop="30dp"
    android:id="@+id/check_group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal"
    >

    <RadioButton
        android:id="@+id/rb_male"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男"
      />

    <RadioButton
        android:id="@+id/rd_female"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女"
    />
</RadioGroup>

    <Button
        android:id="@+id/btn_write"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:text="写入数据库"
        />
</LinearLayout>
read.xml:

<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
        <TextView
            android:id="@+id/tv_id"
            android:textAlignment="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="id"
            android:layout_weight="1"/>
        <TextView
            android:text="姓名"
            android:textAlignment="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <TextView
            android:textAlignment="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="性别"
            android:layout_weight="1"/>

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

    </ListView>

</LinearLayout>


item_sql.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">
    <TextView
        android:id="@+id/tv_id"
        android:textAlignment="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_name"
        android:textAlignment="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_sex"
        android:textAlignment="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
</LinearLayout>

    逻辑层:

        TestSQLite.java:

package com.maeeage.administrator.androidlearn;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;

import com.maeeage.administrator.androidlearn.testSql.AtyRead;
import com.maeeage.administrator.androidlearn.testSql.AtyWrite;

/**
 * Created by Administrator on 2018/2/2/002.
 */

public class TestSQlite extends Activity {
    Button btn_w,btn_r;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testsqlite);
        findById();
        inti();

    }

    private void inti() {

        btn_w.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                write();
            }
        });

        btn_r.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                read();
            }
        });
    }

    private void findById() {
        btn_r=(Button)findViewById(R.id.btn_r);
        btn_w=(Button)findViewById(R.id.btn_w);
    }

    //bnt_w的onclick
    void write(){
        Intent intent=new Intent(TestSQlite.this, AtyWrite.class);
        startActivity(intent);
    }
    //btn_r的哦click
    void read(){
        Intent intent=new Intent(TestSQlite.this, AtyRead.class);
        startActivity(intent);
    }

}
        AtyWrite.java:

package com.maeeage.administrator.androidlearn.testSql;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.maeeage.administrator.androidlearn.R;

/**
 * Created by Administrator on 2018/2/2/002.
 */

public class AtyWrite extends Activity {
    EditText username;
    RadioButton male,female;
    Button btn_write;

    RadioGroup radioGroup;
    SQLiteDatabase db;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write);
        findById();
        init();
    }

    private void init() {
        //每个程序都要自己数据库,默认情况下各自互不干扰
        //创建一个数据库,并且打开;
        //通过下面这个方法,创建,如果存在就打开,不存在就创建并打开
        db=  openOrCreateDatabase("user.db",MODE_PRIVATE,null);
        db.execSQL("create table if not exists tb_user(_id integer primary key autoincrement,name text not null,sex text not null)");
        btn_write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toSql();
            }
        });
    }

    private void findById() {
        username=(EditText)findViewById(R.id.et_name);
        male=(RadioButton)findViewById(R.id.rb_male);
        female=(RadioButton)findViewById(R.id.rd_female);
        btn_write=(Button)findViewById(R.id.btn_write);
        radioGroup=(RadioGroup)findViewById(R.id.check_group);
    }

    //btn_write的onclick事件
   void  toSql(){

       String name=username.getText().toString();
       String sex;
       if(male.isChecked())
        sex="男";
       else
           sex="女";
       Toast.makeText(AtyWrite.this,name+"  "+sex,Toast.LENGTH_SHORT);
       String sql="insert into tb_user(name,sex) values('"+name+"','"+sex+"')";
       Toast.makeText(AtyWrite.this,name+"  "+sex,Toast.LENGTH_SHORT).show();
       db.execSQL(sql);

    }
}

AtyRead.java:

package com.maeeage.administrator.androidlearn.testSql;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.maeeage.administrator.androidlearn.R;

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

/**
 * Created by Administrator on 2018/2/2/002.
 */

public class AtyRead extends Activity {

    ListView listView;
    SimpleAdapter adapter;
    List<Map<String,String>> list;
    SQLiteDatabase db;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read);
        inti();

    }

    private void inti() {

        //每个程序都要自己数据库,默认情况下各自互不干扰
        //创建一个数据库,并且打开;
        //通过下面这个方法,创建,如果存在就打开,不存在就创建并打开
        db=  openOrCreateDatabase("user.db",MODE_PRIVATE,null);
        list=new ArrayList<Map<String, String>>();
        //初始化
        listView=(ListView)findViewById(R.id.read_listview);
        adapter=new SimpleAdapter(this,getData(),R.layout.item_sql,new String[]{"id","name","sex"},new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_sex});
        listView.setAdapter(adapter);
    }

    public List<Map<String,String>> getData() {
        if (isTableExist("tb_user")) {
            Cursor c = db.rawQuery("select * from tb_user", null);
            if (c != null) {
                while (c.moveToNext()) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", c.getString(0));
                    map.put("name", c.getString(1));
                    map.put("sex", c.getString(c.getColumnIndex("sex")));
                    list.add(map);

                }
                c.close();
                db.close();
                return list;
            } else {
                c.close();
                db.close();
            }
        }
        return list;
    }
//判断table是否存在
    public boolean isTableExist(String table) {

        Cursor c = db.rawQuery("select count(*) from sqlite_master where type='table' and name='"+table+"'", null);
        if (c != null) {
            while (c.moveToNext()) {
                int count = c.getInt(0);
                if (count > 0) {
                    c.close();
                    return true;
                }
            }
        }else{
                c.close();
        }
        return false;
    }
}


总结:

SQLite的讲解,用真机运行程序,想查看数据库文件,这是教程







阅读更多
版权声明: https://blog.csdn.net/qq_37664986/article/details/79249240
文章标签: Android SQLite 数据库
个人分类: Android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Android中SQLite的使用(简单数据存入与读取)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭