开发者

How can I call the Database (from another class) through the main activity class?

I want to make my code clean & simple, so I want to create DB but I want to call it from another class through the main activity... I tried to do this but it didn't works... So, how should it works ??

Note: I'm kind a newbie in the android development. So, sorry for this type of question...

This is the main activity:

package com.DataStorage.Excercise;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

public class DataStorageActivity extends Activity {

    private Context context;
    public SQLiteDatabase db_1=null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       AccessingDB acc= new AccessingDB(context);
       acc.onCreate(db_1);


    }
}

the other class that have the DB code.. :

package com.DataStorage.Excercise;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class AccessingDB extends SQLiteOpenHelper {

    public AccessingDB(Context context) {
        super(context, "Test_1", null, 1);
        // TODO Auto-generated constructor stub
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        db.execSQL(CreateTable());
        db.execSQL(Insert_1());

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

    /*
    public String CreateDB_1(){

        String s1= "create database Test_1;";
            return s1;
    }
    */

    private String CreateTable(){

        String s2="create table Customer(id_1 INTEGER,fn TEXT,ln TEXt);";
        return s2;
    }

    private String Insert_1(){

        String s3="insert into Customer values(1开发者_开发知识库,'aaa','bbb');";
        return s3;

    }

}

Thanks alot...


If you call the database in your MainActivity, can't you just call your MainActivity in your other activity's and then call the database using the Main? Like this:

In your MainActivity:

Database db;

In your other activity's:

MainActivity main;

main.db.somequery; //call the method you want

Or did I misunderstand and you need something else?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜