如何在Android中使用SQLite数据库来选择数据库中的数据? [英] how to select data from database using SQLite database in android?

查看:159
本文介绍了如何在Android中使用SQLite数据库来选择数据库中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新Android开发,并想选择数据和pre-填充使用.sq3文件从资产folder.But获取其路径异常的SQLite数据库。
所以我该怎么做?
这里是我的code。

 包com.wiztech.wahab;进口的java.io.File;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;进口android.content.ContentValues​​;
进口android.content.Context;
进口android.database.Cursor;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteException;
进口android.database.sqlite.SQLiteOpenHelper;公共类的DatabaseManager扩展SQLiteOpenHelper {//你的应用程序数据库的Andr​​oid的默认系统路径。
  私人静态字符串DB_PATH =/data/data/com.wiztech.wahab/databases/;
//私有静态字符串DB_NAME =BlueConnect.sq​​3;
 私人静态字符串DB_NAME =database.sq3;私人SQLiteDatabase MYDATABASE;
私人SQLiteDatabase MYDATA的;私人最终上下文myContext;公众的DatabaseManager(上下文的背景下){
    超级(上下文,DB_NAME,空,1);
    this.myContext =背景;
} / **
 *在系统上创建一个空数据库,并与自己的数据库重写它。
 * * /
公共无效的CreateDatabase()抛出IOException    布尔dbExist = checkDataBase();
    如果(dbExist){
        //什么也不做 - 已存在于数据库
    }其他{
        CopyFiles();
    }
}
私人无效CopyFiles()
{
    尝试
    {
       InputStream为= myContext.getAssets()开(DB_NAME)。
       文件OUTFILE =新的文件(DB_PATH,DB_NAME);
       outfile.getParentFile()mkdirs()。
       outfile.createNewFile();      如果(是== NULL)
      抛出新的RuntimeException(流为空);
      其他
      {
         FileOutputStream中出=新的FileOutputStream(OUTFILE);
      //的BufferedOutputStream出=新的BufferedOutputStream(新的FileOutputStream(OUTFILE));
          中byte buf [] =新的字节[128];
            做{
          INT numread = is.​​read(BUF);
                如果(numread&下; = 0)
                    打破;
          out.write(BUF,0,numread);
           }而(真);            is.close();
            out.close();
      }
       // AssetFileDescriptor AF = am.openFd(world_treasure_hunter_deluxe.apk);
    }
    赶上(IOException异常E)
    {
          抛出新的RuntimeException(E);
    }}/ **
 *检查是否已存在于数据库,以避免重新复制每次打开应用程序时的文件。
 *如果存在返回:真的,假的,如果它不
 * /
私人布尔checkDataBase(){    SQLiteDatabase CHECKDB = NULL;    尝试{
        字符串mypath中= DB_PATH + DB_NAME;
        CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);    }赶上(SQLiteException E){    }    如果(CHECKDB!= NULL){
        checkDB.close();
    }    返回CHECKDB!= NULL?真假;
}/ **
 *副本数据库从本地资产文件夹在刚才创建的空数据库
 *系统文件夹,从那里可以访问和处理。
 *这是通过转流的字节流进行。
 * * /
@燮pressWarnings(未使用)
私人无效copyDataBase()抛出IOException    //打开本地数据库的输入流
    InputStream的myInput = myContext.getAssets()开(DB_NAME)。    //路径刚刚创建的空分贝
    字符串outFileName = DB_PATH + DB_NAME;    //打开空分贝的输出流
    的OutputStream myOutput =新的FileOutputStream(outFileName);    //传递从inputfile中字节到OUTPUTFILE
    字节[]缓冲区=新的字节[1024];
    INT长;
    而((长度= myInput.read(缓冲液))大于0){
        myOutput.write(缓冲液,0,长度);
    }    //关闭流
    myOutput.flush();
    myOutput.close();
    myInput.close();}公共无效的openDatabase()抛出的SQLException {    //打开数据库
  字符串mypath中= DB_PATH + DB_NAME;  MYDATABASE = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);}@覆盖
公共同步无效的close(){        如果(MYDATABASE!= NULL)
            myDataBase.close();        super.close();}@覆盖
公共无效的onCreate(SQLiteDatabase DB){}@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){}
// ---检索记录---
公共光标selectQuery(查询字符串)抛出的SQLException
{
    字符串mypath中= DB_PATH + DB_NAME;
    // MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READWRITE);
    MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.CREATE_IF_NECESSARY);
    光标mCursor = myData.rawQuery(查询,NULL);
    mCursor.moveToFirst();
    myData.close();
    返回mCursor;
}
//////////对于插入和更新数据////////
公共无效INSERT_UPDATE(查询字符串)抛出的SQLException
{
    字符串mypath中= DB_PATH + DB_NAME;
    MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READWRITE);
    myData.execSQL(查询);
    myData.close();
}公共布尔UpdateVote_Individual(字符串的rowid,字符串值,字符串计数){
    字符串mypath中= DB_PATH + DB_NAME;
    MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READWRITE);      ContentValues​​ ARGS =新ContentValues​​();
      args.put(total_votes,计数);
      返回myData.update(启动子,指定参数时,
              promoter_id ='+ ROWID +',NULL)> 0;
  }
}
包com.wiztech.wahab;进口android.app.Activity;
进口android.content.Intent;
进口android.database.Cursor;
进口android.graphics.Color;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.TextView;公共类Criteria_Activity延伸活动{的DatabaseManager分贝;
光标CUR;公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的System.out.println(内Criteria_Activity达);
    的setContentView(R.layout.criteria);    DB =新的DatabaseManager(getBaseContext());
    CUR = db.selectQuery(从client_table1选择*;);    如果(cur.moveToFirst()){        做{            串年龄= cur.getString(1);
            字符串性别= cur.getString(2);
            串教授= cur.getString(3);
            串嗜好= cur.getString(4);
            串喜欢= cur.getString(5);
            串不喜欢= cur.getString(6);            TextView的AG =(的TextView)findViewById(R.id.age_value);
            如果(age.length()== 0 ||年龄==){
                年龄=未保存;
                ag.setTextSize(16);
                ag.setTextColor(Color.GRAY);
            }
            ag.setText(年龄);            TextView的GEND =(的TextView)findViewById(R.id.gender_value);
            如果(gender.length()== 0 ||性别==){
                性别=未保存;
                gend.setTextSize(16);
                gend.setTextColor(Color.GRAY);
            }
            gend.setText(性别);            TextView的PR =(的TextView)findViewById(R.id.prof_value);
            如果(prof.length()== 0 ||教授==){
                教授=未保存;
                pr.setTextSize(16);
                pr.setTextColor(Color.GRAY);
            }
            pr.setText(教授);            TextView的霍=(的TextView)findViewById(R.id.hobby_value);
            如果(hobby.length()== 0 ||爱好==){
                爱好=未保存;
                hobbie.setTextSize(16);
                hobbie.setTextColor(Color.GRAY);
            }
            hobbie.setText(爱好);            TextView的LYKES =(的TextView)findViewById(R.id.likes_value);
            如果(likes.length()== 0 ||喜欢==){
                喜欢=未保存;
                lykes.setTextSize(16);
                lykes.setTextColor(Color.GRAY);
            }
            lykes.setText(喜欢);            TextView的dislykes =(的TextView)findViewById(R.id.dislikes_value);
            如果(dislikes.length()== 0 ||不喜欢==){
                踩=未保存;
                dislykes.setTextSize(16);
                dislykes.setTextColor(Color.GRAY);
            }
            dislykes.setText(不喜欢);        }而(cur.moveToNext());
        cur.close();
    } // end如果(cur.moveToFirst ..........    按钮criteria_edit_btn =(按钮)findViewById(R.id.cr_edit_btn);    criteria_edit_btn.setOnClickListener(新OnClickListener(){
        公共无效的onClick(视图v){
            // TODO自动生成方法存根
            意图update_criteria_intent =新意图(的getParent(),Edit_Criteria_Activity.class);
            TabGroupActivity parentActivity =(TabGroupActivity)的getParent();
            parentActivity.startChildActivity(Edit_Criteria_Activity,update_criteria_intent);
        }
    });} //结束的onCreate } //结束this.Activity


解决方案

好了,刚读什么在日志中。您在 client_table1 做一个选择,但表不存在。你首先要创建表。

请阅读这个教程如何使用SQLiteOpenHelper类使用在Android源码:

http://www.vogella.de/articles/AndroidSQLite/article.html

I am new to Android development and would like to select data and pre-populate a SQLite database using .sq3 files from the Assets folder.But getting exception on its path. So,what should i do? here is my code.

package com.wiztech.wahab;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
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;

public class DataBaseManager extends SQLiteOpenHelper{

//The Android's default system path of your application database.
  private static String DB_PATH = "/data/data/com.wiztech.wahab/databases/";


// private static String DB_NAME = "BlueConnect.sq3";
 private static String DB_NAME = "database.sq3";



private SQLiteDatabase myDataBase; 
private SQLiteDatabase myData; 

private final Context myContext;

public DataBaseManager(Context context) {
    super(context, DB_NAME, null, 1);
    this.myContext = context;
}

 /**
 * 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{  
        CopyFiles();
    }
}


private void CopyFiles()
{
    try
    { 
       InputStream is = myContext.getAssets().open(DB_NAME); 
       File outfile = new File(DB_PATH,DB_NAME);
       outfile.getParentFile().mkdirs();
       outfile.createNewFile();

      if (is == null)
      throw new RuntimeException("stream is null");
      else
      {
         FileOutputStream out = new FileOutputStream(outfile);      
      // BufferedOutputStream out = new BufferedOutputStream( new       FileOutputStream(outfile));
          byte buf[] = new byte[128];
            do {
          int numread = is.read(buf);
                if (numread <= 0)
                    break;
          out.write(buf, 0, numread);
           } while (true);

            is.close();
            out.close();
      }
       //AssetFileDescriptor af = am.openFd("world_treasure_hunter_deluxe.apk");
    }
    catch (IOException e)
    {
          throw new RuntimeException(e); 
    }

}    

/**
 * 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 + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

    }

    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.
 * */
@SuppressWarnings("unused")
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 + DB_NAME;

    //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 + DB_NAME;

  myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@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) {

}


//---retrieve records---
public Cursor selectQuery(String query) throws SQLException 
{
    String myPath = DB_PATH + DB_NAME;
    //myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    myData =  SQLiteDatabase.openDatabase(myPath,null, SQLiteDatabase.CREATE_IF_NECESSARY); 
    Cursor mCursor =myData.rawQuery(query, null);
    mCursor.moveToFirst();      
    myData.close();
    return mCursor;
}


////////// For Insert And Update Data ////////
public void insert_update(String query) throws SQLException 
{
    String myPath = DB_PATH + DB_NAME;
    myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    myData.execSQL(query);
    myData.close();        
}

public boolean UpdateVote_Individual(String rowid,String value,String count) {
    String myPath = DB_PATH + DB_NAME;
    myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

      ContentValues args = new ContentValues();
      args.put("total_votes", count);
      return myData.update("promotors", args, 
              "promoter_id='" + rowid+"'", null) > 0;           
  }


}






package com.wiztech.wahab;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Criteria_Activity extends Activity {

DataBaseManager db;
Cursor cur;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    System.out.println("reached inside Criteria_Activity");
    setContentView(R.layout.criteria);

    db = new DataBaseManager(getBaseContext());
    cur = db.selectQuery("select * from  client_table1;");

    if(cur.moveToFirst()) {

        do {

            String age = cur.getString(1);
            String gender = cur.getString(2);
            String prof = cur.getString(3);
            String hobby = cur.getString(4);
            String likes = cur.getString(5);
            String dislikes = cur.getString(6);

            TextView ag = (TextView) findViewById(R.id.age_value);
            if(age.length()==0||age==""){
                age="Not Saved";
                ag.setTextSize(16);
                ag.setTextColor(Color.GRAY);
            }
            ag.setText(age);

            TextView gend = (TextView) findViewById(R.id.gender_value);
            if(gender.length()==0||gender==""){
                gender="Not Saved";
                gend.setTextSize(16);
                gend.setTextColor(Color.GRAY);
            }
            gend.setText(gender);

            TextView pr = (TextView) findViewById(R.id.prof_value);
            if(prof.length()==0||prof==""){
                prof="Not Saved";
                pr.setTextSize(16);
                pr.setTextColor(Color.GRAY);
            }
            pr.setText(prof);

            TextView hobbie = (TextView) findViewById(R.id.hobby_value);
            if(hobby.length()==0||hobby==""){
                hobby="Not Saved";
                hobbie.setTextSize(16);
                hobbie.setTextColor(Color.GRAY);
            }
            hobbie.setText(hobby);

            TextView lykes = (TextView) findViewById(R.id.likes_value);
            if(likes.length()==0||likes==""){
                likes="Not Saved";
                lykes.setTextSize(16);
                lykes.setTextColor(Color.GRAY);
            }
            lykes.setText(likes);

            TextView dislykes = (TextView) findViewById(R.id.dislikes_value);
            if(dislikes.length()==0|| dislikes==""){
                dislikes="Not Saved";
                dislykes.setTextSize(16);
                dislykes.setTextColor(Color.GRAY);
            }
            dislykes.setText(dislikes);

        }while(cur.moveToNext());
        cur.close();
    }//end if(cur.moveToFirst..........

    Button criteria_edit_btn = (Button) findViewById(R.id.cr_edit_btn);

    criteria_edit_btn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent update_criteria_intent = new Intent(getParent(),    Edit_Criteria_Activity.class);
            TabGroupActivity parentActivity = (TabGroupActivity)getParent();
            parentActivity.startChildActivity("Edit_Criteria_Activity", update_criteria_intent);
        }           
    });

}// end onCreate

 }//end this.Activity

解决方案

Well, just read what's in the log. You are doing a select on client_table1 but the table does not exist. You first have to create the table.

Please read into this tutorial on how to use sqlite on Android by using the SQLiteOpenHelper class:

http://www.vogella.de/articles/AndroidSQLite/article.html

这篇关于如何在Android中使用SQLite数据库来选择数据库中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆