Fetch data from database in a tree structure in sqlite - android

In my application I have a tree structured table and I want to know that if I can fetch the tree structure data from sqlite database by simply applying a single query. Currently I am lopping it manually using a for loop and able to meet my requirement but I am not statisfied with that approach as its more complex, may be time consuming, etc.
My table table structure is as below,
parent_id | cat_id
null | 1
1 | 2
1 | 3
1 | 4
4 | 5
4 | 6
So, now above is my table structure and I want to fetch the tree structure like,
If I pass parent_id as 1 in my query then it should return 2,3,4,5,6 as 1 is parent of 1, 2, 3, 4 and 4 is parent of 5,6 and also 4 is child of 1
So, input and output expected by me,
input output
1 2,3,4,5,6
4 5, 6
So, it there a simple way to acheive the above tree structure by using sqlite query?
OR
There is no way to acheive this using sqlite query and I need to follow the current method or way that I am using it by manually looping all the category ids.

You can use group_concat method as it is available in sqlite.
For your question i have created one table called Trans and added parent_id and cat_id columns.
select parent_id, group_concat(cat_id) from trans group by parent_id;
I have table like this i have mentioned below.
and i got resultant like this :
Hope this will help you.

I didn't find any solution from sqlite itself, so created an Algorithm that creates Tree structure by iterating over each id & over its sub_ids and write into database.
I had gone through Closure Tables which gives the expected result that I was looking as a solution
Some more references of Closure Table -
http://technobytz.com/closure_table_store_hierarchical_data.html
http://karwin.blogspot.in/2010/03/rendering-trees-with-closure-tables.html

Related

CASE expression in insert with ContentProvider

I visited sqlfiddle.com and made some tests.
I wanted to get a SQL statement that would let me insert a row, and have a field (below is called active) whose value depends on the table being empty or not.
I used the following schema:
CREATE TABLE kids (
identifier INTEGER PRIMARY KEY,
name VARCHAR,
surname VARCHAR,
active INTEGER);
INSERT INTO
kids
VALUES
(1, "name1", "surname1", CASE WHEN EXISTS (SELECT * FROM kids) THEN 0 ELSE 1 END);
INSERT INTO
kids
VALUES
(2, "name2", "surname2", CASE WHEN EXISTS (SELECT * FROM kids) THEN 0 ELSE 1 END);
And I get the following result when performing a SELECT * FROM kids:
+---+-------+----------+---+
| 1 | name1 | surname1 | 1 |
+---+-------+----------+---+
| 2 | name2 | surname2 | 0 |
+---+-------+----------+---+
This is perfect. The thing is, how do I perform this insert in Android using SQLite and ContentProviders?. Both insert (on ContentProviders and SQLite instance take a ContentValues as a parameter, and I can't add a subquery there, it would be literally read and written.
Is it even possible to achieve this ? If you can think of any other approach, it is also welcome.
Thank you.
Another way of achieving your requirement would be to check the value of underlying field before insertion and then insert the entire data along with computed value in active field
ContentValues ensures that it contents are never interpreted as SQL, so this is not possible.
Unless you actually need to provide data to other apps, do not use content providers. (And if you need to give data to other apps, it would be a bad idea to allow them to execute arbitrary SQL.)

Tree select sqlite [duplicate]

This question already has answers here:
Database Structure for Tree Data Structure [closed]
(5 answers)
Closed 7 years ago.
I am using sqlite in android and need to make an select to get all parent with their child's, for example:
id || parent_id || child_id || name
1 1 1 jhon
2 1 2 helen
3 2 3 barack
4 1 4 manuel
5 3 5 gaga
result should be:
jhon
helen
manuel
barack
gaga
So, I need a reqursive sql, but googling a bit I found that CTE is not supported on sqlite, anyway I can use even an recursive java method to return a list of selected names order by parent asc
Notice that tree depth can be more than 2 levels!
I'm not sure how to interpret your table. Each node has an ID, right; and a (unique) parent_id (pointing to itself for the root node?). What's the child_id? Can't there be multiple children?
When dealing with recursive structures of arbitrary depth, if the tree doesn't change too often, and queries need to be fast, create a supporting table (say, "ancestral_closure") detailing the closure of all parent-child relationships:
ancestor_id, child_id
and make sure it's updated whenever the base table changes (recurse through the base table and add a row for each node that sits below another one). Join with the ancestral_closure table when you need to find all parents and/or children of a node. I don't think sqlite supports stored procedures executed on insert/delete/update triggers, so the update will have to be triggered by hand.
SQL is good at simple relations, not arbitrary graphs.

Does SQLite guarantee the order of results to match a table?

If table Scores looks like this:
_id | score
---------
1 | 1,000
2 | 2,000
3 | 3,000
4 | 4,000
5 | -1
6 | -1
7 | -1
Will the following query always return the rows in _id ascending order?
SELECT * FROM Scores
Also, will the following query always return the first ordered occurrence of _id (that is, 5)?
SELECT _id FROM Scores WHERE Score = -1 LIMIT 0, 1
The key here is ALWAYS. I have tested it and it works as intended but I want to verify this outcome is guaranteed and that an order by clause is not needed in these cases.
Thank you all.
By default, the rows are logically stored in order of increasing rowid.
And if your select stament does not include an order by, or the table has no index, the default sorting order will always be the primary key column, which is the _ID column in this case
Read more here
One of the principles of the databases is that you can not suppose that your registers are ordered in any way, as the internal implementation of SQLite may differ between devices. You should use the operator order by to assure a certain order.

(Java) Data Structure for agenda-like program?

In a nutshell, I've parsed data like this from XML:
root ---- date1 ---- time 1 ----item 1 ---- prop 1 --- a
| | | | |-- b
| | | |
| | | |- prop 2
| | |
| | |--item 2
| |
| |- time 2
|
|
|- date2 ---- time 1
each item has several properties (like item1 has prop1 and prop2)
each time has several items
each date has several times
root has several dates as its children
And I want to use this data:
Be able to show user the content within each date. e.g. if date1 is current date, then shows user each item sorted by time, just display these data kind like Android Google Calendar's Agenda View.
So may I ask what data structure should I use to achieve this?
The possible candidates I've thought are:
Nested HashMap, like HashMap<Time, HashMap<item1, HashMap<prop1, a>>>;
SQL database, create table for each time, then put item in row, prop in column
It's totally ok for this app not to strictly keep the tree-like structure when store the data, so I prefer SQL database, may I ask you guy for possible better solutions?
This app is going to running on Android, thanks for any help.
UPDATE
My thought of the database structure:
create database table for each date;
Then in each DB table:
time prop1 prop2 prop3
item1
item2
...
Then maybe later I can retrieve items by using select on time basis.
UPDATE2
I need to create table for dates because some of the item may be the same. Please imagine you put two same meetings on different days in a week. I can't create tables for each item because it is difficult to extract those info from original XML than just create date tables and put them in database.
Create one table for all and us a date column to retrieve data as you wish. you don't need to make it complicated like creating tables for all dates.
My approach would be to create a DAO (Data Access Object) that would be responsible for taking the object that resulted from parsing the XML and storing all the data on SQLite correctly. The DAO would also be responsible for re-making the object from the SQLite data.
Keep in mind that this translation won't be as easy as you mentioned though. You said "create table for each time, then put item in row, prop in column". This is not a standard DB model, as usually you don't create a table for each instance of a given entity.
Start by analyzing what entities you have (e.g., date, time, item) and then analyze the relationship between them (e.g., a data contains one or more time, a time contains one or more items, etc). Usually each entity will become a table on your DB, and relationships will either go inside an existing table (as a reference to other tables) or they will have their own table. You can read more about this approach here: http://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model

Get Duplicate entries for some Items

I am new to android and working on an android application, I am parsing an xml and then storing data in the DB (SQLite). items i have in xml are basically slideshows. and i am saving individual slides.
Sometimes, it happens that i get one slide saved two times with different itemid(PK + autoincrement) but same data in other cloumns.
e:g
1 | www.abc.com | 25
2 | www.abc.com | 25
which should not be saved. i cant post original code. any general solutions to avoid that. Thanks in advance.
You can create table with UNIQUE column.And can handle error while inserting.In this case keep 2nd column also unique as you did with your first column

Categories

Resources