创建一个DataBaseHelper的类,这个类是继承SQLiteOpenHelper类的,这个类中包含创建数据库、打开数据库、创建表、添加数据和查询数据的方法。代码如下:

package com.example.message_board;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.R.bool;
import android.R.integer;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper

{
private static String DB_PATH= "";
private static String DB_NAME="Message.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context)
{
  super(context, DB_NAME, null, 1);
  this.myContext = context;
  Log.v("DB_PATH1",DB_PATH);
  DB_PATH=myContext.getDatabasePath(DB_NAME).getPath();
  Log.v("DB_PATH2",DB_PATH);
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException

{
  boolean dbExist = checkDataBase();
  if(dbExist)
  {
    //do nothing - database already exist
  }
  else
  {

    //By calling this method and empty database will be created into the default system path
    //of your application so we are gonna be able to overwrite that database with our database.
    this.getReadableDatabase();
    try
    {
      copyDataBase();
    }

     catch (IOException e)
    {
      throw new Error("Error copying database");
    }
  }
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase()
{
  SQLiteDatabase checkDB = null;
  try
  {
    String myPath = DB_PATH;
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  }
  catch(SQLiteException e)
  {
    //database does't exist yet.
  }
  if(checkDB != null)
  {
    checkDB.close();
  }
  return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException
{
  //Open your local db as the input stream
  InputStream myInput = myContext.getAssets().open(DB_NAME);
  // Path to the just created empty db
  String outFileName = DB_PATH;
  //Open the empty db as the output stream
  OutputStream myOutput = new FileOutputStream(outFileName);
  //transfer bytes from the inputfile to the outputfile
  byte[] buffer = new byte[1024];
  int length;
  while ((length = myInput.read(buffer))>0)
  {
    myOutput.write(buffer, 0, length);
  }
  //Close the streams
  myOutput.flush();
  myOutput.close();
  myInput.close();
}

public void openDataBase() throws SQLException
{
  //Open the database
  String myPath = DB_PATH ;
  Log.v("myPath",myPath);
  myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

//create a table
public void createTable() throws SQLException
{
  try
  {
    myDataBase.execSQL("CREATE TABLE MessageTable (_id INTEGER PRIMARY KEY AUTOINCREMENT,content TEXT);");
  }
  catch (Exception e)
  {
    // TODO: handle exception
  }
}

//insert the data to the database
public void insertrecord(String contentString) throws SQLException
{
  try
  {
    //String content=contentString;
    String sql="insert into MessageTable(content) values('"+contentString+"');";
    Log.v("aaa", sql);
    myDataBase.execSQL(sql);
    Log.v("aaa_a", sql);
  }
  catch (Exception e)
  {
    Log.v("aaa_e", e.toString());
  }
}

//select record
public List<String> selectrecord() throws SQLException
{
  List<String> list = new ArrayList<String>();
  //String[] strArr = new String[list.size()];
  //list.toArray(strArr);
  try
  {
    Cursor cr = myDataBase.rawQuery("select * from MessageTable", null);
    while(cr.moveToNext())
    {
      //Content+=cr.getString(1);
      Log.v("Record",cr.getString(1));
      list.add(cr.getString(1));
    }
  }
  catch (Exception e)
  {
    // TODO: handle exception
    Log.v("ERR", e.toString());
  }
  return list;
}

@Override
public synchronized void close()
{
if(myDataBase != null)
myDataBase.close();
super.close();
}

@Override
public void onCreate(SQLiteDatabase db)
{

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{

}

}

Android平台使用SQLite数据库存储数据的更多相关文章

  1. Android下用Sqlite数据库存储数据

    第一步:  写个类 ,继承 SQLiteOpenHelper public class MyDatabaseOpenHelper extends SQLiteOpenHelper { } 第二步:   ...

  2. Android中数据存储(三)——SQLite数据库存储数据

    当一个应用程序在Android中安装后,我们在使用应用的过程中会产生很多的数据,应用都有自己的数据,那么我们应该如何存储数据呢? 数据存储方式 Android 的数据存储有5种方式: 1. Share ...

  3. 使用嵌入式关系型SQLite数据库存储数据

    除了可以使用文件或SharedPreferences存储数据,还可以选择使用SQLite数据库存储数据. 在Android平台上,集成了一个嵌入式关系型数据库—SQLite, 1.SQLite3支持 ...

  4. 使用Sqlite数据库存储数据

    1.Sql基本命令 1.1.创建表 表是有行和列组成的,列称为字段,行称为记录. 使用CREATE命令来创建表: 1 CREATE TABLE tab_student (studentId INTEG ...

  5. Android Studio 查看SQLite数据库存储位置及文件

    前言: 之前开发的一个记账本APP,用的是SQLite数据库,会有一些网友问如何查看数据库,这篇博文对此进行一个说明. 操作: 1.通过DDMS(Dalvik Debug Monitor Servic ...

  6. QT 创建本地数据库(SQLite数据库)存储数据

    注意:QT自带SQLITE数据库,不需要再安装 1.创建一个包含创建.查询.修改和删除数据库的数据库类(DataBase) DataBase.h头文件 #pragma once #include &l ...

  7. Android学习笔记36:使用SQLite方式存储数据

    在Android中一共提供了5种数据存储方式,分别为: (1)Files:通过FileInputStream和FileOutputStream对文件进行操作.具体使用方法可以参阅博文<Andro ...

  8. <Android基础> (六) 数据存储 Part 3 SQLite数据库存储

    6.4 SQLite数据库存储 SQLite是一种轻量级的关系型数据库,运算速度快,占用资源少. 6.4.1 创建数据库 Android为了管理数据库,专门提供了SQLiteOpenHelper帮助类 ...

  9. Android学习之基础知识九 — 数据存储(持久化技术)之SQLite数据库存储

    前面一讲介绍了数据持久化技术的前两种:文件存储.SharedPreferences存储.下面介绍第三种技术:SQLite数据库存储 一.SQLite数据库存储 SQLite数据库是一款轻量级的关系型数 ...

随机推荐

  1. UI进阶 SQLite错误码

    #define SQLITE_OK 0 /* 成功 | Successful result */ /* 错误码开始 */ #define SQLITE_ERROR 1 /* SQL错误 或 丢失数据库 ...

  2. 用ConfigurationManager读取和修改配置文件

    为了方便有时我们会把一些简单的配置的信息放入web.config文件里. 放到appSettings添加key   value等信息. ConfigurationManager.AppSettings ...

  3. JHipster的安装

    JHipster GitHub地址:https://jhipster.github.io/ 刚开始接触JHipster,理解还不深,此次随笔只是把自己对JHipster的所学记录一下,也算是一种知识的 ...

  4. hdu3001 Travelling

    Travelling Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  5. java泛型的讲解

    java泛型 什么是泛型? 泛型(Generic type 或者 generics)是对 Java 语言的类型系统的一种扩展,以支持创建可以按类型进行参数化的类.可以把类型参数看作是使用参数化类型时指 ...

  6. 为什么监听不到开机广播action.BOOT_COMPLETED

    为什么监听不到开机广播action.BOOT_COMPLETED 1. 说明 Android手机开机后,会发送android.intent.action.BOOT_COMPLETED广播,监听这个广播 ...

  7. Codeforces Round #333 (Div. 2) C. The Two Routes flyod

    C. The Two Routes Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/602/pro ...

  8. Codeforces Gym 100286G Giant Screen 水题

    Problem G.Giant ScreenTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/con ...

  9. XML Helper XML操作类

    写的一个XML操作类,包括读取/插入/修改/删除. using System;using System.Data;using System.Configuration;using System.Web ...

  10. [Jest] Track project code coverage with Jest

    Jest comes pre-packaged with the ability to track code coverage for the modules you're testing, but ...