How to retrieve data from specific row SQLiteAssetHelper - java

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>") ;

Related

SwipeToDeleteCallback - Not working as espected

I'm implementing swipe to delete in RecyclerView but I've notice that is not working as espected.
When the app launch for first time, items are collected from the db and polulated, when I swipe works fine. After thar if I add an item to the list (also to the db) I'm recovering all items again from the db and recreating the adapter, but if I swipe one element, the size of the adapter in SwipeToDeleteCallback doesn't match with the database items, so I'm getting an IndexOutOfBounds error.
Can you help me? I don't know what's wrong...
public SwipeToDeleteCallback(RecyclerviewAdapter adapter) {
super(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
mAdapter = adapter;
icon = ContextCompat.getDrawable(mAdapter.getContext(), R.drawable.ic_delete);
background = new ColorDrawable(Color.RED);
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mAdapter.deleteItem(position);
}
public void deleteItem(int position) {
mRecentlyDeletedItem = vehiculos.get(position);
mRecentlyDeletedItemPosition = position;
vehiculos.remove(position);
notifyItemRemoved(position);
showUndoSnackbar();
}
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(context);
recyclerviewAdapter.setVehiculosList(vehiculos);
ItemTouchHelper itemTouchHelper = new
ItemTouchHelper(new SwipeToDeleteCallback(recyclerviewAdapter));
itemTouchHelper.attachToRecyclerView(recycler);
recycler.setAdapter(recyclerviewAdapter);
This is the code I've follow:
https://medium.com/#zackcosborn/step-by-step-recyclerview-swipe-to-delete-and-undo-7bbae1fce27e
vehiculos = new ArrayList<Vehiculo>();
Database dbHelper = new Database(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = new String[]{
Database.SQL_FIELD_MATRICULA,
Database.SQL_FIELD_ETIQUETA,
Database.SQL_FIELD_DESCRIPCION
};
Cursor c = db.query(Database.SQL_TABLE_MATRICULAS, columns, null, null, null, null, null);
c.moveToFirst();
while (!c.isAfterLast()) {
Vehiculo vehiculo = new Vehiculo(c.getString(c.getColumnIndex(Database.SQL_FIELD_MATRICULA)), c.getString(c.getColumnIndex(Database.SQL_FIELD_ETIQUETA)), c.getString(c.getColumnIndex(Database.SQL_FIELD_DESCRIPCION)));
vehiculos.add(vehiculo);
c.moveToNext();
}
c.close();
db.close();

how to delete a specific item from table in database?

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});

How to filter second spinner values from database on the basis of selection made in the first spinner?

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

confusing about customize listview in android studio

What's the problem that my db is null?
there says Cursor cursor = myDb.getData(select * from Donation_Details); myDb : null and it pops out the error below.
And here is the runtime error says
Here is the DatabaseHelper which When I assign & declear database.
private static final String DATABASE_NAME = "eBossCharity.db";
private static final int DATABASE_VERSION = 1;
public dbOpenHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
Here is the dbAccess when I want to get data from database.
public dbOpenHelper openHelper;
public SQLiteDatabase db;
private static dbAccess instance;
public dbAccess(Context context) {
this.openHelper = new dbOpenHelper(context);
}
public static dbAccess getInstance(Context context) {
if (instance == null) {
instance = new dbAccess(context);
}
return instance;
}
public Cursor getData(String sql) {
db = openHelper.getReadableDatabase();
return db.rawQuery("", null);
}
Here is the Summary page when I want to show the data into the customize list view. I put a break point at line 13 and debug it. It says my database is null. I Called the dbAccess method getData and grab the database"Donation_details". It should show the data...
ListView listView;
ArrayList<Model> mList;
RecordListAdapter mAdapter = null;
dbAccess myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary__page);
this.listView = findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this,R.layout.row,mList);
listView.setAdapter(mAdapter);
Cursor cursor = myDb.getData("Select * from Donation_Details");
mList.clear();
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String txnno = cursor.getString(1);
String name = cursor.getString(2);
String txndate = cursor.getString(3);
BigDecimal amount = BigDecimal.valueOf(cursor.getDouble(4));
String description1 = cursor.getString(5);
String createddate = cursor.getString(7);
mList.add(new Model(id,txnno,name,txndate,amount,description1,createddate));
}
I think I missed something here and there. But I couldn't find it, Or maybe I typed wrong something to cause database is null? Can I have some guidance? Thank in advance...
You need to initialize 'dbAccess myDb'
Solution:
Write this
myDb = new dbAccess(this);
In your onCreate () after the line setContentView(...)
Try it..

How do i get and use information from a Sqlite database in android

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();

Categories