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

时间:2018-03-27 21:26:55

标签: java android database sqlite

我有一个数据库我需要从中读取数据并在列表视图中查看它包含一些表格,其名为" main_categories"其中有一个名为" category_name"这是主键 这是DataAdapter:

    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")并使用列表视图查看它们

2 个答案:

答案 0 :(得分:0)

取决于您的表格列类型

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

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

答案 1 :(得分:0)

有几件事:

  • 首先,我会考虑在您的0.400000000000021课程中添加float64方法,而不是使用query,例如:

    DataBaseHelper

  • 您可以在rawQuery中调用查询方法,并使用Cursor query(String table, String[] projection, String where, String orderBy) { return getReadableDatabase().query(table, projection, where, null, null, null, orderBy); }对象填充列表。

  • 看看使用Cursor Loader? 从光标和适配器中获取数据。