java - 如何从 sqlite 数据库中获取数据并将其存储在 ListView 中

标签 java android database sqlite

我有一个数据库,我需要从中读取数据并在 ListView 中查看它,它包含其中的一些表,一个名为“main_categories”的表,其中有一个名为“category_name”的字段,它是主键 这是数据适配器:

    public DataAdapter(Context context) {
        this.mContext = context;
        mDbHelper = new DataBaseHelper(mContext);
    }

    public DataAdapter createDatabase() throws SQLException {
        try {
            mDbHelper.createDataBase();
        } catch (IOException mIOException) {
            Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
            throw new Error("UnableToCreateDatabase");
        }
        return this;
    }

    public DataAdapter open() throws SQLException {
        try {
            mDbHelper.openDataBase();
            mDbHelper.close();
            mDb = mDbHelper.getReadableDatabase();
        } catch (SQLException mSQLException) {
            Log.e(TAG, "open >>" + mSQLException.toString());
            throw mSQLException;
        }
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public Cursor getTestData() {
        try {
            String sql = "SELECT * FROM myTable";

            Cursor mCur = mDb.rawQuery(sql, null);
            if (mCur != null) {
                mCur.moveToNext();
            }
            return mCur;
        } catch (SQLException mSQLException) {
            Log.e(TAG, "getTestData >>" + mSQLException.toString());
            throw mSQLException;
        }
    }
}

这是 DataBaseHelper:

    public  class DataBaseHelper extends SQLiteOpenHelper
    {
        private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
        //destination path (location) of our database on device
        private static String DB_PATH = "";
        private static String DB_NAME ="my_knowledge";// Database name
        private SQLiteDatabase mDataBase;
        private final Context mContext;

        public DataBaseHelper(Context context)
        {
            super(context, DB_NAME, null, 1);// 1? Its database Version
            if(android.os.Build.VERSION.SDK_INT >= 17){
                DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
            }
            else
            {
                DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
            }
            this.mContext = context;
        }

        public void createDataBase() throws IOException
        {
            //If the database does not exist, copy it from the assets.

            boolean mDataBaseExist = checkDataBase();
            if(!mDataBaseExist)
            {
                this.getReadableDatabase();
                this.close();
                try
                {
                    //Copy the database from assests
                    copyDataBase();
                    Log.e(TAG, "createDatabase database created");
                }
                catch (IOException mIOException)
                {
                    throw new Error("ErrorCopyingDataBase");
                }
            }
        }

        //Check that the database exists here: /data/data/your package/databases/Da Name
        private boolean checkDataBase()
        {
            File dbFile = new File(DB_PATH + DB_NAME);
            //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
            return dbFile.exists();
        }

        //Copy the database from assets
        private void copyDataBase() throws IOException
        {
            InputStream mInput = mContext.getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_NAME;
            OutputStream mOutput = new FileOutputStream(outFileName);
            byte[] mBuffer = new byte[1024];
            int mLength;
            while ((mLength = mInput.read(mBuffer))>0)
            {
                mOutput.write(mBuffer, 0, mLength);
            }
            mOutput.flush();
            mOutput.close();
            mInput.close();
        }

        //Open the database, so we can query it
        public boolean openDataBase() throws SQLException
        {
            String mPath = DB_PATH + DB_NAME;
            //Log.v("mPath", mPath);
            mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
            //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
            return mDataBase != null;
        }

        @Override
        public synchronized void close()
        {
            if(mDataBase != null)
                mDataBase.close();
            super.close();
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {

        }

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

        }
    }

and this is the main activity for now:

public class MainActivity extends AppCompatActivity {
    SQLiteDatabase sqLiteDatabase;
    private static String DB_NAME ="my_knowledge"; // Database name

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView list = findViewById(R.id.main_list);
        DataAdapter mDbHelper = new DataAdapter(this);
        mDbHelper.createDatabase();
        mDbHelper.open();

        Cursor testdata = mDbHelper.getTestData();
        mDbHelper.close();
    }
}

我想知道一种将数据存储在数组表中的方法(例如“main_categories”)并使用 ListView 查看它们

最佳答案

取决于你的表列类型

List<String> temp;
testdata.moveToFirst();
do {
      temp.add(testdata.getString(0));
} while (testdata.moveToNext());

您的游标 testdatatestdata.moveToFirst(); 中有第一行,每一列都与列索引相关联,即 0、1 等。 testdata.moveToNext(); 将有连续的行。

关于java - 如何从 sqlite 数据库中获取数据并将其存储在 ListView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49522672/

相关文章:

java - 使用带有字符串的 Luhn 算法在 Java 中进行信用卡验证

java - 如何在 Unix 上获取 Java 中所有已安装文件系统的列表?

android - Room - 检查最近是否获取了数据

sql - 如何使用其他表数据 SQL 更新一列数据

php - 我正在努力处理我的数据库和查询

java - 如何将 json 字符串作为 RESTFUL 请求发送给 postman

c# - 是否有与 Java 的注释处理工具 (apt) 等效的 C#?

android - 使用蓝牙打印机从 Android 应用程序打印数据

android - 软键盘不会在 android 中以编程方式隐藏

java - OkHttp3的实例增长很快,无法被GC释放! OOM