我正在使用 Mimir 的 Android 教程 #10,该教程涉及在列表中显示来自预填充数据库的数据。在他们的数据库中,它们有四列,即:(1) 成分描述、(2) 库存、(3) _id 和 (4) 成分名称。但是,在它们的列表中,它们仅显示来自成分名称列的数据。例如,他们的列表看起来像这样......
冰
水
等等。
但我想做的是连续显示所有四列的数据,就像这样......
冰
说明:冷冻水
编号:1
有库存:是
水
描述:H2O
ID:2
库存:是
等等。
本教程使用了 bindView 和 newView,根据他们的评论,“这让我们的代码更简洁一些,并且是更好的方法。”
我花了很多时间研究这个问题,但我无法弄清楚如何从数据库中获取这三个额外的列以显示在行中。以下是原始代码以及我所做的一些更改(我的更改在带有 * * * 的注释中注明)。
我知道我仍然缺少一些东西,但这就是我卡住的地方。有人可以建议缺少什么以显示这三个附加列中的数据吗?如果可能的话,请让我具体知道缺少什么/如何修复,而不是指点我教程(我已经看过很多,不幸的是,没有任何东西能够回答我的问题)。还请记住,示例代码使用了 bindView 和 newView 所以它需要使用它。非常感谢您的帮助。
package com.mimirsoft.tutorial10;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
class IngredientHelper extends SQLiteOpenHelper {
//we declare a bunch of useful constants
//the should be pretty obvious what they are!
private static final String DATABASE_PATH = "/data/data/com.mimirsoft.tutorial10/databases/";
private static final String DATABASE_NAME="ingredients.db";
private static final int SCHEMA_VERSION=1;
public static final String TABLE_NAME = "Ingredients";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE = "ingredient_name";
//* * * MY ADD * * *
public static final String COLUMN_TITLE2 = "ingredient_description";
//* * * MY ADD * * *
public static final String COLUMN_TITLE3 = "in_stock";
public SQLiteDatabase dbSqlite;
private final Context myContext;
public IngredientHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
this.myContext = context;
// check if exists and copy database from resource
//createDB();
}
@Override
public void onCreate(SQLiteDatabase db) {
// check if exists and copy database from resource
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbExist = DBExists();
if (!dbExist) {
//By calling this method we create an empty database into the default system location
//We need this so we can overwrite that database with our database.
this.getReadableDatabase();
//now we copy the database we included!
copyDBFromResource();
}
}
private boolean DBExists() {
SQLiteDatabase db = null;
try {
String databasePath = DATABASE_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
db.setVersion(1);
} catch (SQLiteException e) {
Log.e("SqlHelper", "database not found");
}
if (db != null) {
db.close();
}
return db != null ? true : false;
}
private void copyDBFromResource() {
InputStream inputStream = null;
OutputStream outStream = null;
String dbFilePath = DATABASE_PATH + DATABASE_NAME;
try {
inputStream = myContext.getAssets().open(DATABASE_NAME);
outStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
outStream.flush();
outStream.close();
inputStream.close();
} catch (IOException e) {
throw new Error("Problem copying database from resource file.");
}
}
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (dbSqlite != null)
{
dbSqlite.close();
}
super.close();
}
public Cursor getCursor() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
// * * * MY CHANGE - CHANGED FROM... * * *
//String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_TITLE};
//* * * TO... * * *
//String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_TITLE, COLUMN_TITLE2, COLUMN_TITLE3};
//make sure you get your search by string pass correctly!
Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
null, null, null, "ingredient_name ASC");
return mCursor;
}
public String getName(Cursor c) {
return(c.getString(1));
}
}
和...
package com.mimirsoft.tutorial10;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
//This tutorial introduces the CursorAdaptor, explains how it is different
//from the Array Adapter, and also introduces the database functionality.
//We will build a ListView from a Database of cocktail Ingredients
public class Tutorial10 extends Activity {
private IngredientHelper dbIngredientHelper = null;
private Cursor ourCursor = null;
private IngredientAdapter adapter=null;
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//this is our ListView element, obtained by id from our XML layout
ListView myListView = (ListView)findViewById(R.id.myListView);
//create our database Helper
dbIngredientHelper=new IngredientHelper(this);
//we call the create right after initializing the helper, just in case
//they have never run the app before
dbIngredientHelper.createDatabase();
//
//open the database!! Our helper now has a SQLiteDatabase database object
dbIngredientHelper.openDataBase();
//get our cursor. A cursor is a pointer to a dataset, in this case
//a set of results from a database query
ourCursor=dbIngredientHelper.getCursor();
//tell android to start managing the cursor,
//we do this just incase our activity is interrupted or ends, we want the activity
//to close and deactivate the cursor, as needed
startManagingCursor(ourCursor);
//create our adapter
adapter=new IngredientAdapter(ourCursor);
//set the adapter!!!
myListView.setAdapter(adapter);
}
catch (Exception e)
{
// this is the line of code that sends a real error message to the log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
// this is the line that prints out the location in
// the code where the error occurred.
e.printStackTrace();
}
}
class IngredientAdapter extends CursorAdapter {
IngredientAdapter(Cursor c) {
super(Tutorial10.this, c);
}
@Override
//this is a CusorAdapter
//instead of Using a getView and if(row==null)
// we use bindView and newView calls
//we can get away with this because CursorAdapters have
//a default implementation of getView that calls bindView and newView
//as needed. This makes our code a bit cleaner, and is the better way to
//do this.
public void bindView(View row, Context ctxt,
Cursor c) {
IngredientHolder holder=(IngredientHolder)row.getTag();
holder.populateFrom(c, dbIngredientHelper);
}
@Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
IngredientHolder holder=new IngredientHolder(row);
row.setTag(holder);
return(row);
}
}
static class IngredientHolder {
private TextView name=null;
IngredientHolder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, IngredientHelper r) {
name.setText(r.getName(c));
}
}
}