SELECT one record and bind to text boxes - android

this is my query
SELECT *
FROM articles
WHERE id >1
ORDER BY id ASC
LIMIT 1
my requirement is very simple. I just want to select only one record and bind to textViews . This is what I had done so far.
public Article oneRecord()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM articles WHERE id=3;", null);
if(c.moveToFirst()){
Article a= new Article();
a.setId(c.getString(c.getColumnIndex("id")));
a.setImage_url(c.getString(c.getColumnIndex("image_url")));
a.setTitle(c.getString(c.getColumnIndex("title")));
a.setBody(c.getString(c.getColumnIndex("body")));
}
return a;
}

I am not sure I have understood you problem correctly or not. However there is not special thing to do. Just update TextView after getting article from database.
Article a = getOneRecordFromDB();
titleView.setText(a.getTitle());
bodyView.setText(a.getBody());

Related

Retaining CheckBox state within RecyclerView which is feed by SQL Database

Good evening everyone
Brief overview before a greater explanation. I currently have a SQL database which feeds into an arraylist thanks to a modal, we then feed this arraylist to our recycle view adapter which then populates the row.
Now i'm trying to build in the option for the user to select a row and then a check becomes true and tick is displayed. As you all currently know if the state is not stored then it start moving to random rows or being removed completely.
Lets start at the beginning with my SQL Lite database. Three simple rows Title , Description and checkbox state. Note that when a new row is added to the sql he checkbox column is automatically set to false.
Snippet below of the SQL query used to populate my recyclerView adapter
ArrayList<NoteInfoModal> noteInfoModalArrayList = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + Primary_Table + " ORDER BY Col_DateOrder ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
NoteInfoModal noteInfoModal = new NoteInfoModal();
noteInfoModal.setNoteName(cursor.getString(cursor.getColumnIndex(Col_NoteTitle)));
Applying it to the adapter
homeScreenAdapter = new HomeScreenAdapter(getContext(), primaryDatabase.populateHomeScreenOldestFirst(), filterOption, HomeScreenFragment.this);
Finally binding the information inside the adapter to the correct view (This one is for the check box)
((CustomViewHolder) holder).chkNote.setChecked(Boolean.valueOf(noteInfoModal.noteCheckBox));
Now I understand that I could simply update the row of the SQL DB to be true as this will then save the state, but if the user closes and then opens the app again I want them all to unchecked / false each time
Just looking for another way of approaching this issue.
Thank you
I thought I would input the current way in which I have resolved the issue.
Now when the user click a check box it will update the SQL to become true or false and because I want all results to be false upon app reopening I have implemented a small section of SQL Lite code which will set a column to false for me.
public boolean checkboxStateColumn ()
{
SQLiteDatabase db = this.getReadableDatabase();
ContentValues args = new ContentValues();
args.put(Col_CheckedRow, "false");
int i = db.update(Primary_Table, args, Col_CheckedRow + "=" + Col_CheckedRow , null);
return i > 0;
}

Android - How to retrieve values from SQLite Database and post them as Checkboxes

I'm currently trying to retrieve values from my SQLite Database. Screenshot
And output the value of the subname and units on checkboxes. I'm pretty sure I just have to get the IDs so I could output the subname and units values as checkboxes, so subname + unit = 1 checkbox. Could you please provide a sample code or link me a tutorial on how to do this? I'm rather clueless on how to do this and really new to Android.
I'm also looking for a way on how to save their IDs afterwards and add them into another table, so when I retrieve the IDs it will output the values. If you know how to do this too please do help. Thank you! Your time is much appreciated
Currently I have this in my DatabaseHandler.java. I just really don't know the code or syntax on how to retrieve it in my MainActivity and output it on checkboxes.
//get all subjects
public List < Subject > getAllSubjects() {
List < Subject > subjectList = new ArrayList < Subject > ();
//select all query
String selectQuery = " SELECT * FROM " + TABLE_SUBJECTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//loop through all rows and add it to list
if (cursor.moveToFirst()) {
do {
Subject subject = new Subject();
subject.setID(Integer.parseInt(cursor.getString(0)));
subject.setSubName(cursor.getString(1));
subject.setUnits(cursor.getString(2));
//ADD CONTACT TO LIST
subjectList.add(subject);
} while (cursor.moveToNext());
}
return subjectList;
}

SQLite get row data using SELECT

Using SQLite Database, I have a table with 6 columns in each row as the rows are added. The first column is the name of the "person." I have it so when you click on the person in a listview, it brings up a screen with 5 edit texts. You fill them out and submit it and it adds it to another row in the database.
To retrieve that data later on, I am trying to use SELECT by the name to get it, but cannot figure out how this works.
public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
dop.getReadableDatabase().execSQL("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME + "=\""+ name+"\"");
}
What do I do with that to retreive every column inside of that specific row. I am confused on the process to get it out.
Any lead in the write direction would be greatly appreciated. Thanks. If you need any more information please let me know.
Try this,
public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
return dop.getReadableDatabase().rawQuery("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME+" = '"+ name+"' ", null);}
Do not use execSql for getting data, that is only for sending data to the database. Instead, use rawQuery if you want to use the String. So it would be:
public Cursor getChildRulesInformation(DatabaseOperations dop, String name) {
return dop.getReadableDatabase().rawQuery("SELECT * FROM "+CHILD_RULES_TABLE_NAME+" WHERE "+CHILD_NAME + "='"+ name+"'", null);
}
This will return you the cursor object that you are looking for.

getAll from sqlite database android

I want to make a memo which was dated, I input the date with activities in a separate place from the calendar. How do I display all events in the calendar according to the date that I fed?
public List<Foto> getAllFotoList() {
List<Foto> fotoList = new ArrayList<Foto>();
String query_tb_foto = "SELECT * FROM " + TABLE_FOTO;
// SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query_tb_foto, null);
if (cursor.moveToFirst()) {
do {
// Siswa siswa = new Siswa(cursor.getString(0),
// cursor.getString(1));
Foto foto = new Foto(cursor.getString(cursor
.getColumnIndexOrThrow("COL_JUDULFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_IMG")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_DESFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_STARTDATEFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_STARTTIMEFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_ENDDATEFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_ULANGFT")),
cursor.getString(cursor
.getColumnIndexOrThrow("COL_ALARMFT")));
fotoList.add(foto);
} while (cursor.moveToNext());
return fotoList;
}
return null;
}
Is this true? Thanks for respons.
You need to use something like SELECT * FROM some_table WHERE date('1990-01-01'); (Just insert your custom date). This should return all of the results from your table with the same date value. See this post for further explanation and the SQLite documentation to see what else you can do with dates.
Two answer your second question, using a ListView should be fine. I personally use an ArrayList to populate my ListViews for SQLite results since queries return an arbitrary number of results. An ArrayList makes it easy to store and access those results.
did you sore the date as a GMTTIMESTAMP?
if so
String Q= "SELECT * FROM "+TABLE_FOTO +" ORDER BY GMTTIMESTAMP DESC;";
will put all the rows of the data with the most recent at the front.
or you could reference it by your primary key?
I was always told to make sure you remember to put a semicolon in side the brackets or your leave yourself open to SQL injections.
and you always want to check for null cursors so you should also have
if(cursor!=null&&cursor.moveToFirst()){}

Android: Select data from SQLite database - advice

Please give me advice, what is the efficient way to select data from database if I have query like SELECT * FROM order_list WHERE order_number = ? In table I have more entries (in my case) with common order number and I'd like to create List for entries with same order number and then shot it in ListView. I don't know if it is efficient first select all order numbers and then in foreach loop select and create List<Item> or exists something better. I've tried find some example but unsuccessfully. How should I solve this problem? Thank you. I appreciate every help.
You can use the same you are thinking like this:
"select col1,col2,col3 from table WHERE order_number = ? ", new String[]{YOUR_VARIABLE_HERE};
For example:
public Object[] getData(String Id) {
Cursor c = null;
ArrayList<String> arrayListProductName = new ArrayList<String>();
ArrayList<String> arrayListProductId = new ArrayList<String>();
db=helper.getWritableDatabase();
c = db.rawQuery("select distinct Column1,Column2 from Table1inner join Table2 on Table1.anyId = Table2.anyId Table2.Id = ?", new String[]{Id});
c.moveToFirst();
while(!c.isAfterLast())
{
arrayListProductName.add(c.getString(c.getColumnIndex("Column1")));
arrayListProductId.add(c.getString(c.getColumnIndex("Column2 ")));
c.moveToNext();
}
c.close();
db.close();
return new Object[]{arrayListProductName,arrayListProductId};
}
And in your Activity class:
helper = new YourDatabaseHelper(this);
Object[] objectScheme = merchandisingHelper.getData(retId);
arrayListSchemeProductName = (ArrayList<String>) objectScheme[0];
arrayListSchemeProductId = (ArrayList<String>) objectScheme[1];
Hope this will help you.
Thanks
Use GROUPBY in SQL
SELECT *
FROM table_name
WHERE column_name = yourvalue
GROUP BY your_columnname
The GROUP BY is used in conjunction with the aggregate functions to group the result-set by one or more columns. In your case it will group your records based on your order number.After grouped you can assign to your list view or what ever you want.
If I understand correctly you want to know if it's more efficient to :
filter using a WHERE order_number = ? clause
load everything, then filter in a loop.
Then 1 is a much better solution, it will avoid a lot of unnecessary object creation. If you have a lot of rows it may be interesting to add an index on the order_number column.
If you want to show the result in a Listview the best solution is to connect the SQLiteCursor to the ListView, using a SimpleCursorAdapter.
This is very efficient because you only have to load data when the ListView needs it.

Categories

Resources