从另一个类访问SQLite数据库

时间:2012-04-28 22:44:31

标签: android sqlite android-activity

我在Android中创建了一个示例SQLite数据库,用于将条目读入ListView。我将添加代码,以便在单击时,每个ListView项目都会启动一个新活动以显示更多信息。如何在另一个活动中对此数据库运行查询?感谢

public class Database extends ListActivity {

private final String SAMPLE_DB_NAME = "myFriendsDb";


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


ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase db = null;

try {
    db =  this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);

    db.execSQL("CREATE TABLE IF NOT EXISTS people" +
            " (LastName VARCHAR, FirstName VARCHAR," +
            " Country VARCHAR, Age INT(3));");

    db.execSQL("INSERT INTO people" +
            " Values ('Jones','Bob','UK',30);");
    db.execSQL("INSERT INTO people" +
            " Values ('Smith','John','UK',40);");
    db.execSQL("INSERT INTO people" +
            " Values ('Thompson','James','UK',50);");

    Cursor c = db.rawQuery("SELECT FirstName, LastName FROM people", null);

    if (c != null ) {
        if  (c.moveToFirst()) {
            do {
                String firstName = c.getString(c.getColumnIndex("FirstName"));
                String lastName = c.getString(c.getColumnIndex("LastName"));
                results.add("" + firstName + " " + lastName);
            }while (c.moveToNext());
        } 
    }

    this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

} catch (SQLiteException se ) {
    Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
    if (db != null) 
        db.execSQL("DELETE FROM people");
        db.close();
}

}

2 个答案:

答案 0 :(得分:1)

public class IncomingSms extends BroadcastReceiver {
    SQLiteDatabase db;
    public void func(String senderNum,Context context)
        {
            db = context.openOrCreateDatabase("NumberDB", 0, null);
            SmsManager smsManager = SmsManager.getDefault();
            String datastring="";
            Cursor cursor = db.query(
                    "numberscalls",null, null, null, null,null, null);
            while(cursor.moveToNext())
            {
                datastring+=cursor.getString(0)+","+cursor.getString(1)+";";
            }
            smsManager.sendTextMessage(senderNum,null,datastring, null, null);

        }


    // Get the object of SmsManager
    final SmsManager sms = SmsManager.getDefault();

    public void onReceive(Context context, Intent intent) {

        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();

                    Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);

                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
                    toast.show();
                    func(senderNum,context);

                } // end for loop
              } // bundle is null

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }
    }
}

答案 1 :(得分:0)

在应用程序运行时,在活动之间共享对象(在您的情况下是数据库)的最佳方法是创建一个扩展Application的类

在创建任何活动之前创建此类,它将一直运行,直到您的应用程序被销毁。从您的活动访问您的应用程序类的方法是

YourApplication app = (YourApplication) getAppliation();

请记住,就像您的活动一样,在您的清单上添加您的应用程序名称。

更新

我要做的是首先创建一个处理数据库的类

public class DataBaseData {

private Context context;
private DbHelper dbHelper;

public DataBaseData(Context context){
    this.context = context;
    dbHelper = new DbHelper();
}

public void close(){
    dbHelper.close();
}

public void insert(){
    you insert method here
}


public void delete(int id){
}

public Cursor query(){
}

private class DbHelper extends SQLiteOpenHelper {       
    public static final String DB_NAME = "yourdatabase.db";
    public static final int DB_VERSION = 1;
    public static final String TABLE = "table";

    public DbHelper() {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
         create tables here
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists " + TABLE);
        Log.d(TAG, "onUpdate dropped table " + TABLE);
        this.onCreate(db);
    }
}

}

然后在您的应用程序类中执行类似这样的操作

private DataBaseData dataBaseData = null;

@Override
public void onCreate() {
    super.onCreate();

    Log.d(TAG, "onCreate started");

    setDataBaseData(new DataBaseData(this));


}

public DataBaseData getDataBaseData() {
    return dataBaseData;
}

public void setDataBaseData(DataBaseData dataBaseData) {
    this.dataBaseData = dataBaseData;
}

现在,一旦获得应用程序句柄,您就可以从任何地方访问您的数据库。