- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我试图从我的 SQLite 数据库中提取我的数据并将其显示在 ListView 中,这是我目前所拥有的,但它只将第一条记录放在 ListView 中。我认为“while (mCursor.moveToNext()){”位需要更改但不确定如何更改。原始代码每次都将每条记录放在新行的 TextView 中。
if (mCursor == null){
mCursor.close();
Log.w("cursor", "null cursor");
}
mCursor.moveToFirst();
String[] s = null;
while (mCursor.moveToNext()){
s = new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn };
mCursor.moveToNext();
}
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.aa_four_column,
mCursor,
s,
new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3, R.id.txtCol4 }, 0);
lvDB.setAdapter(adapter);
更新:
我已经更改了它,所以只有这段代码在 onCreate 方法中,但是同样的事情发生了,当数据库中有多个东西时显示一个项目。
mCursor = dataBase.select("SELECT * FROM " + TABLE_NAME);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.aa_four_column,
mCursor,
new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn },
new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3, R.id.txtCol4 }, 0);
lvDB.setAdapter(adapter);
aa_column_four.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/txtCol1"
android:layout_width="181dp"
android:layout_height="wrap_content"
android:text="Column 1 text will end up here!" />
<TextView
android:id="@+id/txtCol2"
android:layout_width="63dp"
android:layout_height="wrap_content"
android:text="Column 2 text will end up here!" />
<TextView
android:id="@+id/txtCol3"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:text="Column 3 text will end up here!" />
<TextView
android:id="@+id/txtCol4"
android:layout_width="104dp"
android:layout_height="wrap_content"
android:text="Column 4 text will end up here!" />
</LinearLayout>
DatabaseManager 类
public class DataBaseManager extends SQLiteOpenHelper {
//the MAIN package of your project
private static String DB_PATH = "/data/data/com.example.activities/databases/";
//the name of your database
private static String DB_NAME = "DB_Nutrition";
private static SQLiteDatabase mDataBase;
private static DataBaseManager sInstance = null;
// database version
private static final int DATABASE_VERSION = 1;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*/
DataBaseManager() {
super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION);
try {
createDataBase();
openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Singleton for DataBase
*
* @return singleton instance
*/
public static DataBaseManager instance() {
if (sInstance == null) {
sInstance = new DataBaseManager();
}
return sInstance;
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
*
* @throws java.io.IOException io exception
*/
private void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method an empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database doesn't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
*
* @throws java.io.IOException io exception
*/
public void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
mDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/**
* Select method
*
* @param query select query
* @return - Cursor with the results
* @throws android.database.SQLException sql exception
*/
public Cursor select(String query) throws SQLException {
return mDataBase.rawQuery(query, null);
}
/**
* Insert method
*
* @param table - name of the table
* @param values values to insert
* @throws android.database.SQLException sql exception
*/
public void insert(String table, ContentValues values) throws SQLException {
mDataBase.insert(table, null, values);
}
/**
* Delete method
*
* @param table - table name
* @param where WHERE clause, if pass null, all the rows will be deleted
* @throws android.database.SQLException sql exception
*/
public void delete(String table, String where) throws SQLException {
mDataBase.delete(table, where, null);
}
/**
* Update method
*
* @param table - table name
* @param values - values to update
* @param where - WHERE clause, if pass null, all rows will be updated
*/
public void update(String table, ContentValues values, String where) {
mDataBase.update(table, values, where, null);
}
/**
* Let you make a raw query
*
* @param command - the sql comand you want to run
*/
public void sqlCommand(String command) {
mDataBase.execSQL(command);
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
错误
03-03 15:42:13.894: E/SQLiteLog(9809): (14) cannot open file at line 30176 of [00bb9c9ce4]
03-03 15:42:13.894: E/SQLiteLog(9809): (14) os_unix.c:30176: (2) open(/data/data/com.example.activities/databases/DB_Nutrition) -
03-03 15:42:13.904: E/SQLiteDatabase(9809): Failed to open database '/data/data/com.example.activities/databases/DB_Nutrition'.
03-03 15:42:13.904: E/SQLiteDatabase(9809): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.example.db_food.DataBaseManager.checkDataBase(DataBaseManager.java:228)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.example.db_food.DataBaseManager.createDataBase(DataBaseManager.java:193)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.example.db_food.DataBaseManager.<init>(DataBaseManager.java:163)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.example.db_food.DataBaseManager.instance(DataBaseManager.java:179)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.example.db_food.MyActivity.onCreate(MyActivity.java:63)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.Activity.performCreate(Activity.java:5104)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.os.Looper.loop(Looper.java:137)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-03 15:42:13.904: E/SQLiteDatabase(9809): at dalvik.system.NativeStart.main(Native Method)
最佳答案
看起来你想在 ListView 中显示表格中的数据,所以只需创建一个适配器:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.aa_four_column,
mCursor,
new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn },
new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3, R.id.txtCol4 }, 0);
lvDB.setAdapter(adapter);
(单独使用此代码,您不需要使用下面的任何其他代码,但您应该阅读它以了解为什么您的大部分代码不会执行您尝试执行的操作。)
你有一些逻辑错误。
1) 如果一个对象是null
,你不能引用它的任何方法:
if (mCursor == null){
/* mCursor.close(); This will throw an NullPointerException! */
Log.w("cursor", "null cursor");
return;
}
2) 在读取一行之前调用moveToFirst()
和 moveToNext()
可以跳过第一条记录。此外,您在两次读取记录之间调用了 moveToNext()
,因此您只是每隔一个读取一次。试试这个:
while (mCursor.moveToNext()){
// Do something
}
3) 现在要手动从 Cursor 读取实际值,您必须使用类似 getString()
或 getInt()
的方法:
List<String> strings = new ArralyList<String>();
while (mCursor.moveToNext()){
strings.add(mCursor.getString(mCursor.getColumnIndex(foodNameColumn)) + " " + mCursor.getInt(mCursor.getColumnIndex(proteinColumn)));
}
4) 在原始循环中,您没有向 s
添加任何数据。您只是用相同的值一遍又一遍地覆盖 s
:
while (mCursor.moveToNext()){
s = new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn };
}
不管这个循环执行一次还是一千次,s
总是一样的。
关于Android:将数据从数据库绑定(bind)到 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15178956/
初学者 android 问题。好的,我已经成功写入文件。例如。 //获取文件名 String filename = getResources().getString(R.string.filename
我已经将相同的图像保存到/data/data/mypackage/img/中,现在我想显示这个全屏,我曾尝试使用 ACTION_VIEW 来显示 android 标准程序,但它不是从/data/dat
我正在使用Xcode 9,Swift 4。 我正在尝试使用以下代码从URL在ImageView中显示图像: func getImageFromUrl(sourceUrl: String) -> UII
我的 Ubuntu 安装 genymotion 有问题。主要是我无法调试我的数据库,因为通过 eclipse 中的 DBMS 和 shell 中的 adb 我无法查看/data/文件夹的内容。没有显示
我正在尝试用 PHP 发布一些 JSON 数据。但是出了点问题。 这是我的 html -- {% for x in sets %}
我观察到两种方法的结果不同。为什么是这样?我知道 lm 上发生了什么,但无法弄清楚 tslm 上发生了什么。 > library(forecast) > set.seed(2) > tts lm(t
我不确定为什么会这样!我有一个由 spring data elasticsearch 和 spring data jpa 使用的类,但是当我尝试运行我的应用程序时出现错误。 Error creatin
在 this vega 图表,如果我下载并转换 flare-dependencies.json使用以下 jq 到 csv命令, jq -r '(map(keys) | add | unique) as
我正在提交一个项目,我必须在其中创建一个带有表的 mysql 数据库。一切都在我这边进行,所以我只想检查如何将我所有的压缩文件发送给使用不同计算机的人。基本上,我如何为另一台计算机创建我的数据库文件,
我有一个应用程序可以将文本文件写入内部存储。我想仔细看看我的电脑。 我运行了 Toast.makeText 来显示路径,它说:/数据/数据/我的包 但是当我转到 Android Studio 的 An
我喜欢使用 Genymotion 模拟器以如此出色的速度加载 Android。它有非常好的速度,但仍然有一些不稳定的性能。 如何从 Eclipse 中的文件资源管理器访问 Genymotion 模拟器
我需要更改 Silverlight 中文本框的格式。数据通过 MVVM 绑定(bind)。 例如,有一个 int 属性,我将 1 添加到 setter 中的值并调用 OnPropertyChanged
我想向 Youtube Data API 提出请求,但我不需要访问任何用户信息。我只想浏览公共(public)视频并根据搜索词显示视频。 我可以在未经授权的情况下这样做吗? 最佳答案 YouTube
我已经设置了一个 Twilio 应用程序,我想向人们发送更新,但我不想回复单个文本。我只是想让他们在有问题时打电话。我一切正常,但我想在发送文本时显示传入文本,以确保我不会错过任何问题。我正在使用 p
我有一个带有表单的网站(目前它是纯 HTML,但我们正在切换到 JQuery)。流程是这样的: 接受用户的输入 --- 5 个整数 通过 REST 调用网络服务 在服务器端运行一些计算...并生成一个
假设我们有一个名为 configuration.js 的文件,当我们查看内部时,我们会看到: 'use strict'; var profile = { "project": "%Projec
这部分是对 Previous Question 的扩展我的: 我现在可以从我的 CI Controller 成功返回 JSON 数据,它返回: {"results":[{"id":"1","Sourc
有什么有效的方法可以删除 ios 中 CBL 的所有文档存储?我对此有疑问,或者,如果有人知道如何从本质上使该应用程序像刚刚安装一样,那也会非常有帮助。我们正在努力确保我们的注销实际上将应用程序设置为
我有一个 Rails 应用程序,它与其他 Rails 应用程序通信以进行数据插入。我使用 jQuery $.post 方法进行数据插入。对于插入,我的其他 Rails 应用程序显示 200 OK。但在
我正在为服务于发布请求的 API 调用运行单元测试。我正在传递请求正文,并且必须将响应作为帐户数据返回。但我只收到断言错误 注意:数据是从 Azure 中获取的 spec.js const accou
我是一名优秀的程序员,十分优秀!