Sqlite printing - android

hi I have a SQLite Database and I've placed it in my assets folder. I was wondering how you can "print" information from the table on the screen. I have looked around and all I can find are people adding to a database all I want to do is show it on the screen and add some filters later on.

It should be roughly like this:
private static String DB_PATH = "/data/data/com.your.app/your_path/yourdb.sqlite";
private static SQLiteDatabase myDataBase;
public static void openDatabase() {
String queryString="YOUR SQL QUERY HERE";
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,SQLiteDatabase.OPEN_READONLY);
Cursor cursor = myDataBase.rawQuery(queryString, null);
if(cursor!=null) {
cursor.moveToFirst();
while(!cursor.isLast()) {
/*CHECK CURSOR USAGE AND DO SOMETHING WITH YOUR RESULTS HERE */
cursor.moveToNext();
}
}
myDataBase.close();
}

I think this may help.
Retrieve data from the SQLIte database and store them in a String / Strings.
Bring in some TextViews in your xml to your layout.
get references to those textview / textviews in your java code.
textview.settext(-----the string retrieved------);
This will print whatever string that your retrieved from your SQLite database.

SQLiteDatabase database;
public int getId() {
String sqlQuery = "SELECT * FROM <table_name>;
int id = 0;
Cursor cursor = database.rawQuery(sqlQuery, null);
if (cursor.moveToFirst()) {
id = cursor.getInt(0); // In my case, id (int) is in first column
}
return id;
}

Related

retrieve data from database what next?

ok I just followed an instruction that I should do this to retrieve sql data from database but it just cuts to there so far I have this inside my databasehelper class.
public void getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
}
while (cursor.moveToNext());
}
db.close();
}
So somehow this does is it get all the values of my tables 4th column which contains an int... how do I retrieve the value in my MainActivity and save it in an array of integers?
just add everything in a ArrayList and return the arraylist
simply call the method in your main activty
public ArrayList<Integer> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
ArrayList data= new ArrayList<>();
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
data.add(resource);
}
while (cursor.moveToNext());
}
db.close();
}
return data;
}
Well, as you have it, the variable resource is scoped only to the while loop. Even if it wasn't it would constantly get overwritten on each loop iteration.
Instead, you should declare a collection higher up and Add each value to it during your while loop. You could also redefine your function to return the collection if integers.
public List<int> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
List<int> myVals = new List<int>();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource, null); //null for conditions
if (cursor.moveToFirst())
{
do
{
myVals.Add(cursor.getInt(3));
}
while (cursor.moveToNext());
}
db.close();
return myVals;
}
Also, as a note... string concatenation of a SQL query is a recipe for disaster. Look up SQL Injection and best practices to avoid it before continuing further. It is worth the time to get into good habits early on.
EDIT / ADDENDUM
Unless you also limit your result set returned from your table query, you will be getting every record. The function you have here really has no practical use and would likely cause more problems than any benefits it may have. I would suggest, as an example of a more usable function that returns a specific IconResource based on the IconId:
public int getIconResource(int iconId)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "select IconResource from IconTable where IconId = ?";
PreparedStatement pstmnt = db.prepareStatement(getresource);
pstrmnt.setString(1, iconId);
ResultSet rset = db.executeQuery();
int iconResource;
if (rset.next())
iconResource = rset.getInt("IconResource");
db.close();
return iconResource;
}
Of course, the above is making assumptions of your table structure.
Using the above, in your code elsewhere, you would simply call this function with the IconId and use the output however needed:
int iconResource = getIconResource(5); // returns the IconResource for IconId = 5
The above prevents any possible SQL Injection attacks by using a parameterized query and avoiding the use of dynamic concatenated strings sent to your SQL server.
You may try out the following code:
public List<Integer> getIconResource(String tblName)
{
List<Integer> list = new ArrayList<Integer>();
list.clear();
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
list.add(resource);
}
while (cursor.moveToNext());
}
db.close();
return list;
}
Then call this method in MainActivity and store the List in another Integer type list.
databasehelper dbhelper;
List<Integer> newList = dbhelper.getIconResource("Your tablename");
fot(int i = 0 ; i< newList.size() ; i++){
int yourValue = newList(i);
}

Searching and retrieving specific data from a previously created SQLite Database in Android?

I have an SQLite Database which I made in SQLite Browser and exported to my Android Application through SQLite Asset Helper Library. This database is for reading-only tasks and can't be upgraded or modified.
Now I want to search in an specific column any data the user input in a TextView, and in case the data matches with some value of the column retrieve all the values corresponding from the other columns.
For example:
TABLE FRUITS
_id NAME URL
1 apple R.drawable.apple
2 orange R.drawable.orange
3 kiwi R.drawable.kiwi
Since my application only allows the user to input the NAME field, the query needs to search in the NAME column only, and retrieve the URL value only if exists in the database, otherwise will return nothing.
Here's my code for importing the database:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "fruitManager";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor answerRequest(String request) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "FRUITS";
qb.setTables(sqlTables);
String[] sqlSelect = {"0 _id", "NAME", "0 URL"};
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
return c;
}
}
And from here I made the request:
public class Request {
private Cursor cursor;
private MyDatabase db;
String request;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite_asset_helper);
public void onClick(View v) {
request = mEdit.getText().toString().toLowerCase();
db = new MyDatabase(this);
cursor = db.answerRequest(request);
url = cursor.getString(c.getColumnIndex("NAME"));
System.out.println("Your request was: " + request +
" and has this URL: " + url);
}
}
protected void onDestroy() {
super.onDestroy();
cursor.close();
db.close();
}
Still, loads of code are needed for do the query but I don't know exactly how to implement them in this case (due to imported database). Thanks in advance.
UPDATE: I'm kinda desperate so if you don't have the answer but know an alternative for do the task (like using another database handler instead of SQLite) I will accept your suggestions as the correct answer.
Only restriction is: Has to be an offline solution (no internet connection needed for access the database).
Your current query looks like this:
`select 0 _id, NAME, 0 URL from FRUITS`
Notice you aren't using the request string anywhere. You are also selecting integer literal 0 and aliasing this to other column names--there doesn't seem to be any reason for this. As is, your results would be
_id NAME URL
0 apple 0
0 orange 0
0 kiwi 0
What you want is the following:
`select * from FRUITS where NAME = request`
Here's how I would write it:
public Cursor answerRequest(String request) {
SQLiteDatabase db = getReadableDatabase();
String table = "FRUITS";
String where = "NAME = ?";
String[] whereArgs = {request};
// select * from fruits where name = request
return db.query(table, null, where, whereArgs, null, null, null);
}
And elsewhere when you want to retrieve the values:
db = new MyDatabase(this);
Cursor cursor = db.answerRequest(request);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
// cursor is not empty, read values here
String url = cursor.getString(cursor.getColumnIndex("URL"));
}
} finally {
cursor.close();
}
}

SQLITE SUM and LIMIT don't seem to work together

I'm trying to retrieve the sum of a column from SQLITE. I am able to successfully get it.
But when I try to retrieve just the sum of 10 rows, it returns the sum of the entire column again. The query seems to be correct though.
public String getUnitsForWeek(Context context) throws IOException {
DataBaseHelper dbHelper = new DataBaseHelper(context);
String query = "SELECT sum(UNITS) FROM SERVICE_TABLE order by id DESC limit 7";
return String.valueOf(dbHelper.getString(query));
}
The dbHelper.getString method is:
public int getString(String query) {
String mypath = DB_PATH + DB_NAME;
SQLiteDatabase database = SQLiteDatabase.openDatabase(mypath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = null;
int i;
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
i= cursor.getInt(cursor.getColumnIndex(cursor.getColumnName(0)));
return i;
}
Thanks.
SUM is an aggregate function that combines data from many rows into one. Since there is only one result row, LIMIT and ORDER BY are meaningless.
To sum UNITS on the 7 rows with highest ID, you can use a subselect:
SELECT SUM(UNITS) FROM (SELECT UNITS FROM SERVICE_TABLE ORDER BY id DESC LIMIT 7);
Can't you do a subelect?
SELECT sum(UNITS) FROM (SELECT UNITS FROM SERVICE_TABLE order by id DESC limit 7) s

Android sqlite rowcount is always zero?

I've used the GUI to create a DB which has 1650 records in it.
I'm trying to query this DB but it's always returning nothing. I've tried writing a simple getrowcount() method to see if I'm getting anything at all, but it always returns zero. I must be missing something obvious here, if someone can help point out what's going on.
In my main app.java:
db = new DbHandler(this);
String sIcao1 = "ROW COUNT = " + String.valueOf(db.getRowCount());
In my dbhandler.java:
package com.jammo.mywidget4;
<snip - standard includes>
public class DbHandler extends SQLiteOpenHelper {
private static SQLiteDatabase db;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "airports";
private static final String TABLE_AIRPORTS = "airports";
public DbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db = this.getWritableDatabase();
}
int getRowCount() {
int nCount = -1;
//SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM airports", null);
nCount = cur.getCount();
if (cur != null) {
//cur.moveToFirst();
//nCount = cur.getInt(0);
//if (cur.getInt (0) == 0) {
//}
}
return nCount;
}
}
In the GUI (SQLite DB Browser) I'm doing a simple
select * from airports
... and I'm getting back the full number of rows. When I debug the Java, cursor returns nothing.
Also, the DB created by the GUI is located in myapp/assets/airports.db.
Any ideas?
I think you need to include the .db in the DATABASE_NAME.
Try changing this:
private static final String DATABASE_NAME = "airports";
to this:
private static final String DATABASE_NAME = "airports.db";
Edit:
Actually I think even with this change it is not going to work for you. SQLiteOpenHelper is expecting your db file to be inside of /data/data/your.package/databases/ So I think you'll need to copy it from assets to there if you want it to work with an unmodified SQLiteOpenHelper.
See here to learn how to copy it over: Android: Accessing assets folder sqlite database file with .sqlite extension

Concat database tables 1 field multiple records string in one row

I have a tables and records like :
EmployeeName
------------
Ram
Laxman
Bharat
Shatrugn
where i want to output to concat all values in one row in a single query:
I want result like:
Ram,Laxman,bharat,shatrugn
Concat string with ,(comma) in singlee line..
but i don't know that how to concat in android using cursor...
In SQLite, you can use GROUP_CONCAT():
select Group_Concat(EmployeeName)
from table1
See SQL Fiddle with Demo
If you had multiple fields that you want to return, then you would use a GROUP BY with the query, similar to this:
select id, Group_Concat(EmployeeName)
from table1
group by id
See SQL Fiddle with Demo
Here is my code i used...hope it helps you.
private SQLiteDatabase myDataBase;
Cursor cursor;
String S="";
String myPath2 = yourDBpath + yourDBNAME;
try{
myDataBase = SQLiteDatabase.openDatabase(myPath2, null,SQLiteDatabase.OPEN_READWRITE);
String sql="your query";
cursor=myDataBase.rawQuery(sql, null);
if(cursor != null)
{
while(cursor.moveToNext())
{
S=S.append(cursor.getString(0));
}
}
}
}catch(Exception e){
}finally{
myDataBase.close();
}
Final result will be there in String S.
String values;
if (cursor.moveToFirst()) {
do {
values=values + cursor.getString(0)+",";
} while (cursor.moveToNext());
remove last comma
if (values.length() > 0)
{
values= values.substring(0,values.length() - 1);
}

Categories

Resources