java - 更改依赖于 Spinner 行的 SQLite 查询

标签 java android sqlite listview spinner

我正在从 SQLite 数据库获取信息并通过 ListView 显示它。在 ListView 上方,我有一个微调器,其中包含在 XML 中创建的各种选项:

<Spinner
        android:id="@+id/categoryChoose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:entries="@array/catergory_arrays" />

微调值数组:

<string-array name="catergory_arrays">
        <item>Select category here:</item>
        <item>Fridge / Freezer</item>
        <item>Canned Food</item>
        <item>Fruit</item>
        <item>Vegetable</item>
    </string-array>

根据微调器的位置,我想设置一个不同的查询,然后显示在 ListView 中。当前代码:

显示数据库信息的类(CurrentItems):

package com.example.fooditemmonitor;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;

public class CurrentItems extends Activity {

    ItemDatabase db;
    Context context;
    Button addButton, editButton;
    ListView listView;
    int spinnerID;

    // the table that displays the data

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.current_inventory);

        db = new ItemDatabase(this);

        // create references and listeners for the GUI interface
        setupViews();

        // make the buttons clicks perform actions
        addButtonListeners();

        displaySearch();

    }

    private void setupViews() {
        // bring up current database items
        listView = (ListView) findViewById(R.id.dbListView);

        // THE BUTTONS
        addButton = (Button) findViewById(R.id.scanCurrent);
        editButton = (Button) findViewById(R.id.editItemCurrent);
    }

    private void addButtonListeners() {

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CurrentItems.this, AddItem.class));

            }
        });

        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CurrentItems.this, EditItems.class));

            }
        });
    }

    public int getSelectedItemPosition() {
        Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
        spinnerID = selectCat.getSelectedItemPosition();
        return spinnerID;
    }

    private void displaySearch() {
        // TODO Auto-generated method stub
        Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
        spinnerID = selectCat.getSelectedItemPosition();
        String catSelected;
        final ArrayList<String> items = new ArrayList<String>();
        final ArrayAdapter<String> itemArray;
        itemArray = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items);

        {
            if (getSelectedItemPosition() == 0) {
                ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
                for (int position = 0; position < data.size(); position++) {
                    ArrayList<Object> row = data.get(position);
                    items.add("\nDate:  " + row.get(0).toString()
                            + "\nTitle:  " + row.get(1).toString()
                            + "\nQuantity:  "
                            + Integer.parseInt(row.get(2).toString())
                            + "\nCategory:" + row.get(3).toString() + "\n");
                    itemArray.notifyDataSetChanged();
                    listView.setAdapter(itemArray);
                }
            } else if (getSelectedItemPosition() == 1) {
                catSelected = "Fridge";
                ArrayList<ArrayList<Object>> data = db
                        .getCategoryOfArrays(catSelected);
                for (int position = 0; position < data.size(); position++) {
                    ArrayList<Object> row = data.get(position);
                    items.add("\nDate:  " + row.get(0).toString()
                            + "\nTitle:  " + row.get(1).toString()
                            + "\nQuantity:  "
                            + Integer.parseInt(row.get(2).toString())
                            + "\nCategory:" + row.get(3).toString() + "\n");
                    itemArray.notifyDataSetChanged();
                    listView.setAdapter(itemArray);
                }
            } else if (getSelectedItemPosition() == 2) {
                catSelected = "Can";
                ArrayList<ArrayList<Object>> data = db
                        .getCategoryOfArrays(catSelected);
                for (int position = 0; position < data.size(); position++) {
                    ArrayList<Object> row = data.get(position);
                    items.add("\nDate:  " + row.get(0).toString()
                            + "\nTitle:  " + row.get(1).toString()
                            + "\nQuantity:  "
                            + Integer.parseInt(row.get(2).toString())
                            + "\nCategory:" + row.get(3).toString() + "\n");
                    itemArray.notifyDataSetChanged();
                    listView.setAdapter(itemArray);
                }
            } else if (getSelectedItemPosition() == 3) {
                catSelected = "Fruit";
                ArrayList<ArrayList<Object>> data = db
                        .getCategoryOfArrays(catSelected);
                for (int position = 0; position < data.size(); position++) {
                    ArrayList<Object> row = data.get(position);
                    items.add("\nDate:  " + row.get(0).toString()
                            + "\nTitle:  " + row.get(1).toString()
                            + "\nQuantity:  "
                            + Integer.parseInt(row.get(2).toString())
                            + "\nCategory:" + row.get(3).toString() + "\n");
                    itemArray.notifyDataSetChanged();
                    listView.setAdapter(itemArray);
                }
            } else if (getSelectedItemPosition() == 4) {
                catSelected = "Vegetable";
                ArrayList<ArrayList<Object>> data = db
                        .getCategoryOfArrays(catSelected);
                for (int position = 0; position < data.size(); position++) {
                    ArrayList<Object> row = data.get(position);
                    items.add("\nDate:  " + row.get(0).toString()
                            + "\nTitle:  " + row.get(1).toString()
                            + "\nQuantity:  "
                            + Integer.parseInt(row.get(2).toString())
                            + "\nCategory:" + row.get(3).toString() + "\n");
                    itemArray.notifyDataSetChanged();
                    listView.setAdapter(itemArray);
                }
            } else {
                ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
                for (int position = 0; position < data.size(); position++) {
                    ArrayList<Object> row = data.get(position);
                    items.add("\nDate:  " + row.get(0).toString()
                            + "\nTitle:  " + row.get(1).toString()
                            + "\nQuantity:  "
                            + Integer.parseInt(row.get(2).toString())
                            + "\nCategory:" + row.get(3).toString() + "\n");
                    itemArray.notifyDataSetChanged();
                    listView.setAdapter(itemArray);
                }

            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

项目数据库:

package com.example.fooditemmonitor;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public final class ItemDatabase {

    // the Activity or Application that is creating an object from this class.
    Context context;

    // a reference to the database used by this application/object
    private SQLiteDatabase db;

    // These constants are specific to the database.
    private final String DATABASE_NAME = "ItemDatabase.sqlite";
    private final int DATABASE_VERSION = 5;

    // These constants are specific to the database table.
    private final String TABLE_NAME = "foodItems";
    private final String COLUMN_NAME_ENTRY_ID = "entryid";
    private final String COLUMN_NAME_BARCODE = "barcode";
    private final String COLUMN_NAME_TITLE = "title";
    private final String COLUMN_NAME_QUANTITY = "quantity";
    private final String COLUMN_NAME_DATE = "date";
    private final String COLUMN_NAME_CATEGORY = "category";
    String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
    String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
            + COLUMN_NAME_ENTRY_ID
            + " integer primary key autoincrement not null," + COLUMN_NAME_DATE
            + " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
            + " text," + COLUMN_NAME_QUANTITY + " int," + COLUMN_NAME_CATEGORY + " text" + ");";

    public ItemDatabase(Context context) {
        this.context = context;

        // create or open the database
        ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
        this.db = helper.getWritableDatabase();
    }

    public void addRow(String rowStringOne, String rowStringTwo,
            String rowStringThree, String rowStringFour, int rowIntFive) {
        // this is a key value pair holder used by android's SQLite functions
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME_DATE, rowStringOne);
        values.put(COLUMN_NAME_BARCODE, rowStringTwo);
        values.put(COLUMN_NAME_TITLE, rowStringThree);
        values.put(COLUMN_NAME_CATEGORY, rowStringFour);
        values.put(COLUMN_NAME_QUANTITY, rowIntFive);

        // ask the database object to insert the new data
        try {
            db.insert(TABLE_NAME, null, values);
        } catch (Exception e) {
            Log.e("DB ERROR", e.toString());
            e.printStackTrace();
        }
    }


    public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
            String rowStringThree, int rowIntFour) {
        // this is a key value pair holder used by android's SQLite functions
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME_DATE, rowStringOne);
        values.put(COLUMN_NAME_BARCODE, rowStringTwo);
        values.put(COLUMN_NAME_TITLE, rowStringThree);
        values.put(COLUMN_NAME_QUANTITY, rowIntFour);

        // ask the database object to update the database row of given rowID
        try {
            db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
                    null);
        } catch (Exception e) {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }
    }

    public void deleteRow(long rowID) {
        // ask the database manager to delete the row of given id
        try {
            db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
            getAllRowsAsArrays();
        } catch (Exception e) {
            Log.e("DB ERROR", e.toString());
            e.printStackTrace();
        }
    }

    public ArrayList<ArrayList<Object>> getCategoryOfArrays(String category) {
        // create an ArrayList that will hold all of the data collected from
        // the database.
        ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
        // this is a database call that creates a "cursor" object.
        // the cursor object store the information collected from the
        // database and is used to iterate through the data.
        Cursor cursor;

        try {
            // ask the database object to create the cursor.

            cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
                    COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, COLUMN_NAME_CATEGORY + "='" + category + "'", null,
                    null, null, COLUMN_NAME_TITLE + " ASC");

            // move the cursor's pointer to position zero.
            cursor.moveToFirst();

            // if there is data after the current cursor position, add it to the
            // ArrayList.
            while (cursor.moveToNext()) {
                // your content

                ArrayList<Object> dataList = new ArrayList<Object>();

                dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE)));
                dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
                dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));
                dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CATEGORY)));

                dataArrays.add(dataList);
            }
        } catch (SQLException e) {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }
        // return the ArrayList that holds the data collected from the database.
        return dataArrays;
    }

    public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
        // create an ArrayList that will hold all of the data collected from
        // the database.
        ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
        // this is a database call that creates a "cursor" object.
        // the cursor object store the information collected from the
        // database and is used to iterate through the data.
        Cursor cursor;

        try {
            // ask the database object to create the cursor.

            cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
                    COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY, COLUMN_NAME_CATEGORY }, null, null,
                    null, null, COLUMN_NAME_TITLE + " ASC");

            // move the cursor's pointer to position zero.
            cursor.moveToFirst();

            // if there is data after the current cursor position, add it to the
            // ArrayList.
            while (cursor.moveToNext()) {
                // your content

                ArrayList<Object> dataList = new ArrayList<Object>();

                dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DATE)));
                dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
                dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));
                dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_CATEGORY)));

                dataArrays.add(dataList);
            }
        } catch (SQLException e) {
            Log.e("DB Error", e.toString());
            e.printStackTrace();
        }
        // return the ArrayList that holds the data collected from the database.
        return dataArrays;
    }

    public class ItemDatabaseHelper extends SQLiteOpenHelper {
        public ItemDatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        public void onCreate(SQLiteDatabase db) {
            // execute the query string to the database.
            db.execSQL(SQL_CREATE_TABLE);
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // This database is only a cache for online data, so its upgrade
            // policy is to simply to discard the data and start over
            db.execSQL(SQL_DELETE_ENTRIES);
            onCreate(db);
        }
    }
}

已经测试了 getCategoryOfArrays() 并且它有效。当前代码不会返回任何错误,但 Spinner 操作不会更改 ListView 内容。

我们将不胜感激所有帮助!

最佳答案

您的方法 displaySearch() 仅在 Activity 创建时、当微调器位于零位置时调用一次。在 onCreate 中(可能在您的 addButtonListeners() 方法中)在微调器上设置值更改时的监听器。当它出现时,再次调用displaySearch()。

Spinner selectCat = (Spinner) findViewById(R.id.categoryChoose);
selectCat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
    {
        displaySearch();
    }
    public void onNothingSelected(AdapterView<?> parent)
    {
        // Do nothing
    }
});

关于java - 更改依赖于 Spinner 行的 SQLite 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319769/

相关文章:

android - 此界面的最佳父级布局?

android - 从一项 Activity 移至另一项 Activity 时,键盘会自动弹出

c# - UWP - 在特定条件下在 ListView 中显示数据库

java - GWT webappcreator 创建 Maven 项目 : the source attachment does not contain the source for the file URLClassPath. 类

java - 如何使 JLable 在鼠标悬停时可见和半透明(几乎不可见)

java - 使用 Java 客户端 API 在 marklogic 中创建或添加集合

optimization - SQLite 查询优化(子查询和连接)

java - Flutter 应用程序在启动时和通过 java.lang.ClassNotFoundException 崩溃

java - JsonObject 构建 Stackoverflow 错误

android - 无法从存储库类调用(无法解析)来自 SQLiteOpenHelper 类的同步 getinstance 方法