簡體   English   中英

在Android上使用ListView從SQLite數據庫查看數據

[英]View data from SQLite database using ListView on Android

我是Android開發的新手。 我設法將數據保存到SQLite數據庫。 現在,我想要的是在調用viewData()時查看這些數據。 我有viewData(),它將數據作為示例顯示為Toast。 現在,我需要這些數據以使用ListView在新活動中顯示,但是要顯示的數據數量取決於當前數據庫中的數據量,如果用戶保存了10個項目,那么我希望顯示所有10個項目起來 我該怎么做?

希望我的問題清楚。

提前致謝。

您可以使用ListView在布局中聲明它

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

     <ListView
          android:id="@+id/list"
          android:layout_height="wrap_content"
          android:layout_width="match_parent">
     </ListView>

</LinearLayout>

在您的活動中聲明globar var:

 ListView listView;

和onCreate

listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);

 // Assign adapter to ListView
    listView.setAdapter(adapter); 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
    public void onItemClick(AdapterView<?> parent, View v,
           int position, long id){

        // ListView Clicked item index
         int itemPosition     = position;

         // ListView Clicked item value
         String  itemValue    = (String) listView.getItemAtPosition(position);
    }

   });

datos可以是一個數組,您可以用從數據庫中提取的數據填充該數組,這是顯示它的最簡單方法。 如果要自定義listView,則可以創建自定義適配器,或者以其他方式替換listView的最新元素是ReciclerView。 希望對您有幫助

您可以使用SimpleCursorAdapter:

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView answerList=(ListView)findViewById(R.id.answerList);  
Cursor mCursor = getData();
startManagingCursor(mCursor);
// now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
    android.R.layout.two_line_list_item, 
    mCursor, // Pass in the cursor to bind to.
    // Array of cursor columns to bind to.
    new String[] {"_id", "answer"};

    // Parallel array of which template objects to bind to those
    // columns.
    new int[] { android.R.id.text1,android.R.id.text2 });

// Bind to our new adapter.
answerList.setAdapter(adapter);
}

private Cursor getData() { 
  String sq = "Select _id, answer from foo";
  Cursor c = db.rawQuery(sql);
  return c;

}

我將嘗試對此做一個深入的回答。

每當您想從數據庫中獲取並顯示數據列表時,都可以使用ListViewGridViewSpinner等。

您可以使用CursorAdapter來簡化查詢和顯示數據的工作。

這是它的基本視覺表示,

在此處輸入圖片說明

第1步

首先,您需要創建一個數據庫。 正如您的問題中提到的,很明顯,您知道如何創建數據庫並將一些數據放入其中。 因此,我不會深入探討它。

第2步

我們需要定義用於ListView各個項目的布局,並將其另存為res/layout/item_todo.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="match_parent"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/tvBody"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Study cursors"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/tvPriority"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="3"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

第三步

現在我們需要定義一個適配器。 在這里,我們使用CursorAdapter ,它將Cursor (您提供)轉換成Views(由布局定義)。

我們需要重寫兩種方法,即newViewbindView newView負責第一次使newViews膨脹,bindView負責將數據綁定到Views。

public class TodoCursorAdapter extends CursorAdapter {
  public TodoCursorAdapter(Context context, Cursor cursor) {
      super(context, cursor, 0);
  }

  // The newView method is used to inflate a new view and return it, 
  // you don't bind any data to the view at this point. 
  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
      return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false);
  }

  // The bindView method is used to bind all data to a given view
  // such as setting the text on a TextView. 
  @Override
  public void bindView(View view, Context context, Cursor cursor) {
      // Find fields to populate in inflated template
      TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
      TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
      // Extract properties from cursor
      String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
      int priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority"));
      // Populate fields with extracted properties
      tvBody.setText(body);
      tvPriority.setText(String.valueOf(priority));
  }
}

第四步

現在,您可以清楚地看到,構造函數需要ContextCursor 現在,我們需要查詢數據庫並將數據檢索到Cursor中並將其傳遞給適配器。

// TodoDatabaseHandler is a SQLiteOpenHelper class connecting to SQLite
TodoDatabaseHandler handler = new TodoDatabaseHandler(this);
// Get access to the underlying writeable database
SQLiteDatabase db = handler.getWritableDatabase();
// Query for items from the database and get a cursor back
Cursor todoCursor = db.rawQuery("SELECT  * FROM todo_items", null);

第5步

這是最后一步,我們需要實例化適配器並將ListView與適配器連接以填充數據。

// Find ListView to populate
ListView lvItems = (ListView) findViewById(R.id.lvItems);
// Setup cursor adapter using cursor from last step
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, todoCursor);
// Attach cursor adapter to the ListView 
lvItems.setAdapter(todoAdapter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM