So I have an imageArray it finds the 17 fields. But will not populate them to an Array at the end. It says the image array is empty. My debugger shows that the log is populated with 17 fields from the database. But the array fails to include them #
imageArray.add(rn);
Java onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myreceipts);
ReceiptsOperations ro = new ReceiptsOperations(this);
List<Receipt> receipts = ro.getReceipts();
for(Receipt rn : receipts){
String log = "RECEIPTID:" + rn.getReceiptID() + "RECEIPTURI:" + rn.getReceiptURI();
Log.d("Result: ", log);
imageArray.add(rn);
}
Receipt List initialised
public List<Receipt>getReceipts() {
// This code will retrieve all images from database.
List<Receipt> receiptList = new ArrayList<Receipt>();
String selectQuery = "SELECT* FROM receipts_table ORDER BY receipt_ID";
// Check all rows and add to list.
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,null);
if(cursor.moveToFirst())
{
do
{
Receipt receipt = new Receipt();
receipt.setReceiptID(new String(cursor.getString(0)));
receipt.setReceiptURI(new String(cursor.getString(2)));
receiptList.add(receipt);
}
while(cursor.moveToNext());
}
db.close();
return receiptList;
}
Related
I want to make a to-do list app, and I wanted to delete the item in the list by tapping the checkbox.
I tried to make a "deleteTask"(as you see in the code) method in the database class. Also, you can see the "populateListView"
method, it provides data from the database into listview, I use it to refresh after each time a task got deleted from the database.
public void deleteTask(String task) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL2 , new String[]{task});
}
public void populateListView() {
try {
mDataBaseHelper = new DataBaseHelper(MainActivity.this);
data = mDataBaseHelper.getData();
mArrayList = new ArrayList<>();
if (data.getCount() != 0) {
while (data.moveToNext()) {
mArrayList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter(MainActivity.this, R.layout.list_items, R.id.checkBox, mArrayList);
list = (ListView) findViewById(R.id.myListId);
list.setAdapter(listAdapter);
}
mDataBaseHelper.close();
} else {
toastMessage("the Database is empty");
}
}catch(Exception e){
Log.e(TAG, "populateListView: error"+e.getStackTrace() );
}
}
when the application gets started, I tapped the item that I want to delete, but I see that the items start to be deleted by order from above!
one by one each time I tapped any checkbox.
You want :-
public void deleteTask(String task) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL2 + "=?" , new String[]{task});
}
If you weren't trapping the error by using the try/catch using db.delete(TABLE_NAME, COL2 , new String[]{task}); you would get an exception along the lines of :-
java.lang.IllegalArgumentException: Too many bind arguments. 1 arguments were provided but the statement needs 0 arguments.
However
Assuming that the issue with deleting rows sequentially rather than according to the checked item(s), is likely due to the handling of the checked items. However, as the code for this is not provided it would only be guess work to know where in the code you are going wrong.
One thing is that you do not want to be creating a new listadapter instance every time you populate the ListView.
As a hint to handling a ListView, but deleting an item when it is long-clicked based upon the COL2 value, perhaps consider the following which has been based upon your code (but deletes according to long clicking an item) :-
public void populateLisView() {
mDataBaseHelper = new DataBaseHelper(this); //<<<<<<<<<< NOTE 1
list = (ListView) this.findViewById(R.id.myListId); //<<<<<<<<<< NOTE 1
data = mDataBaseHelper.getData(); //<<<<<<<<<< get the data to be listed
if (listadapter == null) { //<<<<<<<<<< Only need to instantiate one adapter when it has not bee instantiated
listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data); // for convenience using a stock layout
list.setAdapter(listadapter);
//<<<<<<<<<<< add the onItemLongClick listener
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
mDataBaseHelper.deleteTaskByCol2(data.get(position)); //<<<<<<<<<< gets the value of the item according to it's position in the list
populateLisView(); //<<<<<<<<<< as the item has been deleted then refresh the Listview
return true; // flag the event as having been handled.
}
});
//<<<<<<<<<<< If the Adapter has been instantiated then refresh the ListView's data
} else {
listadapter.clear(); // Clear the data from the adapter
listadapter.addAll(data); // add the new changed data to the adapter
listadapter.notifyDataSetChanged(); // tell the adapter that the data has changed
}
}
NOTE 1
you would typically instantiate these variables once.
Check the comments
You may wish to edit your question to include how you are handling the check events.
The Full Working Example
DatabaseHelper.java
Note this may differ from yours a little
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TABLE_NAME = "mytable";
public static final String COL1 = "col1";
public static final String COL2 = "col2";
SQLiteDatabase db;
private static final String CRT_MYTABLE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"(" +
COL1 + " TEXT, " +
COL2 + " TEXT" +
")";
public DataBaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CRT_MYTABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addMytableRow(String col1, String col2) {
ContentValues cv = new ContentValues();
cv.put(COL1,col1);
cv.put(COL2,col2);
return db.insert(TABLE_NAME,null,cv);
}
public ArrayList<String> getData() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL2)));
}
csr.close();
return rv;
}
public void deleteTaskByCol2(String task) {
db.delete(TABLE_NAME,COL2 + "=?",new String[]{task});
}
}
MainActivity.java
i.e. an example activity that is based upon your code, but according to the above :-
public class MainActivity extends AppCompatActivity {
DataBaseHelper mDataBaseHelper;
ArrayList<String> data;
ListView list;
ArrayAdapter<String> listadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addSomeTestData();
populateLisView();
}
private void example001() {
}
public void populateLisView() {
mDataBaseHelper = new DataBaseHelper(this);
list = (ListView) this.findViewById(R.id.myListId);
data = mDataBaseHelper.getData();
if (listadapter == null) {
listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,android.R.id.text1,data);
list.setAdapter(listadapter);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//mDataBaseHelper.deleteTaskWrong(data.get(position)); // ooops
mDataBaseHelper.deleteTaskByCol2(data.get(position));
populateLisView();
return true;
}
});
} else {
listadapter.clear();
listadapter.addAll(data);
listadapter.notifyDataSetChanged();
}
}
private void addSomeTestData() {
if (mDataBaseHelper == null) {
mDataBaseHelper = new DataBaseHelper(this);
}
if (DatabaseUtils.queryNumEntries(mDataBaseHelper.getWritableDatabase(),DataBaseHelper.TABLE_NAME) > 0) return;
mDataBaseHelper.addMytableRow("Test1","Test1");
mDataBaseHelper.addMytableRow("Test2","Test2");
mDataBaseHelper.addMytableRow("Test3","Test3");
mDataBaseHelper.addMytableRow("Test4","Test4");
}
}
Note AddSomeTestData adds some data for testing/demonstration.
Result
When first run :-
After LongClicking Test 2
i.e. the long clicked item has been removed (from the list and the database) and the list refreshed.
Try to replace
db.delete(TABLE_NAME, COL2 , new String[]{task});
By
db.delete(TABLE_NAME, COL2 + " = ?" , new String[]{task});
I am setting a new activity named Dispatch Report, which has two Spinners: CustomerSpinner and LotSpinner.
LotSpinner shows all Lots in Dispatch Table instead of showing only those Lots which are related to the Customer selected in the first Spinner.
I have fetched CustomerSpinner Value from Dispatch Table. In LotSpinner also fetched Lot numbers from Dispatch Table, but not Filtered according to customer selection.
DispatchReportActivity.Java
// Fetching customer from dispatch table
private void loadCustomerNameDispatch() {
DatabaseHelper db = new DatabaseHelper( getApplicationContext() );
List<String> lables1 = db.getFirmNAmeMoveStock();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables1);
dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinCustomer.setAdapter(dataAdapter);
spinCustomer.setOnItemSelectedListener(this);
}
// Fetching lot from dispatch table
private void loadLotbyCustomerDispatch() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getLotbyCustomer();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinLotbyCustomer.setAdapter(dataAdapter);
}
DATABASEHELPER.Java
//Get firm name in Dispatch Stock Report screen
public List < String > getFirmNAmeMoveStock() {
List < String > labels = new ArrayList < String > ();
// Select all query
String selectQuery = "SELECT * FROM " + Table_Inventory;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(3));
Set < String > set = new HashSet < >(labels);
labels.clear();
labels.addAll(set);
} while ( cursor . moveToNext ());
}
// Closing connection
cursor.close();
db.close();
// Returning lables
return labels;
}
// Method to get Lot No. in Dispatch Stock Report Activity
public List < String > getLotbyCustomer() {
List < String > labels1 = new ArrayList < String > ();
// Select all query
String selectQuery = "SELECT * FROM " + Table_StockDispatch;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels1.add(cursor.getString(4));
Set < String > set = new HashSet < >(labels1);
labels1.clear();
labels1.addAll(set);
} while ( cursor . moveToNext ());
}
// Closing connection
cursor.close();
db.close();
// Returning lables
return labels1;
}
There will be multiple customers, and each customer could have multiple Lots, so I want the second spinner to show only those Lots which are relevant to the customer selected in the first Spinner.
I'd suggest utilising Cursor's and Cursor adapters which can make matter simpler as :-
there is no need for intermediate arrays (one of your issues is that String arrays do not provide sufficient information)
CursorAdapters are designed to handle id (albiet a requirement that these exists in the Cursor with the column name _id (see the use of BaseColumns._ID below)).
The following is a basic example of related spinners based loosely upon your requirements.
First the DatbaseHelper DatabaseHelper.java
Two tables are defined/created Customers and Lots, methods to add data for each exist as do methods to extract a list from each of the tables. The lots extracted are based upon the customer to which they reference/belong to/associate with.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TBL_CUSTOMER = "customer";
public static final String TBL_LOT = "lot";
public static final String COL_CUSTOMER_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
public static final String COL_CUSTOMER_NAME = "customer_name";
public static final String COL_LOT_ID = BaseColumns._ID; //<<<<<<<<<< column name is _id (needed for Cursor Adapter)
public static final String COL_LOT_NAME = "lot_name";
public static final String COL_LOT_CUSTOMERREFERENCE = "customer_refererence";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase(); //<<<<<<<<<< get the database connection (force create when constructing helper instance)
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_customer_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_CUSTOMER + "(" +
COL_CUSTOMER_ID + " INTEGER PRIMARY KEY, " +
COL_CUSTOMER_NAME + " TEXT UNIQUE " +
")";
String crt_lot_table_sql = "CREATE TABLE IF NOT EXISTS " + TBL_LOT + "(" +
COL_LOT_ID + " INTEGER PRIMARY KEY, " +
COL_LOT_NAME + " TEXT, " +
COL_LOT_CUSTOMERREFERENCE + " INTEGER " +
/*?????????? OPTIONAL IF FOREIGN KEYS ARE TURNED ON
"REFERENCES " + TBL_CUSTOMER + "(" +
COL_CUSTOMER_ID +
")" +
*/
")";
db.execSQL(crt_customer_table_sql);
db.execSQL(crt_lot_table_sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long addCustomer(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_CUSTOMER_NAME,name);
return mDB.insert(TBL_CUSTOMER,null,cv);
}
public long addLot(String name, long customer_reference) {
ContentValues cv = new ContentValues();
cv.put(COL_LOT_NAME,name);
cv.put(COL_LOT_CUSTOMERREFERENCE,customer_reference);
return mDB.insert(TBL_LOT,name,cv);
}
public Cursor getCustomers() {
return mDB.query(TBL_CUSTOMER,null,null,null,null,null,COL_CUSTOMER_NAME);
}
public Cursor getLotsPerCustomer(long customer_id) {
String whereclause = COL_LOT_CUSTOMERREFERENCE + "=?";
String[] whereargs = new String[]{String.valueOf(customer_id)};
return mDB.query(TBL_LOT,null,whereclause,whereargs,null,null,COL_LOT_NAME);
}
}
Note the above is pretty straight-forward. However, it would obviously need to be adapted to suit you App.
The second code is the activity that utilises the above and incorporates the 2 linked/related spinners where the selectable Lots are as per those lots associated with the currently selected customer.
The layout used for the activity is very basic, it just has two spinners. The spiners use the stock Simple_List_Item_2 layout (2 has been used to allow the all important ID's to be viewed (typically the user would not be shown the ID's)).
In short whenever a selection is made in the Customer spinner the Lot spinner is managed (setup or refreshed) based upon the customer id which is used to select the related/reference lots.
public class MainActivity extends AppCompatActivity {
Context mContext;
DatabaseHelper mDBHlpr;
SimpleCursorAdapter mCustomerSCA, mLotSCA;
Spinner mCustomerList, mLotList;
Cursor mCustomers, mLots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mDBHlpr = new DatabaseHelper(this);
mCustomerList = this.findViewById(R.id.customer_list);
mLotList = this.findViewById(R.id.lot_list);
addTestingDataIfNoData(); //Go and add some testing data if there is none
manageCustomerSpinner();
}
private void manageCustomerSpinner() {
mCustomers = mDBHlpr.getCustomers();
if (mCustomerSCA == null) {
mCustomerSCA = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mCustomers,
new String[]{
DatabaseHelper.COL_CUSTOMER_NAME,
DatabaseHelper.COL_CUSTOMER_ID
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mCustomerList.setAdapter(mCustomerSCA);
mCustomerList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageLotSpinner(id); //<<<<<<<<<< WHENEVER CUSTOMER IS SELECTED THE LOT SPINNER IS MANAGED >>>>>>>>>>
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mCustomerSCA.swapCursor(mCustomers);
}
}
private void manageLotSpinner(long id) {
mLots = mDBHlpr.getLotsPerCustomer(id);
if (mLotSCA == null) {
mLotSCA = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
mLots,
new String[]{
DatabaseHelper.COL_LOT_NAME,
DatabaseHelper.COL_LOT_ID
},
new int[]{
android.R.id.text1,
android.R.id.text2
},
0
);
mLotList.setAdapter(mLotSCA);
} else {
mLotSCA.swapCursor(mLots);
}
}
private void addTestingDataIfNoData() {
if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseHelper.TBL_CUSTOMER) < 1) {
mDBHlpr.addCustomer("Fred");
mDBHlpr.addCustomer("Mary");
mDBHlpr.addCustomer("Sue");
mDBHlpr.addCustomer("Alan");
mDBHlpr.addLot("Lot001",2); // Lot for mary
mDBHlpr.addLot("Lot002",1); // Lot for fred
mDBHlpr.addLot("Lot003",4); // Lot for ala
mDBHlpr.addLot("Lot004",3); // Lot for sue
mDBHlpr.addLot("Lot005",3); // Lot for sue
mDBHlpr.addLot("Lot006",3); // Lot for use
mDBHlpr.addLot("Lot007",2); // Lot for mary
mDBHlpr.addLot("Lot008",2); // Lot for mary
mDBHlpr.addLot("Lot009",2); // Lot for mary
mDBHlpr.addLot("Lot0010",2); // Lot for mary
mDBHlpr.addLot("Lot0020",1); // Lot for Fred
mDBHlpr.addLot("Lot00130",4); // Lot for Alan
mDBHlpr.addLot("Lot00130",3); // Lot for Sue
}
}
}
Result Example
Initial
Alan is initial selection due to sort order
After Selecting Mary
Note Lot names, as used, are not really suited to sorting
My app contains a series of long texts, and I'd like the user to be able to return to them at the point where they left off if they leave that View.
I've adapted the code from this answer for a ListView. The first Log is fine, but the second does not, which suggests to me that state is null.
Here's my StoryBodyActivity:
public class StoryBodyActivity extends AppCompatActivity {
private TextView storyBodyTextView;
private ScrollView storyBodyScrollView;
Parcelable state;
#Override
public void onPause() {
Log.d("pause", "saving listview state # onPause");
state = storyBodyTextView.onSaveInstanceState();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_body);
Bundle extras = getIntent().getExtras();
String story = extras.getString("story");
setTitle(story);
storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);
DatabaseHelper db = new DatabaseHelper(this);
String storyBody = db.getStoryBody(story);
storyBodyTextView.setText(Html.fromHtml(storyBody));
if(state != null) {
Log.d("pause", "trying to restore textview state..");
storyBodyTextView.onRestoreInstanceState(state);
}
}
}
I also need to ensure that the position of each individual long text is saved.
Here's the DatabaseHelper to show where the data is coming from:
public String getStoryBody(String story) {
Log.i("test", "hello");
String storyBody = "";
// Select all query
String selectQuery = "SELECT * FROM " + BOOKS + " WHERE title = '" + story + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
storyBody = cursor.getString(4);
} while (cursor.moveToNext());
}
return storyBody;
}
This is my code and my CarsDbHelper, CarsContract for my CarsEntry.
It has no problems, but I am unsure from here on how to use information I have put in a Sqlite database.
String current_car_name = "TOYOTA YARIS";
String current_car_colour = "GREY";
int current_car_age = 3;
CarsDbHelper mDbHelper = new CarsDbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CarsEntry.COLUMN_NAME,current_car_name);
values.put(CarsEntry.COLUMN_COLOUR,current_car_colour);
values.put(CarsEntry.COLUMN_AGE,current_car_age);
long newRowId = db.insert(CarsEntry.TABLE_NAME, null, values);
}
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
CarsEntry.COLUMN_NAME,
CarsEntry.COLUMN_COLOUR,
CarsEntry.COLUMN_AGE
};
public void button (View view) {
String selection = CarsEntry.COLUMN_NAME + " = ?";
String[] selectionArgs = {current_car_name};
TextView car_name = (TextView) findViewById(R.id.name);
car_name.setText();
TextView car_colour = (TextView) findViewById(R.id.colour);
car_colour.setText();
TextView car_age = (TextView) findViewById(R.id.age);
car_age.setText();
}
I am still a bit confused on how to input this data into my TextViews.
You type in them... Did you mean get values out of them?
First off, the purpose of the "helper" object is to help you not expose a SQLiteDatabase object.
Make a Car class and an addCar(Car car) method in your helper.
public long addCar(Car car) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CarsEntry.COLUMN_NAME,car.getName());
values.put(CarsEntry.COLUMN_COLOUR,car.getColour());
values.put(CarsEntry.COLUMN_AGE,car.getAge());
long newRowId = db.insert(CarsEntry.TABLE_NAME, null, values);
return newRowId;
}
Then, in the Activity, you need to set the helper in onCreate, not outside
CarsDbHelper mDbHelper;
TextView mCarName, mCarColour, mCarAge;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCarName = (TextView) findViewById(R.id.name);
mCarColour = (TextView) findViewById(R.id.colour);
mCarAge = (TextView) findViewById(R.id.age);
mDbHelper = new CarsDbHelper(this); // Moved in here
}
public void button (View view) {
String name = mCarName.getText().toString();
String colour = mCarColour.getText().toString();
String age = mCarAge.getText().toString();
Car c = new Car(name, colour, Integer.parseInt(age));
mDbHelper.addCar(c); // This is the helper method
}
If you want to get data out of the database, you need a ListView and an Adapter (such as CursorAdapter)
If you would like to not mess with the details of raw SQLite, see the Room Persistence library
First, you should create db instance in onCreate Function.
Cursor cursor = db.query(
TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Copied from Android Dev Site.
You will get cursor, iterate through it as follows:
if(!cursor.moveToFirst())
//No Data
//cache columns indexes in integers
int idIndex = cursor.getColumnIndex("id");
...
while(cursor.moveToNext()){
String id = cursor.getString(id); //Same for boolean, Int, long, etc.
...
}
//Never forget to close cursor
cursor.close();
how to retrieve specific data by their Id and display them in textview? instead of retrieving the data and display all the data in listview. please help!
public class KaikaiProfileActivity extends ListActivity {
private Cursor animals;
private MyDatabase db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new MyDatabase(this);
animals = db.getAnimals(); // you would not typically call this on the main thread
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
animals,
new String[] {"animalName","animalPersonality"},
new int[] {android.R.id.text1, android.R.id.text2});;
getListView().setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
animals.close();
db.close();
}
// retrieve all data
how to retrieve the data from specific row?
public Cursor getAnimals() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"0_id", "animalName", "animalInfo","ImageName","animalGender","animalDOB",
"animalDOB", "animalBirthPlace", "animalPersonality", "animalFeatures", "animalFood", "animalPastTime"
};
String sqlTables = "AnimalInfo";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
c.moveToFirst();
return c;
}
use c.moveToPosition(int index) in place of c.moveToFirst() to get record at that particular index
For example, if you want to return first record, use c.moveToPosition(0), for second record use c.moveToPosition(1) and so on
If you want to retrieve by column value then use qb.appendWhere("<colname>=<value>") ;