Android sqlite data retriever - java

SQLiteDatabase db = new MySQLiteOpenHelper(this).getReadableDatabase();
String table = SQLContract.tables.Score.TABLE_NAME;
String [] columns = {SQLContract.tables.Score._ID,SQLContract.tables.Score.COLUMN_NAME_player_Name,SQLContract.tables.Score.COLUMN_NAME_Score};
String selection = null;
String [] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
int [] to = {android.R.id.text1};
String [] from = { SQLContract.tables.Score.COLUMN_NAME_player_Name};
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(sca);
I want to display data on list view bt this code is not workin......Some one help about this....???
This is error (1) no such column: _id

int [] to = {android.R.id.text1};
Assign it the value of your Primary key Column for say "_id"
The Way You are assiging to
String [] from = { SQLContract.tables.Score.COLUMN_NAME_player_Name};
in from you show the Value that you want to display in List.
in To you bind the Value that you want to reutrn when list item is clicked.
MoreOver
Rename your primary key ColumnName to "_id" you are not extending the BaseAdapter so you have to stick with their already defined column name "_id"

Related

How can I search all columns of a table in Android Studio using SQL database

I have an Android app with a SQL database that has 4 columns. I would like to search all 4 columns in the database however I can only get 1 to be searched.
I'm not quite sure on how to get it to search all 4 columns.
All 4 Columns are displayed but I can only search one. I can not seem to get it to search all 4 columns.
the code I'm using to get it to search one column is
#SuppressLint("Range")
public List<Data> getDataByVARIETY (String VARIETY) {
variety = VARIETY;
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"VARIETY", "COMMODITY", "PLU", "BOTANICAL"};
String tableName = "data";
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
List<Data> result = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setCOMMODITY(cursor.getString(cursor.getColumnIndex("COMMODITY")));
data.setVARIETY(cursor.getString(cursor.getColumnIndex("VARIETY")));
data.setPLU(cursor.getString(cursor.getColumnIndex("PLU")));
data.setBOTANICAL(cursor.getString(cursor.getColumnIndex("BOTANICAL")));
result.add(data);
} while (cursor.moveToNext());
}
return result;
}
so all i had to do was
change this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
to this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
String conditions = "COMMODITY LIKE ? OR PLU LIKE ? OR VARIETY LIKE ?";
String par;
par = "%"+COMMODITY+"%";
Cursor cursor = db.query(tableName, sqlSelect, conditions, new String[]{par, par, par}, null, null, null);

search in SQLite android java not work

I am trying to fetch data from sqlite data base .I already have a table for employees and I want to fetch employee info by employee name.I already created a function in the database helper like this:
public List getEmpdat(String empname) {
final String TABLE_NAME = "Employee";
String selectQuery = "SELECT * FROM Employee where EmployeeName="+empname;
SQLiteDatabase db = this.getReadableDatabase();
List<String> li = new ArrayList<String>();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
// String name =null;
if (cursor.moveToFirst()) {
do {
String name=cursor.getString(2);
String notes=cursor.getString(3);
String strdate=cursor.getString(4);
if(strdate==null)
strdate = "0";
String gate=cursor.getString(6);
if(gate==null)
gate = "0";
String enddate=cursor.getString(5);
if(enddate==null)
enddate = "0";
li.add(name);
li.add(notes);
li.add(strdate);
li.add(enddate);
li.add(gate);
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return li;
}
and then call it in the search activity like this :
db=new DataBaseHelper(this);
data = (GridView) findViewById(R.id.gridView);
List<String> li = new ArrayList<String>();
li = db.getEmpdat(editName.getText().toString());
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, li);
dataAdapter.setDropDownViewResource(R.layout.activity_search);
dataAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, li);
data.setAdapter(dataAdapter);
but there is a problem taking place from the logcat the problem is
" java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.university.newapp/com.example.university.newapp.SearchActivity}: android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: SELECT * FROM Employee where EmployeeName=
"
can any one provide help with this issue please
Try to change the line where exception occurred and check if it works.
String selectQuery = "SELECT * FROM Employee where EmployeeName='"+empname+"'";
You can use placeholder in querying, like that,
String query = String.format("SELECT * FROM Employee WHERE EmployeeName='%s'",empname);
You will see '%s',it serve as placeholder and your variable value will be insert to placeholder when querying.
So, '%s' can be use for String placeholder and if you want for Digit , you can use '%d'.I hope this will help for you.

Android SQLlite Get List of Columns from Empty Table

Using Android SQL, I'm trying to get a list of the columns from an SQL table which is empty.
Here is what I have tried so far:
SQLiteDatabase db = getReadableDatabase();
ArrayList<String> output = new ArrayList<String>();
Cursor ti = db.rawQuery("PRAGMA table_info("+myTable+")", null);
if ( ti.moveToFirst() ) {
do {
output.add(ti.getString(1));
} while (ti.moveToNext());
}
ti.close();
db.close();
return output;
The resulting list Appears just the word INTEGER, while the database has many columns. How can I make this work?
this is i use to retrieve column name in string:
SQLiteDatabase mDataBase;
(some code here...)
mDataBase = getReadableDatabase();
Cursor dbCursor = mDataBase.query(TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
or this :
Cursor c = db.rawQuery("SELECT * FROM table WHERE 0", null);
try {
String[] columnNames = c.columnNames();
} finally {
c.close();
}
The column name is returned in the column named name:
...
int nameColIdx = ti.getColumnIndexOrThrow("name");
...
output.add(ti.getString(nameColIdx));
...

How to pass dynamic values to a Query using SQLITE in Android ?

i am trying to pass dynamic id to query every time no of passed id will change sometimes it may be 3 or 2 or etc.My question is how can i pass this id and select values from query.
String[] splits = clickedTopicIdString.split("-");
Log.i("splits",""+splits.length); // length 2 bcoz clickedTopicIdString = 0-1 it may be 0-1-2 etc
if(splits.length > 0)
{
for(int i=0;i<splits.length;i++)
{clickedTopicIdInt = Integer.parseInt(splits[i]);// i want to save values in an array and pass it GetQuestionData(); this method after converting it in integer.....
Log.i("clickedTopicIdInt",""+clickedTopicIdInt);
}
}
clickedTopicIdInt = Integer.parseInt(clickedTopicIdString);
dbhelper = new JamiaBinoriaDBHelper(context);
dbhelper.open();
GetQuestionData();
This function will recieve id dynamically in form of arrays and will apply it here topic_question.topic_id="+topic_id1+" OR topic_question.topic_id="+topic_id2+" and so on how can i do this?
public List<String> GetClickedIdImages(int topic_id)
{ List<String> questionImageNameList = new ArrayList<String>();
String query = "SELECT topic_question.question_image_name FROM topic_question,topic WHERE topic_question.topic_id="+topic_id+" AND topic.id=topic_question.topic_id";
// Cursor cursor = db.rawQuery("SELECT topic_question.question_image_name FROM topic_question,topic WHERE topic_question.topic_id=1 AND topic.id=topic_question.topic_id",null);
Cursor cursor = db.rawQuery(query,null);
Log.i("Cursor Query Print:",""+query);
if(cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("cursor",""+cursor);
questionImageNameList.add(cursor.getString(0));
Log.i("cursor.getString(2)",""+cursor.getString(0));
cursor.moveToNext();
}
} else {
Log.d("", "Cursor is Null");
Log.d("retrieving all parameters", "count < 0");
}
cursor.close();
return questionImageNameList;
}
can someone please help me in this task ?
If you want to create your select dynamically basing on a list of IDs you shoud this SQL syntax:
SELECT * FROM TABLE WHERE ID IN (id1, id2, ..., idn)
id1,id2 = your ids
http://www.tutorialspoint.com/sqlite/sqlite_where_clause.htm
String numbers = "1-2-3-4-5";
String [] splits = numbers.split("-");
Integer [] realNumbers = new Integer [splits.length];
String sqlSelect = "SELECT * FROM TABLE WHERE ID IN ";
String whereStatement = "(";
for (int i = 0; i<splits.length; i++)
{
realNumbers[i] = Integer.parseInt(splits[i]);
whereStatement += realNumbers[i]+((i == splits.length -1) ? "" :",");
}
whereStatement += ");";
sqlSelect += whereStatement; //your select SELECT * FROM TABLE WHERE ID IN (1,2,3,4,5);

Can't get any data from sqlite db on Android

I have a DB helper that does this function:
public Cursor getCourseNames() throws SQLException {
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",null, COURSE_ROWID, null, null, null, null, null);
}
The table it is pulling from looks like this:
private static final String COURSE_ID = "CourseID";
private static final String COURSE_NAME = "Name";
private static final String COURSE_CODE = "CourseCode";
private static final String COURSE_ROWID = "_id";
private static final String COURSE_CREATE =
"create table " +
"Course" + " ( " +
COURSE_ROWID + " integer primary key autoincrement, " +
COURSE_ID + "integer not null," +
COURSE_NAME + "text not null, " +
COURSE_CODE + "text not null" + ");";
In my main activity I try this and get a null pointer...
public void buildCoursetoChapterList(){
Cursor cursor = dbHelper.getCourseNames();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cursor, null, null);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
Anyone have an idea what my problem is?
I put data into the db earlier on:
if(dbHelper.checkCourseForData() !=null)
{
setContentView(R.layout.classlist);
}
else
{
dbHelper.addFirstClassToDb(course_code, name, course_id);
Log.d+i("Course added to DB", course_code + " " + name + " " + course_id);
}
tried this and still nothing, I want to select all the Name values within Course.
No clue... losing hope.
public Cursor checkCourseForData() throws SQLException {
String[] values = {COURSE_NAME};
Cursor mCursor = mDb.query("Course",values,COURSE_ROWID + "=" + "Name", null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
It should be this
public Cursor getCourseNames() throws SQLException {
String[] values = {COURSE_NAME};
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",values,COURSE_ROWID, null, null, null, null, null);
}
Explanation :
the medthod in the api has been defined as
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
So you need to pass the strings accordingly.
User my example as a reference it works for me
private String name;
private String Events_Table = "events";
private String[] Columns = {"_id", "Name", "Date", "Time_Slot", "Venue", "Details", "EHName", "EHNumber"} ;
private String WhereClause = Columns[1]+"=?" ;
Cursor cursor = db.query(Events_Table, Columns, WhereClause, new String[] {name}, null, null, null);
Consider Reading this
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

Categories