Using Android studio and the SQLite database:
I have an activity which populates a SQLite database with a few data types per entry.
I want to be able to have another activity that can read this data however, I am not sure how to access the same database via another activity. At the moment I'm not sure if I should pass it as a bundle or whether there is access method.
Thanks in advance
There are multiple ways depending on your needs. The usual is:
startActivity(new Intent(context, OtherClass.class).putExtra("id", <id from db>));
int id= getIntent().getIntExtra("id",0);
SELECT
query on the retrieved id
to get the data from SQLiteMaybe this tutorial for Room will help: https://developer.android.com/training/data-storage/room/index.html
First create a new class eg:- Data
create public static String userid;
in it
then use Data.userid = sqlitedata
and then you can use Data.userid
anywhere in your project it will return the same value...
That's super easy.
Let's say this is your database defined this way if you use Room library.
@Database(
entities = [UserSchema::class],
version = 1,
exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDoa(): UserDao
companion object {
private var instance: UserDatabase? = null
fun getInstance(context: Context): UserDatabase? {
if (instance == null) {
synchronized(LmdDatabase::class) {
instance = Room.databaseBuilder(
context,
UserDatabase::class.java,
Constants.USER_DATABASE
).addMigrations()
.fallbackToDestructiveMigration()
.build()
}
}
return instance
}
fun destroyInstance() {
instance?.close()
instance = null
}
}
}
Here is your user entity definition:
@Entity(tableName = "user_table")
data class UserSchema(
@PrimaryKey
@ColumnInfo(name = "user_id") val userId:String
)
Here is your doa to delete and remove user objects from database
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(vararg userSchema: UserSchema)
@Delete
suspend fun delete(vararg userSchema: UserSchema)
@Query("SELECT * FROM user_table")
fun getAll(): LiveData<List<UserSchema>>
}
Your first activity can call insert from coroutine context to insert data eg user into table using suspend insert
method. The other activity can observe that table or database for data change using getAll()
method
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.