【问题标题】:How to display a query from a database in SQLite to an activity?如何在 SQLite 中显示从数据库到活动的查询?
【发布时间】:2021-05-13 23:59:53
【问题描述】:

我正在开发一个包含计时器的应用程序,并且时间保存到 SQLite 数据库中,我想使用保存的这些时间来获取另一个活动中文本视图的平均时间结果,有什么办法吗?我一般是编程新手,但我还没有找到方法来做到这一点。对于我所看到的查询 SELECT AVG(time) FROM TIMETABLE 在数据库 Inspector 上运行良好,我只需要在文本视图中获取该结果。

【问题讨论】:

  • 您好,请提供一些代码,显示您到目前为止所做的尝试。提交问题时通常会有相关代码。缺乏代码可能是收到社区反对票的原因之一。

标签: android sqlite android-sqlite


【解决方案1】:

我想使用节省的这些时间来获得另一个活动中文本视图的平均时间结果,有什么办法吗?

是的,毫无疑问。尽管您的意思是实际保存,例如在数据库中或仅仅意味着提取会使过程不同。可能只是后者,因为可能不需要永久保存结果(见下一部分)

在另一个活动中获取文本视图的平均时间结果。

这可以直接从活动中提取/由活动直接提取,似乎几乎不需要保存通行证并提取父活动中的平均值。但同样,如果您的意思是一组数据而不是整个数据的平均值SELECT AVG(time) FROM TIMETABLE 是整个数据),如果应用了 WHERE 子句,那么驱动程序就是WHERE 的 /parameters 可能需要从父 Activity 传递给子 Activity,这可以通过在启动子 Activity 之前添加 Intent Extras 然后在子 Activity 中提取它们来完成。)

无论哪种情况,您都可以:-

  1. 实例化数据库助手的实例(使用子活动上下文的 SQLiteOpenHelper 的子类)
  2. 使用rawQuery 或最好使用query 方法返回Cursor 使用/构建(查询方法代表您执行)适当的SELECT
  3. 使用 Cursor 的 moveToFirst 方法,测试它是否返回 true(以防万一,如果查询有效,则应始终返回单行)
  4. 提取值(可能作为字符串使用 光标的getString 方法)
  5. 如果 movetoFirst 返回 false (非常不可能) 将字符串设置为适当的值以指示未获取/提取任何内容。
  6. 在任何一种情况下都使用光标的关闭方法(打开太多(如未关闭)光标会导致异常(类似于 1000))
  7. 设置 Textview 的文本(可以作为 4 和 6 的一部分完成)

示例

这是一个非常基本的例子:-

当开始时进入第一个活动 (MainActivity),准备名为 clickMe 的 TextView,允许单击它并启动第二个活动 (MainActivity2),获取 DatabaseHelper 的实例,添加一些行到 chrono 表,(作弊并更改 clickMe 文本视图以显示平均值)。

如果 clickMe 文本视图被点击,第二个活动被启动并且...

第二个活动获取它的数据库助手实例并将 TextView 设置为平均值。

为简洁起见(可以使用返回按钮返回)。

代码

数据库助手 DBHelper.java

class DBHelper extends SQLiteOpenHelper {

    private static final String DBNAME = "chrono.db"; /* name of the database file - change as fits */
    private static final int DBVERSION = 1; /* version of the database - best to use 1 at first */
    public static final String CHRONO_TABLENAME = "_chrono"; /* name of the table - change as fits underscore at start means no clash with SQLite keywords */
    public static final String CHRONO_TABLE_ID_COLUMN = BaseColumns._ID; /* make the ID column use the android standard column name for the ID column */
    public static final String CHRONO_TABLE_TIME_COLUMN = "time"; /* name of the time column */
    private static SQLiteDatabase db;

    private static volatile DBHelper instance_of_DBHelper;

    private DBHelper(@Nullable Context context) {
        super(context, DBNAME, null, DBVERSION);
        db = this.getWritableDatabase(); /* Force initial open of the database when called - optional */
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + CHRONO_TABLENAME + "(" +
                CHRONO_TABLE_ID_COLUMN + " INTEGER PRIMARY KEY," +
                CHRONO_TABLE_TIME_COLUMN + " INTEGER DEFAULT 0" +
                ");");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public static DBHelper getInstance_of_DBHelper(Context context) {
        if (instance_of_DBHelper == null) {
            instance_of_DBHelper = new DBHelper(context);
        }
        return instance_of_DBHelper;
    }

    public long insertChronoRow(long timeAsLong) {
        ContentValues cv = new ContentValues();
        cv.put(CHRONO_TABLE_TIME_COLUMN,timeAsLong);
        return db.insert(CHRONO_TABLENAME,null,cv);
    }

    public String getAverageTime() {
        String rv = "Cannot get Average????";
        Cursor csr = db.query(
                CHRONO_TABLENAME,
                new String[]{"avg("+ CHRONO_TABLE_TIME_COLUMN +") AS "+ CHRONO_TABLE_TIME_COLUMN +""},
                null,
                null,
                null,
                null,
                null,
                null
        );
        if (csr.moveToFirst()) {
            rv = csr.getString(csr.getColumnIndex(CHRONO_TABLE_TIME_COLUMN));
        }
        csr.close();
        return rv;
    }
}
  • 请注意,这使用了单例方法,因此始终使用相同的实例。

MainActivity 的布局 activity_main.xml :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/clickme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CLICK ME!" />

</LinearLayout>

第一个活动MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView clickMe;
    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        clickMe = this.findViewById(R.id.clickme);
        // Setup the TextView so that if clicked it starts the 2nd activity
        clickMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,MainActivity2.class);
                intent.putExtra("UNIQUE_KEY_FROM_MAINACTIVITY_VALUE1","a suitable values to be passed to the started activity");
                startActivity(intent);
            }
        });

        dbHelper = DBHelper.getInstance_of_DBHelper(this); /* Get an Instance of the Database helper */
        dbHelper.insertChronoRow(60); /* 60 time units */
        dbHelper.insertChronoRow(100); /* 100 time units */
        dbHelper.insertChronoRow(110); /* 110 time untis */
        clickMe.setText("CLICK ME!! - P.S. Average is now " + dbHelper.getAverageTime());
    }
}

第二个活动的布局activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">
    <TextView
        android:id="@+id/average"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No Average as yet - if you see this then something is not right">
    </TextView>

</LinearLayout>

最后是第二个活动MainActivity2.java

public class MainActivity2 extends AppCompatActivity {

    TextView average;
    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        average = this.findViewById(R.id.average);
        dbHelper = DBHelper.getInstance_of_DBHelper(this);
        average.setText(dbHelper.getAverageTime());
    }
}

结果

开始时:-

当点击 TextView(如上图所示)并启动第二个活动时:-

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    相关资源
    最近更新 更多