I am quite new to Android development. I managed to get data saved to SQLite database. Now, what I want is to view these data when I call viewData(). I have viewData() which shows data as a Toast as I made it as a sample. Now I need these data to show on a new activity using a ListView, but the number of data to show is depending on how many data is in the database at the moment, If user saved 10 items then I want all the 10 items to shown up. How can I do it?
I hope my question is clear.
Thanks in advance.
you could use ListView declare it in your layout
in yor activity declare a globar var:
and onCreate
datos can be an array that you can populate with data that you extract from your data base and that's the most simple way to show it. if you want to customizise your listView you can create a custom adapter, or in other way the newest element that replace listView is ReciclerView. I hope tihs help you
I will try to give an in-depth answer to this.
Whenever you want to fetch and display a list of data from the database, you can use a
ListView
,GridView
,Spinner
, etc for it.You can use a
CursorAdapter
which can make the job of querying and displaying data much more simple and easy.Here is a basic visual representation of it,
Step 1
Firstly, you need to create a database. As mentioned in your question, it is clear that you know how to create a database and put some data into it. So I am not going into the depths of it.
Step 2
We need to define the layout to be used for the individual items in the
ListView
and save it asres/layout/item_todo.xml
This is just a sample layout, you can design any kind of layout you want to.Step 3
Now we need to define an adapter. Here we are using a
CursorAdapter
which converts aCursor
(that you provide) into Views (defined by your layout).There are two methods,
newView
andbindView
which we need to override. The newView is responsible for inflating newViews for the first time and the bindView is responsible for binding the data to the Views.Step 4
Now as you can clearly see, that the constructor needs a
Context
and aCursor
. Now we need to query the database and retrieve the data into a Cursor and pass it to the adapter.Step 5
This is the last step where we need to instantiate the adapter and attach the
ListView
with the adapter to populate the data.You can use a SimpleCursorAdapter: