0

我正在使用 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)); 
} 
} 
}
4

2 回答 2

0

我会尝试类似的东西。传递光标并使用整数选择所需的列并将数据保存到变量中。

私人无效getName(c){

 name.setText(c.getString(0)
 name2.setText(c.getString(1)
 name3.setText(c.getString(2)
 name4.setText(c.getString(3)

}

然后只需将更多文本视图添加到您的布局中,并使用数据库中的字符串设置它们的文本。

于 2012-08-16T02:39:52.357 回答
0

最简单的方法是,您可以在字符串的每一行末尾添加一个换行符。这会破坏你想要的字符串。这样做的负面影响是您将无法单独设置每一行的样式。

更好的方法是创建一个布局并将每个字符串添加为文本视图。在 Views/Lists/4 下的 Android API Demos 中有一个示例。列表适配器。因此,将其添加到您的设备或在模拟器上运行。并且包名是com.example.android.apis.view,类是List4.java。

这是 API 示例的子类。

/**
 * We will use a SpeechView to display each speech. It's just a LinearLayout
 * with two text fields.
 *
 */
private class SpeechView extends LinearLayout {
    public SpeechView(Context context, String title, String words) {
        super(context);

        this.setOrientation(VERTICAL);

        // Here we build the child views in code. They could also have
        // been specified in an XML file.

        mTitle = new TextView(context);
        mTitle.setText(title);
        addView(mTitle, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        mDialogue = new TextView(context);
        mDialogue.setText(words);
        addView(mDialogue, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    }
于 2012-08-15T21:24:44.353 回答