how do i use database for my program in android

元气小坏坏 提交于 2020-01-16 00:52:37

问题


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.

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

}

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

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

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??

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


回答1:


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

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

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

}

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



来源:https://stackoverflow.com/questions/18408076/how-do-i-use-database-for-my-program-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!