How do I access the database created in one activity from another activity?
I have two activities, Activity A 开发者_JAVA百科and Activity B. Activity B is creating a database, inserting data to it, editing data and then closing the database. Activity A is an empty screen and it calls activity B. Activity B finishes its database work and goes back to activity A. Now I want my activity A to access the database created and modified by Activity B. It might be a very simple solution, please excuse me if it is a silly question. Any clue will is highly appreciated.
Thanks, Shaista
To access the data in Activity A, use the onActivityResult() in Activity A in the following way:
@Override
protected void onActivityResult(int requestCode, int resultCode, ntent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == PICK_CONTACT_REQUEST && resultCode == 10) {
pos = intent.getIntExtra("doc_id", 1);
mDbHelper.open();
/* Write the database accessing code and whatever you want to do on
returning back from Activity B here. */
mDbHelper.close();
}
}
And also remember that you can use this method with the intent method with calling startActivityForResult()
with intent
That's it, what you have to do
If there is any confusion then you can ask
EDIT: This code will help in fetching the data
public class FirstActivity extends Activity {
AnyDBAdapter mDbHelper = new AnyDBAdapter(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbHelper.open();
Cursor foemiCursor = mDbHelper.fetchAll();/*fetchAll() is which you need to create in AnyDBAdapter class showing query for fetching the database */
startManagingCursor(foemiCursor);
/*Now the query will get executed and you need to access just vales from it, here you write code for it*/
foemiCursor.close();
mDbHelper.close();
}
You should make a DBAdapter class to handle all of your database interaction. The database is SQL Lite and is for the whole application. Just access it in B as you did in A.
use content provider...But directly your activity cannot interact with content provider activity interact with content Resolver and than resolver interact with content provider so now you can access data of other activity.
You should check this link, http://kagii.squarespace.com/journal/2010/9/10/android-sqlite-locking.html. It contains some good information on how to use databases on android.
精彩评论