【问题标题】:Can't populate textview from database无法从数据库中填充文本视图
【发布时间】:2014-04-01 08:51:26
【问题描述】:

我不明白为什么我没有从数据库中获取任何数据。我不得不承认我对列表视图、文本视图和适配器感到困惑。 该数据库包含一个人和一件礼物。那应该倒入一个文本视图中。不知何故,我似乎必须制作一个列表视图,但是....我很困惑。 我读了很多书,也很努力,但我不知道。如果有人可以帮助我,我将不胜感激:-)

唯一发生的事情是出现了一个空列表。

代码如下:

主Activity.java:

package com.example.julegaveliste2;



import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends ListActivity {
    DatabaseHelper db;
    Button knapp1;
    Button knapp2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final DatabaseHelper db = new DatabaseHelper(MainActivity.this);

        knapp1 = (Button) findViewById(R.id.Legg_Til);
        knapp2 = (Button) findViewById(R.id.Les_database);

        knapp2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
            visliste(db.getWritableDatabase());
            }
        });


       knapp1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                LagTabell(db.getWritableDatabase());

            }
        }); 

    }

    public static void LagTabell(SQLiteDatabase db)
    {
        ContentValues jul = new ContentValues();
        jul.put("person", "Ida");
        jul.put("gave", "blomst");
        db.insert("julegaveliste2", "person", jul); 
    }

    public void visliste(SQLiteDatabase db)
    {   
        Cursor cursor=db.rawQuery("SELECT _id, person, gave FROM julegaveliste2", null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.activity_list_item, cursor, new String[]{"person","gave"}, new int[]{R.id.person,R.id.gave},0);

        ListView listView = (ListView) findViewById(R.id.listView1);
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }


    @Override
    protected void onDestroy()
        {
            super.onDestroy();
            db.close();
        }

}

DatabaseHelper.java:

package com.example.julegaveliste2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME="julegaveliste2.db";
    private static final int SCHEMA=1;

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, SCHEMA);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE julegaveliste2 (_id INTEGER PRIMARY KEY AUTOINCREMENT, person TEXT NOT NULL, gave TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        throw new RuntimeException("How did we get here?");
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView    
        android:id="@+id/person"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/gave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/Legg_Til"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="15dp"
        android:layout_marginRight="17dp"
        android:text="@string/opprett_database" />

    <Button
        android:id="@+id/Les_database"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/Legg_Til"
        android:layout_alignBottom="@+id/Legg_Til"
        android:layout_toRightOf="@+id/person"
        android:text="@string/les_database" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_above="@+id/Legg_Til"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="42dp" >
    </ListView>

    <ListView
        android1:id="@+id/listView1"
        android1:layout_width="match_parent"
        android1:layout_height="100dp" >

    </ListView>

</RelativeLayout>

【问题讨论】:

  • 在您的 XML 中,您有两个列表视图,您知道吗?是你想要的吗,还是重点是制作一个且只有一个 lisview ?
  • 如果我删除了 id="@android:id/list 的 ListView,我会收到错误消息说缺少列表。另一个listview(listView1) 在那里,因为我找不到 R.id .list.
  • SimpleCursorAdapter 已弃用。也许您应该尝试使用 ArrayAdapter 并创建一个方法来执行您的查询并将结果作为 ArrayList 返回

标签: android sqlite listview textview adapter


【解决方案1】:

您应该尝试将您的SimpleCursorAdapter 替换为ArrayAdapter。为此,我们需要对您的代码进行一些修改。我们需要在您的应用程序中创建一个新类,我将其命名为 PresentItem,为您的列表创建一个 ArrayAdapter,为列表中的每一行创建一个 XML 布局,以及将 SQLite 行转换为 PresentItems 的方法。首先是新型号,PresentItem

public class PresentItem  {
    private String name, present;
    private int id;

    public PresentItem(int id, String name, String present) {
         // Init 
    }

    // Getters, setters, etc.

}

所以,当我们现在从您的数据库中读取数据时,我们可以将从查询中获得的每一行转换为新的PresentItems

public List<PresentItem> getPresentItems(SQLiteDatabase db) {
    Cursor cursor = db.query("julegaveliste2", 
      new String[] {"_id", "person", "gave"}, null, null, null, null, null);

    List<PresentItem> result = new ArrayList<PresentItem>();
    PresentItem item;

    if (cursor != null && cursor.moveToFirst()) {
        int index = cursor.getColumnIndex("_id");
        int id = cursor.getInt(index));

        index = cursor.getColumnIndex("name");
        String name = cursor.getString(index));

        index = cursor.getColumnIndex("present");
        String present = cursor.getString(index);

        item = new PresentItem(id, name, present);
        result.add(item);
    }
    return result;
}

一旦我们从数据库中解析出PresentItems,我们就需要一种方法来显示它们。要在您的应用中显示PresentItems,我们需要我们自己的ArrayAdapter,它看起来像这样:

public class PresentListAdapter extends ArrayAdapter<PresentItem> {
  private Context ctx;
  private List<PresentItem> presentItems;
  public PresentListAdapter(Context ctx, int layoutResourceId, List<PresentItem> presentItems) { 
    super(context, layoutResourceId, presentItems);
    this.ctx = ctx;
    this.presentItems = presentItems;
}

  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
      convertView = inflater.inflate(mLayoutResourceId, parent, false);
    }
  PresentItem item = presentItems.get(position);
  ((TextView) convertView.findViewById(R.id.row_id)).setText("" + item.getId());
  ((TextView) convertView.findViewById(R.id.name)).setText(item.getName());
  ((TextView) convertView.findViewById(R.id.present)).setText(item.getPresent());
  return convertView;
}

要在您的应用中使用适配器,请执行以下操作:

public void visListe(SQLiteDatabase db){   
  List<PresentItem> items = getPresentItems(db);
  PresentItemAdapter adapter = new PresentItemAdapter(this, R.layout.presentListItem, items);
  ListView listView = (ListView) findViewById(R.id.listView1);
  listView.setAdapter(adapter);
  listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

而且,您可能会注意到,我们的适配器使用presentListItem 作为其布局,我们在res/layout/presentListItem.xml 中将其定义为:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <TextView android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/row_id"
            />
    <TextView android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/name"
            />    
     <TextView android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/present"
            />
</LinearLayout>

我希望我说得清楚,并提防代码中的错误 - 我用一些快速的谷歌搜索来帮助我,大部分都是从内存中写出来的 :) 询问您是否需要更多帮助 ^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多