Android Studio 从外部导入数据库并显示到页面中

Android Studio 从外部导入数据库并显示到页面中,第1张

概述文章目录AndroidStudio从外部导入数据库显示到页面中1.从外部导入数据库2.显示数据库内容3.踩坑记录AndroidStudio从外部导入数据库并显示到页面中最近在开发一个单词学习的App,准备好单词的外部数据库之后突然卡在了将数据库导入项目这一步,参考了很多网上的

文章目录Android Studio从外部导入数据库并显示到页面中1. 从外部导入数据库2. 显示数据库内容3. 踩坑记录

AndroID Studio从外部导入数据库并显示到页面中

最近在开发一个单词学习的App, 准备好单词的外部数据库之后突然卡在了将数据库导入项目这一步,参考了很多网上的资料,自己动手尝试了一遍,最后成功了。在这里将我的 *** 作过程记录一下。

1. 从外部导入数据库

首先,要导入的数据库及其内容是这样的(使用的数据库工具是sqlite Expert Professional 4.2):


该数据库存储在文件1.db中。

打开AndroID Studio,在要导入的项目中,切换至Project视图,新建一个和Java、res同级的目录assets(这个目录的位置与开发环境有关,我看网上说使用Eclispe开发环境时它在res/下,但在AS中它必须与res目录同级),然后将1.db复制到assets目录下:


做到这里的时候,不知道大家有没有这样的疑问:为什么要将数据库文件放在assets下?

有个解释说,这个文件夹主要用于存放应用程序中使用的外部资源文件,然后程序可以通过 I/O 流(使用AssetManager)对目录中的文件进行读写,存放在此目录下的文件都会被打包到发布包中。

接着,实现类MyDBOpenHelper.java;

这个类就是实现从assets目录读取数据库文件然后写入SD卡中,如果在SD卡中存在,就打开数据库,不存在就从assets目录下复制过去。

import java.io.OutputStream;import java.io.fileOutputStream;import java.io.IOException;import java.io.inputStream;import androID.database.Cursor;import androID.util.Log;public class MyDBOpenHelper extends sqliteOpenHelper {    private static String PACKAGE_name = "com.example.wordsofmultilanguage"; //包名    private static String DB_PATH =  "/data" + Environment.getDataDirectory().getabsolutePath() + "/" + PACKAGE_name + "/databases/";    private static String DB_name = "1";    private sqliteDatabase db;    private final Context context;    public MyDBOpenHelper(Context context) {        super(context,  DB_name , null, 1);        this. context  = context;    }    public voID createDB() throws IOException {        this.getReadableDatabase();        try {            copyDB();        } catch (IOException e) {            throw new Error("Error copying database");        }    }    public voID copyDB() throws IOException{        try {            inputStream ip =  context.getAssets().open(DB_name+".db");            Log.i("input Stream....",ip+"");            String op=  DB_PATH  +  DB_name ;            OutputStream output = new fileOutputStream( op);            byte[] buffer = new byte[1024];            int length;            while ((length = ip.read(buffer))>0){                output.write(buffer, 0, length);                Log.i("Content.... ",length+"");            }            output.flush();            output.close();            ip.close();        }        catch (IOException e) {            Log.v("error", e.toString());        }    }    public voID openDB() throws sqlException {        String myPath = DB_PATH + DB_name;        db = sqliteDatabase.openDatabase(myPath, null, sqliteDatabase.OPEN_READWRITE);        Log.i("open DB......",db.toString());    }    @OverrIDe    public synchronized voID close() {        if(db != null)            db.close();        super.close();    }    @OverrIDe    public voID onCreate(sqliteDatabase db) {    }    @OverrIDe    public voID onUpgrade(sqliteDatabase db, int oldVersion, int newVersion) {    }}
2. 显示数据库内容

在页面上显示数据库内容(即英文单词和释义)时,用到了ListVIEw控件,新建一个 布局文件im.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"><ListVIEw    androID:ID="@+ID/word_info"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"/></linearLayout>

对ListVIEw的每一条item做布局item.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">    <TextVIEw        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:ID="@+ID/word"        androID:textSize="16dp"        />    <TextVIEw        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:ID="@+ID/mean1"        androID:textSize="16dp"        />    <TextVIEw        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:ID="@+ID/mean2"        androID:textSize="16dp"        />    <TextVIEw        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:ID="@+ID/mean3"        androID:textSize="16dp"        /></linearLayout>

完成第一步外部数据库的导入之后,定义一个类initdate.java用来实例化数据库:

public class initdate {    public String word;    public String meaning1;    public String meaning2;    public String meaning3;    public initdate(String word, String meaning1, String meaning2, String meaning3){        this.word = word;        this.meaning1 = meaning1;        this.meaning2 = meaning2;        this.meaning3 = meaning3;    }}

然后,实现类

package com.example.wordsofmultilanguage;import androID.content.Context;import androID.os.Bundle;import androIDx.appcompat.app.AppCompatActivity;import java.io.IOException;import androID.database.sqlException;import androID.database.sqlite.sqliteDatabase;import androID.database.sqlite.sqliteDatabase.CursorFactory;import java.io.fileNotFoundException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.SimpleTimeZone;import androID.database.Cursor;import androID.Widget.ListVIEw;import androID.Widget.SimpleAdapter;public class test extends AppCompatActivity {	//创建一个List对象来存储数据    List<initdate>List = new ArrayList<>();    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.im);        ListVIEw ListVIEw = (ListVIEw)this.findVIEwByID(R.ID.word_info);        MyDBOpenHelper db;        db = new MyDBOpenHelper(this);        try {            db.createDB();        } catch (IOException ioe) {            throw new Error("Database not created....");        }        try {            db.openDB();        } catch (sqlException sqle) {            throw sqle;        }                sqliteDatabase db1;        db1 = openorCreateDatabase("1", Context.MODE_PRIVATE, null);        Cursor c = db1.rawquery("SELECT * FROM words1", null);        c.movetoFirst();        //获取表数据        while (!c.isAfterLast()) {            List.add(new initdate(c.getString(c.getColumnIndex("word")),c.getString(c.getColumnIndex("meaning1")),                    c.getString(c.getColumnIndex("meaning2")),c.getString(c.getColumnIndex("meaning3"))));            c.movetoNext();        }				//将获取到的数据通过一个循环存放到map对象中        List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();        for(int i = 0; i < List.size(); i++){            HashMap<String, Object>item = new HashMap<String, Object>();            item.put("word", List.get(i).word);            item.put("meaning1", List.get(i).meaning1);            if(List.get(i).meaning2 != null){                item.put("meaning2", List.get(i).meaning2);            }            //item.put("meaning2", List.get(i).meaning2);            if(List.get(i).meaning3 != null){                item.put("meaning2", List.get(i).meaning3);            }            //item.put("meaning3", List.get(i).mmeaning3);            data.add(item);        }        //创建SimpleAdapter适配器将数据绑定到item显示控件上        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,                new String[]{"word", "meaning1", "meaning2", "meaning3"}, new int[]{R.ID.word, R.ID.mean1, R.ID.mean2, R.ID.mean3});        //实现列表的显示        ListVIEw.setAdapter(adapter);    }}

效果图:

3. 踩坑记录

在 *** 作过程中,导入数据库文件的时候曾经碰到以下问题:


我数据库使用的编码形式是UTF-8,这是我导入1.db文件后显示的内容,全是乱码,并且提示file was loaded in the wrong enCoding: 'UTF-8',我的解决办法是啥也不做,不用管,只要原先的数据库内容没问题,继续往下做就可以。原因好像是因为AS打不开这个类型的文件,要用专门的sqlite工具打开,如果尝试打开的话就会变成一堆乱码,而且从此以后不管删除、重新导入多少次AS都很”贴心“地给你显示成乱码。(小白第一次用 AS 开发项目,啥也不懂,被这玩意儿坑死了,想了各种办法,最后发现它根本不影响……)

总结

以上是内存溢出为你收集整理的Android Studio 从外部导入数据库并显示到页面中全部内容,希望文章能够帮你解决Android Studio 从外部导入数据库并显示到页面中所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1055437.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存