I have a table in which name and number of people are stored. Now I want to make a method in sqlite helper class which will return the number of particular person whose name I will pass in the method
There is something wrong with my code.
Here is my code
public String fetchGroup(SQLiteDatabase inDatabase, String valueCheck){
String query = "SELECT * FROM groups WHERE groupname='" + valueCheck;
Cursor cursor = inDatabase.rawQuery(query,null);
String place = cursor.getString(cursor.getColumnIndex("contactid"));
return place;
Take care to use cursor.moveToFirst() command before reading datas
Else, instead counting the number of people in Java, you can just modify your query to have only this number return.
Something like this :
public String fetchGroup(SQLiteDatabase inDatabase, String valueCheck){
String query = "SELECT COUNT(id) FROM groups WHERE groupname=\"" + valueCheck + "\"";
Cursor cursor = inDatabase.rawQuery(query, null);
cursor.moveToFirst();
int place = cursor.getInt(0);
return String.valueOf(place);
}
After your query do
int count = 0;
while (cursor.moveToNext()) {
// increment variable
count++;
}
after iterating you will get number of count
Related
I'm trying to use rawQuery to return a cursor with a few different rows of data to be passed into it. When there is only 1 argument it works. When there is more than 1 argument it displays the empty ListView state. I believe the issue lies here:
// Query for items from the database and get a cursor back. Edited code for clarity:
recipeCursor = db.rawQuery("SELECT course, name, _id " +
" FROM recipes WHERE _id = ?",
selectedRecipesSQL);
When the code works the selectedRecipesSQL would look something like:
String[] selectedRecipesSQL;
selectedRecipesSQL = new String[]{"2"};
And when it doesn't work it would be something like
String[] selectedRecipesSQL;
selectedRecipesSQL = new String[]{"2 OR 5"};
So, to be clear, I can display a single row of the table in my ListView, but if I try to display more than one row of the table then it won't display anything.
One ugly solution which has crossed my mind (but I haven't pursued) is that I need to edit the rawQuery selection statement to read something like:
recipeCursor = db.rawQuery("SELECT course, name, _id " +
" FROM recipes WHERE _id = ? OR _id = ? OR _id = ?",
selectedRecipesSQL);
I'd probably use a for loop to generate the correct amount of WHERE "_id = ?" and then use a string array:
selectedRecipesSQL = new String[]{"2", "5"};
One way of doing it is by passing the possible values of _id as 1 string which is a comma separated list like this:
selectedRecipesSQL = new String[]{"1,2,3"};
and in your query use the operator LIKE:
recipeCursor = db.rawQuery(
"SELECT course, name, _id FROM recipes WHERE ',' || ? || ',' LIKE '%,' || _id || ',%'",
selectedRecipesSQL
);
This works also for just 1 value.
static String multiply__concat_string(String text,String joiner_,int multiple_)
{
String output="";
for(int i=0;i<multiple_;i++)
{
output+=(text+joiner_);
}
if(output.length()>0)
{
output=output.substring(0,output.length()-1);
}
return output;
}
Use it like this :
selectedRecipesSQL = new String[]{"2", "5"};
db.rawQuery("SELECT course, name, _id " +
" FROM recipes WHERE _id IN("+multiply_concat_string("?",",",selectedRecipesSQL.length)+")",
selectedRecipesSQL);
I'm searching for a word (variable) that occurs in multiple columns of a table. The search has to return the name of the columns in which the word in found.
I could use a foreach loop to go through each column seperately and know the presence of the word in that particular column when the returned cursor isn't null.
The problem is on how to use two different variables (one for column name and one for the word) in SQL query or rawQuery.
My code is as follows:
String[] columnsList = {"col1","col2","col3"};
String[] wordsList = {"fireman","camper","builder"};
for(String i : wordsList){
for(String j : columnsList){
Cursor wordQuery = myDatabaseHandle.rawQuery("Select * from myTableOne WHERE " + j + " = ?",new String[]{i});
if(!(wordQuery==null)){
Toast.makeText(this,j+"is success",Toast.LENGTH_SHORT).show();
}
}
}
But i'm unable to get the answer. I used a seperate string as:
String queryString = "Select * from myTableOne WHERE " + j ;
and in the query,
Cursor WordQuery = myDatabaseHandle.rawQuery(queryString+" = ?",new String[]{i});
But, it's just toasting the names of all columns.
Your error is here:
if(!(wordQuery==null)){
The cursor is never null.
It can contain 0 records, though.
You can check its length by using wordQuery.getCount()
Something like:
if((wordQuery.getCount() > 0)){
This might be stupid question but this code is not working..
String sql= "SELECT field, question, choice1, choice2, choice3, choice4, answer "
+ "FROM WineQuiz ORDER BY RANDOM() LIMIT 5";
Intent i = getIntent();
String mField1 = i.getStringExtra("FIELD1");
String mField2 = i.getStringExtra("FIELD2");
String mField3 = i.getStringExtra("FIELD3");
if(mField1!="" || mField2!="" || mField3!=""){
sql = "SELECT field, question, choice1, choice2, choice3, choice4, answer "
+ "FROM WineQuiz WHERE field='"+mField1+"' or field='"+mField2+"' or field='"+mField3+"' ORDER BY RANDOM() LIMIT 5";
Cursor c =db.rawQuery(sql, null);
What I'm trying to do is simple. I'm creating quiz app, which has SelectActivity sending string data of quiz field into this class receiving it with variables of mField1,2,3.
If SelectActivity does not send any string, the first sql(variable) is put into the query.
If one of the field is chosen, mField1 or 2 or 3 receives string data, then the second sql is put into the query.
However, the first sql querying does not work while the second one works well.
When I use the first sql query independently, it works pretty well. Thus, the first and second sql seems unable to exist at the same time though those two query has no problem by themselves.
Why is that??
Replying the comments, "Not work" means cursor has no data. My continuing code is below, and the error log "Cursor has no data" shows up. It literally means those array does not store any data.
Cursor c =db.rawQuery(sql, null);
if (c.getCount() > 0) { // If cursor has at least one row
c.moveToFirst();
do { // always prefer do while loop while you deal with database
cPos = c.getPosition();
array[cPos][0] = c.getString(c.getColumnIndex("field"));
array[cPos][1] = c.getString(c.getColumnIndex("question"));
array[cPos][2] = c.getString(c.getColumnIndex("choice1"));
array[cPos][3] = c.getString(c.getColumnIndex("choice2"));
array[cPos][4] = c.getString(c.getColumnIndex("choice3"));
array[cPos][5] = c.getString(c.getColumnIndex("choice4"));
array[cPos][6] = c.getString(c.getColumnIndex("answer"));
c.moveToNext();
//Retrieves whether the cursor is after the last row in this SQLServerResultSet object.
} while (!c.isAfterLast());
} else {
Log.e("SQL Query Error", "Cursor has no data");
}
if my data structure is like this
parentA
-------parentAA
--------------parentAAA
---------------------childA
if i can get "childA.name" . how can i know all the parent name till the top level.
so it will be like this > parentA/parentAA/parentAAA/childA
what is the best way to do this ?
i'm working with SQLite and JAVA/android .. thanks in adv.
____________ EDIT
Okay guys, thanks for all of u . so i just make it by repeating "select query". BOTTOM-UP this is the method i create
public String getPath(int id, int type) {
StringBuilder pathBuilder = new StringBuilder();
String sql = null;
int parentId = 0;
if (id == 0) {
pathBuilder.insert(0, "/root/");
return pathBuilder.toString();
}
if (type == LayerManagementActivity.PARENT) {
do {
sql = "SELECT id, name, parent_id from parents_table where id="
+ id;
Cursor c = mDatabase.rawQuery(sql, null);
if (c.moveToFirst()) {
parentId = c.getInt(2);
id = c.getInt(0);
pathBuilder.insert(0, "/" + c.getString(1));
c.close();
}
id = parentId;
} while (parentId != 0);
pathBuilder.insert(0, "/root");
pathBuilder.append("/");
} else if (type == LayerManagementActivity.CHILD) {
sql = "SELECT id, name, folder_id FROM childs_table WHERE id=" + id;
Cursor c = mDatabase.rawQuery(sql, null);
if (c.moveToFirst()) {
pathBuilder.append(c.getString(1));
id = c.getInt(0);
int folderId = c.getInt(2);
String path = getPath(folderId, LayerManagementActivity.PARENT);
pathBuilder.insert(0, path);
}
c.close();
}
Log.d("crumb", pathBuilder.toString());
return pathBuilder.toString();
}
In this SQLite Release 3.8.3 On 2014-02-03 has been added support for CTEs. Here is documentation WITH clause
Example:
WITH RECURSIVE
cnt(x) AS (
SELECT 1
UNION ALL
SELECT x+1 FROM cnt
LIMIT 1000000
)
SELECT x FROM cnt;
I have a table called project with a column named rates.
The rates column is a string that holds a JSON array.
To split this string into rows that I can use in an IN statement to get rows from the related table, I use this for the IN part
WITH
split(s, p) AS (
SELECT substr(printf("%s%s", ss, ","), instr(ss, ",")+1), trim(substr(ss, 0, instr(ss, ","))) from ( select replace(replace(rates,"[",""), "]","") ss from project where rowid = 1)
UNION ALL
SELECT substr(s, instr(s, ",")+1), trim(substr(s, 0, instr(s, ","))) FROM split
where p!=""
)
select p from split where p!=""
You can use nested set model. Nested sets have big advantage that they can be implemented in most SQL engines using simple, non-recursive SQL queries.
SQLite doesn't support recursive CTEs (or CTEs at all for that matter),
there is no WITH in SQLite. Since you don't know how deep it goes, you can't use the standard JOIN trick to fake the recursive CTE. You have to do it the hard way and implement the recursion in your client code:
Grab the initial row and the sub-part IDs.
Grab the rows and sub-part IDs for the sub-parts.
Repeat until nothing comes back.
I have taken String value from a EditText and set it inside SELECT QUERY after WHERE condition
As
TextView tv = (TextView) findViewById(R.id.textView3);
EditTextet2 et = (EditText) findViewById(R.id.editText1);
String name = et.getText().toString();
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = '"+name+"'", null);
c.moveToNext();
tv.setText(c.getString(c.getColumnIndex("email")));
But it doesn't work. Any suggestions?
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst() like #thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Try using the following statement:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = ?", new String[] {name});
Android requires that WHERE clauses compare to a ?, and you then specify an equal number of ? in the second parameter of the query (where you currently have null).
And as Nambari mentioned, you should use c.moveToFirst() rather than c.moveToNext()
Also, could there be quotations in name? That could screw things up as well.
Here is the below code.
String areaTyp = "SELECT " +AREA_TYPE + " FROM "
+ AREA_TYPE_TABLE + " where `" + TYPE + "`="
+ id;
where id is the condition on which result will be displayed.
public User searchUser(String name) {
User u = new User();
SQLiteDatabase db = this.getWritableDatabase(); //get the database that was created in this instance
Cursor c = db.rawQuery("select * from " + TABLE_NAME_User+" where username =?", new String[]{name});
if (c.moveToLast()) {
u.setUsername(c.getString(1));
u.setEmail(c.getString(1));
u.setImgUrl(c.getString(2));
u.setScoreEng(c.getString(3));
u.setScoreFr(c.getString(4));
u.setScoreSpan(c.getString(5));
u.setScoreGer(c.getString(6));
u.setLevelFr(c.getString(7));
u.setLevelEng(c.getString(8));
u.setLevelSpan(c.getString(9));
u.setLevelGer(c.getString(10));
return u;
}else {
Log.e("error not found", "user can't be found or database empty");
return u;
}
}
this is my code to select one user and one only
so you initiate an empty object of your class then
you call your writable Database
use a cursor in case there many and you need one
here you have a choice Use : 1-
if (c.moveToLast()) { } //it return the last element in that cursor
or Use : 2-
if(c.moveToFirst()) { } //return the first object in the cursor
and don't forget in case the database is empty you'll have to deal with that in my case i just return an empty object
Good Luck
Detailed answer:
String[] selectionArgs = new String[]{name};
Cursor c = db.rawQuery(
"SELECT * FROM " + tabl1 +
" WHERE " + name + " = ? ", selectionArgs
);
selectionArgs : this takes the 'name' you desire to compare with, as argrument.
Here note "A Cursor object, which is positioned before the first entry of the table you refer to".
So,to move to first entry :
c.moveToFirst();
getColumnIndex(String ColumnName) : this returns the zero-based column index for the given column name.
tv.setText(c.getString(c.getColumnIndex("email")));
In case, you want to go searching through multiple rows for a given name under 'name' column then use loop as below:
if (cursor.moveToFirst()){
do{
////go traversing through loops
}while(cursor.moveToNext());
}
This should solve the problem.