我如何在android中使用我的程序数据库

时间:2013-08-23 16:55:37

标签: android eclipse sqlite

我是android新手。我尝试了几个代码n也读了一下SQLite。我无法理解。我仍然难以使用我的程序中使用SQLite Browser创建的数据库。

我的项目是我的应用程序应该一个接一个地显示我的数据库中的内容。数据库由2列组成。 id和描述。

package com.example.singlepop;

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class Single extends Activity {

    PopupWindow popUp;
    LinearLayout layout;
    TextView tv;
    LayoutParams params;
    LinearLayout mainLayout;
    Button but;
    boolean click = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single);

        final Calendar cld = Calendar.getInstance();

        int time = cld.get(Calendar.HOUR_OF_DAY);
            if(time==16)
            {
                popUp = new PopupWindow(this);
                layout = new LinearLayout(this);
                mainLayout = new LinearLayout(this);
                tv = new TextView(this);
                but = new Button(this);
                but.setText("Click Me");
                but.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        if (click) {
                            popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
                            popUp.update(50, 50, 300, 80);
                            click = false;
                        } else {
                            popUp.dismiss();
                            click = true;
                        }
                    }



                });
                params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT);
                layout.setOrientation(LinearLayout.VERTICAL);

                // Here a single tuple in the database should be displayed everyday at 16hrs 

                tv.setText("Hi this is a sample text for popup window");
                //

                layout.addView(tv, params);
                popUp.setContentView(layout);
                // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
                mainLayout.addView(but, params);
                setContentView(mainLayout);
            }

                        }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.single, menu);
        return true;
    }

}

以上是我试过的代码。它显示弹出窗口,但我希望显示数据库中的内容。我该怎么做?我已将数据库复制到assets文件夹。提前谢谢你

我为DataBaseHelperClass尝试了以下代码。

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

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelperClass extends SQLiteOpenHelper {

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/package_name/databases/";
    // Data Base Name.
    private static final String DATABASE_NAME = "db.sqlite";
    // Data Base Version.
    private static final int DATABASE_VERSION = 1;
    // Table Names of Data Base.
    static final String TABLE_Name = "TList";

    public Context context;
    static SQLiteDatabase sqliteDataBase;

    public DataBaseHelperClass(Context context) {       
        super(context, DATABASE_NAME, null ,DATABASE_VERSION);
        this.context = context;
    }

    public void createDataBase() throws IOException{
        //check if the database exists
        boolean databaseExist = checkDataBase();

        if(databaseExist){
            // Do Nothing.
        }else{
            this.createDataBase();         
            copyDataBase(); 
        }// end if else dbExist
    } // end createDataBase().


    public boolean checkDataBase(){
        File databaseFile = new File(DB_PATH + DATABASE_NAME);
        return databaseFile.exists();        
    }

    private void copyDataBase() throws IOException{ 
        //Open your local db as the input stream
        InputStream myInput = context.getAssets().open(DATABASE_NAME); 
        // Path to the just created empty db
        String outFileName = DB_PATH + DATABASE_NAME; 
        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName); 
        //transfer bytes from the input file to the output file
        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(); 

    }

    /**
     * This method opens the data base connection.
     * First it create the path up till data base of the device.
     * Then create connection with data base.
     */
    public void openDataBase() throws SQLException{      
        //Open the database
        String myPath = DB_PATH + DATABASE_NAME;
        sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
    }

    /**
     * This Method is used to close the data base connection.
     */
    public synchronized void close() { 
        if(sqliteDataBase != null)
            sqliteDataBase.close(); 
        super.close(); 
    }

    public String getUserNameFromDB(){
        String query = "select desc From "+TABLE_Name;
        Cursor cursor = sqliteDataBase.rawQuery(query, null);
        String description = null;
        if(cursor.getCount()>0){
            if(cursor.moveToFirst()){
        do{
                    description = cursor.getString(0);
                }while (cursor.moveToNext());
            }
        }
        return description;
    }

    public void onCreate(SQLiteDatabase db) {
        // No need to write the create table query.
        // As we are using Pre built data base.
        // Which is ReadOnly.
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // No need to write the update table query.
        // As we are using Pre built data base.
        // Which is ReadOnly.
        // We should not update it as requirements of application.
    }   
}

从我发现易于理解的链接中获取此代码。这也没有显示错误。但是当我尝试在Single.java中调用getUserNameFromDB()方法时,它要求我创建getUserNameFromDB()方法。是这样吗?我不能从不同的java类调用方法??

我需要弹出窗口显示以下查询的结果。 “表中的SELECT描述,其中id = 1”我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:0)

如果您想创建一个sqlite数据库,您应该查看 SQLiteOpenHelper

onCreate()方法中,您必须创建要使用的表。

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE mytable (_id integer primary key autoincrement, 
    stuff varchar(100))");
}

如果要将数据插入表中,可以创建如下方法:

public long insertObject(Object o) {
    ContentValues cv = new ContentValues();
    cv.put("stuff", o.getSomething());

    return getWritableDatabase().insert("mytable", null, cv);
}

您可以以光标的形式获取信息。在这种情况下,我搜索一个特定的条目,所以我从结果中取出第一个Cursor。如果将第三个和第四个条目也设置为null,则会获得每个条目。

public House queryHouse(long id) {
    Cursor wrapped = getReadableDatabase().query(TABLE_HOUSE, null, "_id=?", 
    new String[]{""+id}, null, null, null);

    MyCursor c = new MyCursor(wrapped);

    c.moveToFirst();
    Object o = c.getObject();
    c.close();
    return o;
}

MyCursor类可以像这样。

public static class MyCursor extends CursorWrapper {

    public MyCursor(Cursor cursor) {
        super(cursor);
    }

    public Person getObject() {
        if (isBeforeFirst() || isAfterLast())
            return null;

        Object o = new Object();

        o.setId(getLong(getColumnIndex("column_abc")));
        //more 

        return p;
    }

}

我制作了一个小的SQLite测试应用程序并将其放在github上。 Here是我完整版的SQLiteOpenHelper类。

相关问题