Ваш код должен быть: -
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"
);
}
В тебе Активность: -
- определить член / переменную класса для объекта DatabaseHelper5, например,
DatabaseHelper5 DBHlpr;
определить член класса для курсора, например Cursor csr;
используйте следующее, чтобы заменить // ДАННЫЕ, ЗАПРОСИТЕ ЗДЕСЬ, НАИМЕНОВАТЬ И ИЗОБРАЖИТЬ
DBhlpr = new DatabaseHelper5(this);
Cursor csr = DBhlper.getDataV2();
- Обратите внимание, что вы должны закрыть курсор по окончании действия, поэтому, возможно, переопределите метод onDestroy , чтобы включить
csr.close()
.
Ограниченный рабочий пример
Следующий код представляет собой ограниченный рабочий пример на основе SimpleCursorAdapter (согласно комментариям).
MainActivity.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");
}
}
}
DatabaseHelper5.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"
);
}
}
Результат: -