如何使用数据库来我的Andr​​oid程序 [英] how do i use database for my program in android

查看:96
本文介绍了如何使用数据库来我的Andr​​oid程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的机器人。我尝试了一些codeSň也了解SQLite的一点。我也没有太多的了解。我用我的数据库仍然无法在我的程序使用SQLite浏览器创建的。

i am new to android. i tried a few codes n also read about SQLite a bit. i couldn't understand much. am still having difficulty in using my database created using SQLite Browser in my program.

我的项目是我的应用程序应显示前一后在我的数据库中的一个内容。数据库由2列。 ID和描述。

My project is that my app should display the content in my database one after the other. Database consisting of 2 columns. id and description.

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;
    }

}

以上是code我都试过了。它显示了弹出,但我想显示在数据库中的内容。我该怎么做?我已经将数据库复制到assets文件夹。感谢ü提前

Above is the code i have tried. It shows the pop-up but i want the content in the database to be displayed. How do i do it? I have copied the database to assets folder. Thank u in advance

我曾尝试以下code为DataBaseHelperClass。

I have tried the following code for 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.
    }   
}

这是我发现很容易理解的一个链接得到这个code。这也表示没有错误。但是当我尝试在Single.java调用getUserNameFromDB()方法,它要求我创建getUserNameFromDB()方法。 Y是这样呢?我不能调用不同的java类的方法?

Got this code from one of the links which i found easy to understand. This shows no errors too. But when i try calling getUserNameFromDB() method in the Single.java it asks me to create getUserNameFromDB() method. Y is it so? can't i call methods from different java class??

我需要显示下面的查询结果弹出。
从表中选择说明其中id = 1我怎样才能得到这个工作?

i need the popup to display result of below query. "SELECT description from Table where id=1" how can i get this working??

推荐答案

如果你想创建你应该看看在 SQLiteOpenHelper

If you want to create a sqlite database you should look at the SQLiteOpenHelper class

的onCreate()方式,你必须创建要使用的表。

In the onCreate() method you have to create the tables you want to use.

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

如果您想将数据插入到表中,您可以创建这样一个方法:

If you want to insert data into a table you can create a method like this:

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

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

比你可以得到的信息在光标的形式。在这种情况下,我搜索一个特定的条目,所以我从结果的第一个光标。如果设置了第三和第四条目还为空,你会得到每一个条目。

Than you can get the information in the form of a Cursor. In this case I search a specific entry, so I take the first Cursor from the result. If you set the third and forth entry also to null, you get every entry.

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类可以喜欢这样例如

The MyCursor class can like like this e.g.

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上。 <一href=\"https://github.com/David-GER/SQLiteDemoApp/blob/master/src/de/frost/david/android/sqlitedemoapp/PlacesDatabaseHelper.java\"相对=nofollow>这里是我的SQLiteOpenHelper类的完整版本。

I made a a little SQLite test app and put it on github. Here is my complete version of the SQLiteOpenHelper class.

这篇关于如何使用数据库来我的Andr​​oid程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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