2012-04-28 43 views
0

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

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

}

+0

http://www.vogella.com/articles/AndroidSQLite/article.html#databasetutorial是关于各种SQLite相关事情的不错教程。您应该特别关注用于打开数据库的'SQLiteOpenHelper'和用于访问数据的DataSource类。 – zapl 2012-04-28 22:55:35

回答

0

共享,而您的应用程序运行活动之间的对象(数据库,你的情况),最好的办法是通过创建扩展应用

该类被之前的任何创建的类活动已创建,并且会一直运行,直到您的应用程序被销毁。从您的活动访问你的应用类中的方法是做

YourApplication app = (YourApplication) getAppliation(); 

记得加你应用程序的名称上,你表现就像你会为您的活动。

UPDATE

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

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

现在,只要您掌握了应用程序的处理方式,您就可以从任何地方访问您的数据库。

+0

如果我试着说数据库(我的应用程序名称)不能解析为变量。 – user1362255 2012-04-28 23:44:04

+0

刚刚更新...希望这使事情更清晰 – codeskraps 2012-04-29 00:00:41

+0

如果我使用该类创建我的数据库,它会混淆行 'this.setListAdapter(new ArrayAdapter (this,android.R.layout.simple_list_item_1,results) );' 我可以用什么来代替? – user1362255 2012-04-29 00:31:54

-1

DatabaseHandler myDatabase = new DatabaseHandler(this); 列出allContacts = myDatabase.getAllContacts();

希望这会有所帮助。仅仅指出DatabaseHandler在构造函数中需要一个Context,所以,只要你的类照相机从Activity延伸出来,它就可以工作。

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

     } 
    } 
}