创建一个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. 【Java】C/C++与Java的简单比较

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5827273.html     C/C++:            编译(不同的系统编译出不同的机器码,所以同一 ...

  2. Usage of readonly and const

    Many new learners can not make sure the usage scenarios of readonly and const keywords. In my opinio ...

  3. 简单的玩玩etimer <contiki学习笔记之九>

    好吧,我承认etimer有点小复杂,主要是它似乎和contiki的process搅在一起,到处都在call_process.那就先搜搜contiki下的etimer的example看看,然后再试着写一 ...

  4. Spring连接数据库的几种常用的方式

    本文简单的讲解使用Spring连接数据库的几种常用方法: 测试主类为: package myspring2; import java.sql.*; import javax.sql.DataSourc ...

  5. Codeforces Beta Round #85 (Div. 1 Only) B. Petya and Divisors 暴力

    B. Petya and Divisors Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/111 ...

  6. Codeforces Round #172 (Div. 2) C. Rectangle Puzzle 数学题几何

    C. Rectangle Puzzle Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/281/p ...

  7. Codeforces Round #Pi (Div. 2) D. One-Dimensional Battle Ships set区间分解

    D. One-Dimensional Battle ShipsTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/co ...

  8. Codeforces GYM 100114 D. Selection 线段树维护DP

    D. Selection Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/100114 Descriptio ...

  9. hihocoder #1223 : 不等式 水题

    #1223 : 不等式 Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://hihocoder.com/problemset/problem/1223 ...

  10. C# 循环获取目录

    #region 获取目录 /// <summary> /// 获取指定文件夹下所有子目录及文件 /// </summary> /// <param name=" ...