1

我是安卓新手。我尝试了一些代码,还阅读了一些关于 SQLite 的信息。我不能理解太多。在我的程序中使用使用 SQLite 浏览器创建的数据库时仍然遇到困难。

我的项目是我的应用程序应该一个接一个地显示我的数据库中的内容。数据库由 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;
    }

}

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

我已经为 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类调用方法吗?

我需要弹出窗口来显示以下查询的结果。“从 id=1 的表中选择描述”我怎样才能让它工作?

4

1 回答 1

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的形式获取信息。在这种情况下,我搜索特定条目,因此我从结果中获取第一个 Cursor。如果您将第三个和第四个条目也设置为空,您将获得每个条目。

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 上。是我的 SQLiteOpenHelper 类的完整版本。

于 2013-08-23T17:19:58.813 回答