0

I've created a sample SQLite database in Android that reads entries into a ListView. I'm going to add code so that when clicked, each ListView item starts a new activity to display more information. How can I run queries on this database from within another activity? Thanks

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

}

4

2 回答 2

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

        }
    }
}
于 2016-12-08T15:33:26.120 回答
0

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

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

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

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

于 2012-04-28T23:26:39.603 回答