简体   繁体   English

如何将单个 SQLite 数据显示到 textview 中?

[英]How to display single SQLite data into textview?

I want to retrieve amount from an existing database and display it in a TextView.我想从现有数据库中检索金额并将其显示在 TextView 中。

I've created database.我已经创建了数据库。 But when I'm trying to fetch and display the amount, my app keeps crash.但是当我尝试获取和显示金额时,我的应用程序不断崩溃。

/ DataBaseHelper.java / /数据库助手.java /

   public Cursor getBalance(String amount) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_USER_BALANCE + " WHERE "
            + KEY_AMOUTNT + " = " + amount;

    Log.e(LOG, selectQuery);

    Cursor c = db.rawQuery(selectQuery, null);

    if (c != null)
        c.moveToFirst();

    Balance b = new Balance();
    b.setAmount(c.getInt(c.getColumnIndex(KEY_AMOUTNT)));

    return (Cursor) b;
}

Dashboard class:仪表盘类:

public void saveCallBack(Balance balance) {


   DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
    Cursor cursor = dataBaseHelper.getBalance(DashBoard.email);
  while (cursor.moveToNext()) {
        String s_amount = "";
        s_amount = 
      cursor.getString(cursor.getColumnIndex(DataBaseHelper.KEY_AMOUTNT));

        Double amount = 0.0;
        if (AppUtility.isNum(s_amount)) {
            amount = Double.parseDouble(s_amount);
        }

        TextView Amount = findViewById(R.id.amount);
        Amount.setText(String.valueOf(amount));


    }

}

You are casting a Balance to a Cursor which is not possible, and therefore your app will crash.您正在将Balance投射到Cursor ,这是不可能的,因此您的应用程序将崩溃。 You either want to return the database Cursor itself or the Balance object.您想要返回数据库Cursor本身或Balance对象。 You already made the Balance instance and placed some value in it, so I assume your code should be this:您已经创建了Balance实例并在其中放置了一些值,所以我假设您的代码应该是这样的:

public Balance getBalance(String amount) {
    ...

    Balance b = new Balance();
    b.setAmount(c.getInt(c.getColumnIndex(KEY_AMOUTNT)));
    return b;
}

I would suggest you learn a bit more about casting in Java, so you will understand the casting behavior.我建议您学习更多关于 Java 中的转换的知识,以便您了解转换行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM