如何使按钮使文本显示在不同的活动中?

时间:2018-07-25 19:43:33

标签: android button

如何做到这一点,当我按下按钮时,带有时间和日期的文本会显示在另一个活动中?我想要它,因此您可以通过滚动在该活动的“卡片”中看到尽可能多的卡片(参见图一)。图二是要按下的按钮。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

  • 创建数据库。 (检查房间或SQLite)

  • 使用按钮添加记录

  • 访问具有ListView的活动时,请从数据库中加载记录。

我为您提供一个有关创建数据库的简化示例;但是,那里有很多教程。这个使用Room是SQLite上方的一层。

示例:

在app \ build.gradle中,添加依赖项部分:

implementation 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'

在您的主要活动中,执行以下操作:

private static final String DATABASE_NAME = "db_stuff";
private ADatabase aDatabase;

(稍后我们将设置抽象类ADatabase)

设置数据库:

private void setupDatabase(){
    final File fileDb = getApplicationContext().getDatabasePath(DATABASE_NAME);
    if (!fileDb.exists()){
        createDatabase();
        loadDatabase();
    }else{
        Log.d(TAG, "Database already exists"));
    }
}

private void createDatabase(){
    RoomDatabase.Builder<ADatabase> builder;
    builder = Room.databaseBuilder(getApplicationContext(),
            ADatabase.class,
            DATABASE_NAME);
    aDatabase = builder.fallbackToDestructiveMigration().build();
}

 private void loadDatabase(){
    new Thread(new Runnable(){
        @Override
        public void run(){
            Stuff stuff = new Stuff();
            stuff.setId("1");
            stuff.setName("Candle");
            aDatabase.daoAccess().insertStuff(stuff);

            stuff= new Stuff();
            stuff.setId("2");
            stuff.setName("Chair");                
            aDatabase.daoAccess().insertStuff(stuff);
        }
    }).start();
}

创建我上面描述的抽象类:

@Database (entities = {Stuff.class}, version = 1, exportSchema = false)
public abstract class ADatabase extends RoomDatabase {
    public abstract IDaoAccessStuff daoAccess();
}

创建DAO界面:

@Dao
public interface IDaoAccessStuff {

    @Insert
    void insertStuff (Stuff stuff);

    @Update
    void updateStuff (Stuff stuff);

    @Delete
    void deleteStuff (Stuff stuff);

    @Query("SELECT * FROM Stuff WHERE id = :id")
    Exercises fetchStuffById (int id);

    @Insert
    void insertALotOfStuff (List<Stuff> stuff);

    @Query("DELETE FROM Stuff")
    void emptyTable();
}

创建表的模型:

@Entity
public class Stuff {
    @NonNull
    @PrimaryKey
    private String id;

    private String name;

    public Stuff(){}

    @NonNull
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(@NonNull String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}