创建一个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. Castle IOC容器快速入门

    主要内容 1.为什么要IOC 2.什么是Castle IOC容器 3.快速入门示例 4.几个重要的概念 一,为什么要IOC IOC(控制反转或者叫依赖注入)Martin Fowler大师在他的文章中已 ...

  2. django控制admin的model显示列表

    class goods(models.Model):    name = models.CharField(max_length=300)    price = models.IntegerField ...

  3. C#中反射的使用(How to use reflect in CSharp)(2)

    在上一篇里,我们叨逼了好多如何获取到程序集里的对象,但是对象有了,还不知道怎么调,OK,下面开始干这个对象: 首先,我们对上一篇的对象做了一些修改,以适应多种情况: using System; usi ...

  4. sgu - 269 - Rooks

    题意:给出一个n行的棋盘,每行的长度任意,问在该棋盘中放k个车(不能同行或者同列)有多少种放法(n <= 250, 每行的长度 <= 250). 题目链接:http://acm.sgu.r ...

  5. codeforces Gym 100500C C. ICPC Giveaways 排序

    Problem C. ICPC GiveawaysTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/1005 ...

  6. angularjs入门学习【应用剖析中篇】

    在上一节讲完了关于应用开发中如数据绑定,加入样式一类的基础操作后,接下来,将在应用中,与控制其有关的一些事件... 一.UI和控制器的分离 我们须要明白控制器在应用中的三个作用: [1]在应用模型中设 ...

  7. [转载]Android开发常用调试技术记录

    ANDROID 调试技术: 1)Ps 指令 ls –l /proc/27/ cat /proc/27/cmdline       #cmdline文件表示了这个进程所在的命令行. cat /proc/ ...

  8. NSRange类详解

    NSRange的定义 { NSUInteger location; NSUInteger length; } NSRange; NSRange是一个结构体,其中location是一个以0为开始的ind ...

  9. Python的基础--对象 转

      对象(Objects)是python中数据的抽象,python中所有的数据均可以用对象或者是对象之间的关系来表示.每个对象均有标识符(identity).类型(type).值(value). 标识 ...

  10. divide-conquer-combine(4.1 from the introduction to algorithm)

    this example is from chapter 4 in <the introduction to algorithm> the main idea is all showed ...