查询特定列(包括图像)中的SQLite数据

问题描述 投票:-1回答:1

AuctionList活动:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.auction_list_activity);

    gridView = (GridView)findViewById(R.id.gridView);
    list = new ArrayList<>();
    adapter = new AuctionAdapter(this,R.layout.auction_items,list);
    gridView.setAdapter(adapter);

    //DATA QUERY HERE,TO QUERY NAME AND IMAGE

}
}

DatabaseHelper5:

public class DatabaseHelper5 extends SQLiteOpenHelper {
    private final static String DBNAME = "Auction";
    private final static int DBVERSION = 2;

    SQLiteDatabase mDB5;

    public final static String TBL_AUCTION = "auction";
    public final static String COL_AUCTION_ID = BaseColumns._ID;
    public final static String COL_AUCTION_NAME = "name";
    public final static String COL_AUCTION_DESCRIPTION = "description";
    public final static String COL_AUCTION_PRICE = "price";
    public final static String COL_AUCTION_DURATION = "duration";
    public final static String COL_AUCTION_IMAGE = "image";


    private String crt_tbl_auction = "CREATE TABLE IF NOT EXISTS " + TBL_AUCTION + "(" +
            COL_AUCTION_ID + " INTEGER PRIMARY KEY, " +
            COL_AUCTION_NAME + " TEXT, " +
            COL_AUCTION_DESCRIPTION + " TEXT, " +
            COL_AUCTION_PRICE + " TEXT, " +
            COL_AUCTION_DURATION + " TEXT, " +
            COL_AUCTION_IMAGE + " TEXT " +
            ")";

    public DatabaseHelper5(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB5 = this.getWritableDatabase();
    }

    public Cursor getData() {
//1st option:

        {
            String[] columns={COL_AUCTION_ID,COL_AUCTION_NAME,COL_AUCTION_IMAGE};

            return mDB5.query(TBL_AUCTION, columns, null, null, null, null, null);
        }


//Second option:

        SQLiteDatabase db = this.getReadableDatabase();

        String[] projection = {
                COL_AUCTION_NAME,
                COL_AUCTION_IMAGE
        };

        Cursor res = db.query(
                TBL_AUCTION,   // The table to query
                projection,             // The array of columns to return (pass null to get all)
                null, null, null, null, BaseColumns._ID + " DESC"            
        );

        return res;

    }

我想从我的数据库中查询分别为COL_AUCTION_NAME和COL_AUCTION_IMAGE的名称和图片的数据。

android sqlite gridview
1个回答
0
投票

你的代码应该是: -

public Cursor getData() {
//1st option:

    {
        String[] columns={COL_AUCTION_ID,COL_AUCTION_NAME,COL_AUCTION_IMAGE};

        return mDB5.query(TBL_AUCTION, columns, null, null, null, null, null);
    }
} //<<<<<<<<<< Added to make getData a method

//Second option:
public Cursor getDataV2() {

    SQLiteDatabase db = this.getReadableDatabase();
    String[] projection = {
            COL_AUCTION_NAME,
            COL_AUCTION_IMAGE
    };

    return db.query(
            TBL_AUCTION,   // The table to query
            projection,             // The array of columns to return (pass null to get all)
            null, null, null, null, BaseColumns._ID + " DESC"            
    );
}

在你的活动: -

  1. 为DatabaseHelper5对象定义一个类成员/变量,例如DatabaseHelper5 DBHlpr;
  2. 为Cursor定义一个类成员,例如Cursor csr;
  3. 使用以下内容替换// DATA QUERY HERE,QUERY NAME AND IMAGE DBhlpr = new DatabaseHelper5(this); Cursor csr = DBhlper.getDataV2(); 请注意,您应该在活动完成时关闭Cursor,因此可能会覆盖onDestroy方法以包含csr.close()

Limited Working Example

以下代码是基于SimpleCursorAdapter的有限工作示例(根据注释)。

main activity.Java

public class MainActivity extends AppCompatActivity {

    GridView gridView;
    DatabaseHelper5 mDBHlpr;
    Cursor mCsr;
    SimpleCursorAdapter mSCA;
    Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        gridView = (GridView) this.findViewById(R.id.gridView);
        mDBHlpr = new DatabaseHelper5(this);
        addSomeData(); // Add some data to DB if none
        manageGridView(); // Manage (setup) the GridView
    }

    /**
     * Should always close a Cursor when done with it
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCsr.close();
    }

    @Override
    protected void onResume() {
        super.onResume();
        manageGridView(); // always refresh
    }

    /**
     * Manage the GridView
     * Will setup the Gridview if not already setup
     * Otherwise will refresh the gridview (after changes have been made)
     * Note how onResume calls this, thus any changes in other activities
     * perhaps started via clicking an auction (see example click handling that Toasts info)
     */
    private void manageGridView() {
        mCsr = mDBHlpr.getDataV2();
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    mCsr,new
                    String[]{DatabaseHelper5.COL_AUCTION_NAME, DatabaseHelper5.COL_AUCTION_IMAGE},
                    new int[]{android.R.id.text1, android.R.id.text2},
                    0
            );
            gridView.setAdapter(mSCA);
            /**
             * Example of handling onItemClick (Toasts info about the clicked item)
             * Typically ID would be passed to another activity via an Intent extra
             */
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(
                            mContext,
                            "You clicked on Auction :-" + mCsr.getString(mCsr.getColumnIndex(DatabaseHelper5.COL_AUCTION_NAME)) +
                                    " Image :- " + mCsr.getString(mCsr.getColumnIndex(DatabaseHelper5.COL_AUCTION_IMAGE)) +
                                    " ID :- " + String.valueOf(id),
                            Toast.LENGTH_SHORT
                    ).show();
                }
            });
        } else {
            mSCA.swapCursor(mCsr);
        }
    }

    /**
     * Add some testing data if none exists
     */
    private void addSomeData() {
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper5.TBL_AUCTION) < 1) {
            mDBHlpr.addAuction("Auction1","The first Auction","100","2","image1 as a string");
            mDBHlpr.addAuction("Auction2","The second Auction","100","2","image2 as a string");
            mDBHlpr.addAuction("Auction4","The thirs Auction","100","2","image3 as a string");
        }
    }
}

database helper5.Java

public class DatabaseHelper5 extends SQLiteOpenHelper {
    private final static String DBNAME = "Auction";
    private final static int DBVERSION = 2;

    SQLiteDatabase mDB5;

    public final static String TBL_AUCTION = "auction";
    public final static String COL_AUCTION_ID = BaseColumns._ID;
    public final static String COL_AUCTION_NAME = "name";
    public final static String COL_AUCTION_DESCRIPTION = "description";
    public final static String COL_AUCTION_PRICE = "price";
    public final static String COL_AUCTION_DURATION = "duration";
    public final static String COL_AUCTION_IMAGE = "image";


    private String crt_tbl_auction = "CREATE TABLE IF NOT EXISTS " + TBL_AUCTION + "(" +
            COL_AUCTION_ID + " INTEGER PRIMARY KEY, " +
            COL_AUCTION_NAME + " TEXT, " +
            COL_AUCTION_DESCRIPTION + " TEXT, " +
            COL_AUCTION_PRICE + " TEXT, " +
            COL_AUCTION_DURATION + " TEXT, " +
            COL_AUCTION_IMAGE + " TEXT " +
            ")";

    public DatabaseHelper5(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB5 = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(crt_tbl_auction);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public long addAuction(String name, String description, String price, String duration,  String image) {
        ContentValues cv = new ContentValues();
        cv.put(COL_AUCTION_NAME,name);
        cv.put(COL_AUCTION_DESCRIPTION,description);
        cv.put(COL_AUCTION_PRICE,price);
        cv.put(COL_AUCTION_DURATION,duration);
        cv.put(COL_AUCTION_IMAGE,image);
        return mDB5.insert(TBL_AUCTION,null,cv);
    }

    public Cursor getData() {
            String[] columns = {COL_AUCTION_ID, COL_AUCTION_NAME, COL_AUCTION_IMAGE};
            return mDB5.query(TBL_AUCTION, columns, null, null, null, null, null);
    }

    //Second option:
    public Cursor getDataV2() {

        String[] projection = {
                COL_AUCTION_ID,
                COL_AUCTION_NAME,
                COL_AUCTION_IMAGE
        };
        return mDB5.query(
                TBL_AUCTION,   // The table to query
                projection,             // The array of columns to return (pass null to get all)
                null, null, null, null, BaseColumns._ID + " DESC"
        );
    }
}

结果: -

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.