Showing SQLite in a ListView - java

Hi, I have an SQLite database and I'm using a simple cursor to read the database and then show it to a TextView. However, I would like to show the data in a ListView.
So I have the string but I don't know how to show it in ListView. Is there a simple method or will I have to create an adapter of sorts?
I was also wondering how you can set parts of the list view to the header and others to the subheading. I want it so that each row is a different list item if that's possible.

Here is a simple example.Lets say you have two array lists named "Items" and "ItemsId" in your main activity.
Now, in your database handler class fetch your table and store the values to the Items and ItmesId array lists using below code.
MainActivity.Items.clear();
MainActivity.ItemsId.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
// Adding values to list
MainActivity.Items.add(cursor.getString(0));
MainActivity.ItemsId.add(cursor.getString(0));
} while (cursor.moveToNext());
}
Now populate your list view with Items array list in Main activity.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, Items);
listview.setAdapter(adapter);

Use the SimpleCursorAdapter.
Here is a trivial example:
yourListView.setAdapter(new SimpleCursorAdapter(
/* The context where the ListView associated with this SimpleListItemFactory is running */,
/* resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to" */,
/* The database cursor. Can be null if the cursor is not available yet. */,
/* A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet. */,
/* The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet. */,
/* Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int). */));

Related

Tring to populate a list view using a Firebase Query to create a leaderboard

I can't seem to populate a list view when I use a Query. I can populate it fine by just passing in all Users, although i am trying to create a leaderboard so I need to order these users.
when I use the following code the list view populates fine but of course not ordered:
database = FirebaseDatabase.getInstance().getReference().child("Users");
listview = (ListView) findViewById(R.id.Leaderboard);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,leaderboardlist);
listview.setAdapter(adapter);
database.addChildEventListener(new ChildEventListener()
I then tried this code to order it:
database = FirebaseDatabase.getInstance().getReference().child("Users");
listview = (ListView) findViewById(R.id.Leaderboard);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,leaderboardlist);
listview.setAdapter(adapter);
Query queryRef = database.orderByValue().limitToFirst(10);
queryRef.addChildEventListener(new ChildEventListener()
This returned the same list view (populated but no order). I am attempting to order the users by their score value, so I changed my query to:
Query queryRef = database.child("score").orderByValue().limitToFirst(10);
Although when I did this it seems not to work, the list view doesn't populate.
It won't let me export my JSON file of the database so can only attach the tree to help give you an idea what the uUser looks like.
Database tree
Inside the ChildListener I have this:
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s)
{
String user = dataSnapshot.getValue(User.class).toString();
leaderboardlist.add(user);
adapter.notifyDataSetChanged();
}
So I am not too sure where I have gone wrong or how I can fix this
Just Incase anyone is wondering I ended up fixing this,
the correct way to query isn't ordering by value but ordering by child:
Eg: instead of
Query queryRef = database.child("score").orderByValue().limitToFirst(10);
it should :
Query queryRef = database.orderByChild("score").limitToFirst(10);
My problem now is that it is now ordering them in reverse,
I tried to just change it from
limitToFirst(10);
to
limitToLast(10):
But this didnt change a thing ?
The correct way to query isn't ordering by value but ordering by child:
Eg: instead of
Query queryRef = database.child("score").orderByValue().limitToFirst(10);
it should :
Query queryRef = database.orderByChild("score").limitToFirst(10);
To make sure you have it ordered in the correct way you have to reverse order so instead of:
limitToFirst(10);
it should be:
limitToLast(10):

How to manipulate an array value at java android

i have an array from SQLite return value to passing at Spinner
At DatabaseHelper.java i create 1 void
public List<String> getSpinnerSupir(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sopir";
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(0)+cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
I consume the labels value to display at Spinner
List<String> lables = db.getSpinnerSupir();
Log.d("array:", String.valueOf(lables));
And at Log display
[1Juniarto, 2Agus Haryanto, 3Supriadi, 4Cahyanto]
I need to manipulate to
[Juniarto, Agus Haryanto, Supriadi, Cahyanto]
How to manipulate it?
Thanks
You are adding two columns column 0 and column 1 into labels
labels.add(cursor.getString(0)+cursor.getString(1));
So u have IDs as column 0 so its getting added along with the string
Modify it to
labels.add(cursor.getString(1));
Edit
returning both id and name
create a class like below
class Data {
private String id;
private String label;
public Data(String id,String label){
this.id=id;
this.label=label;
}
}
insert data into class
ArrayList<Data> arrayList=new ArrayList<Data>();
arrayList.add(new Data(cursor.getString(0),cursor.getString(1)));
return the array list and use it :)
You are adding values from both columns column 0 and column 1. If you need values only from column 1 don't add column 0 values
Change your code to add items as follows
labels.add(cursor.getString(1));
You can also use column name while getting the value from cursor in your getSpinnerSupir method.
Instead of below line;
labels.add(cursor.getString(0)+cursor.getString(1));
Use something like;
labels.add(cursor.getString(cursor.getColumnIndex("your_column_name"));
It seems that you want only the second column from each record. When calling:
labels.add(cursor.getString(0)+cursor.getString(1));
you get the numbers that you don't want.
Instead, replace with labels.add(cursor.getString(1));

SQLite grouped items and expandable list views for android

so I'm stuck on something probably pretty basic. I've got data stored in an SQLite database table and want to display that in an expandable list view. The data basically forms as headings and subheadings. There's many sub-headings to a single heading.
Retrieving the data is pretty straightforward. The part I'm stuck at is taking that data and giving it to the expandable list view.
I want the expandable list view to display the headings as the item that can be expanded, with the subheadings as the child items. How can I do this?
Thanks in advance.
You must provide an adapter to ExpandableListView. There is a base class adapter that you can extend it for your needs.
For creating the data lists. Assume Column1 is Heading, Column2 is SubHeading, try this in activity/fragment:
ArrayList<String> headings = new ArrayList<>();
HashMap<String, ArrayList<String>> subheadings = new HashMap<>();
String heading, subheading;
do{
heading = cursor.getString(1);
subheading = cursor.getString(2);
ArrayList<String> tmpChild;
if(headings.contains(heading)){
tmpChild = subheadings.get(heading);
}else{
headings.add(heading);
tmpChild = new ArrayList<>();
}
tmpChild.add(subheading);
subheadings.put(heading, tmpChild);
}while (cursor.moveToNext());
For the adapter, try my answer here: Tree with checkBox
Hope that helps!

Extracting string array from object array

So I have arraylist modelData that populates a recyclerview using sqlite database in some activity.!
Now in my MainActivity I want an string arraylist of names from the modelData !
that's what did so far..
// inside the onCreate of MainActivity
//code ..
db = new DBHandler(this, null, null, 1);
modelData = new ArrayList<AzkarModel>();
modelData = db.getDataFromDB();
for (AzkarModel o : modelData) {
ArrayList<String> names = new ArrayList<>();
names.add(o.getName());
}
for (int i = 0; i< modelData.size();i++){
names.add(modelData.get(i).getName());
Log.i("The List Log", names);
}
Two problems
1) [FIXED] The names arraylist is showing the same element twice at first and end
I/ The List Log: [Mike, John, Sam, Nora, Mike]
2) The arraylist names doesn't get updated..! when I add/edit/delete from the recycler and go back to the MainActivity I don't see the new changes unless I close the app then open it again..! I can't use notifyDataSetChanged since there's no adapter here.!
Once you have an array list object, populate it inside a loop
ArrayList<String> modelNames = new ArrayList<>();
for (AzkarModel model : modelData) {
modelNames.add(model.getName());
}
Now you have an array list with model names inside. Concerning the second question, please use an recyclerview adapter here you can find a nice tutorial.

ListView dynamic customization

I got this method setListView() which I use to populate ListView lv with data from SQLite database:
public void setListView (){
String[] columns= {DbHelper.C_ID, DbHelper.col1, DbHelper.col2, DbHelper.col3, DbHelper.col4,DbHelper.col5};
Cursor cursor = db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, "_id DESC");
String[] from= { DbHelper.col1, DbHelper.col2, DbHelper.col3, DbHelper.col4, DbHelper.col5};
int[] to = {R.id.tvCol1, R.id.tvCol2, R.id.tvCol3, R.id.tvCol4, R.id.tvCol5};
SimpleCursorAdapter adapter = new SimpleCursorAdapter (getApplicationContext(), R.layout.list_row, cursor, from, to);
lv.setAdapter(adapter);
}
There is a textView R.id.tvCol5 which is a part of list row (R.layout.list_row). I would like to dynamically change properties of that R.id.tvCol5 (setText, set background color etc.) based on what was entered in SQLite database column DbHelper.col5.
For example, if entry in DbHelper.col5 for that particular row is string "RED", I want to make that textView R.id.tvCol5 in that particular row to have red background and to set text to "red".
Is it possible to do that or is there some other way to accomplish that same effect?
Thank you all. Best regards.
You would need to do this in your adapter, in other words you're going to have to make a custom adapter that extends a cursoradapter or baseadapter or something similar.
Then you can just simply check the value of the string and do something to the view it returns based on that value (i.e. set the background to red).

Categories

Resources