search in SQLite android java not work - java

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.

Related

no such column: ٤۹۸ (code 1):

I translated my app using android studio translation editor, i get this error when running my application on android phone using Arabic as its language:
android.database.sqlite.SQLiteException: no such column: ٤۹۸ (code 1): , while compiling: SELECT * FROM photos WHERE store_id = ٤۹۸ ORDER BY photo_id ASC
The method in app_id > java > com > db > Queries is:
public ArrayList<Photo> getPhotosByStoreId(int storeId) {
ArrayList<Photo> list = new ArrayList<Photo>();
db = dbHelper.getReadableDatabase();
String sql = String.format("SELECT * FROM photos WHERE store_id = %d", storeId);
Cursor mCursor = db.rawQuery(sql, null);
mCursor.moveToFirst();
if (!mCursor.isAfterLast()) {
do {
Photo entry = formatPhoto(mCursor);
list.add(entry);
} while (mCursor.moveToNext());
}
mCursor.close();
dbHelper.close();
return list;
}
use the full set of method arguments for rawQuery to properly escape your values for use in a sql statement.
...
ArrayList<Photo> list = new ArrayList<Photo>();
db = dbHelper.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM photos WHERE store_id = ?",
new String[] { storeId });
mCursor.moveToFirst();
...
The problem is that you are using String.format(String, Object ...), which uses the default locale for formatting. Arabic uses different digits, causing your query to include characters that does not match what is found in your SQLite database.
To solve this, you could either avoid using String.format() and just do:
String sql = "SELECT * FROM photos WHERE store_id = " + storeId;
Or, if you for some reason still want string.format(), you could do:
Locale locale = Locale.Builder().setLanguage("en").setRegion("US").build();
String sql = String.format(locale, "SELECT * FROM photos WHERE store_id = %d", storeId);

How can I implement a String variable instead of 'Landschaft'?

I have created a SpinnerActivity, which looks like following:
http://img4.fotos-hochladen.net/uploads/bildschirmfotovse8j4po1t.png
Now for example if I select 'Landschaft' (in English: landscape) I want to search in the DatabaseHandler.java for a location which is in the category 'Landschaft' (landscape)
Therefore I have written the following method in DatabaseHandler.java:
In this method, I have just written Kategorie = Landscape.
However I want, that the selected SpinnerArray (Landschaft, Brücken...etc.) in my Spinner would be inserted in my DatabaseHandler instead of "Landschaft", how can I do that?
public List<Position> getAllPositionsWithCategory() {
List<Position> positionList = new ArrayList<Position>();
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = 'Landschaft'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Position position = new Position();
position.setID(Integer.parseInt(cursor.getString(0)));
position.setName(cursor.getString(1));
position.setKategorie(cursor.getString(2));
position.setLaenge(cursor.getFloat(3));
position.setBreite(cursor.getFloat(4));
// Adding position to list
positionList.add(position);
} while (cursor.moveToNext());
}
}
Simply replace the the fixed String with ? in your query, and pass the value to be inserted in the second argument of db.rawQuery().
The following might work for your case:
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = ?";
// ...
Cursor cursor = db.rawQuery(selectQuery, new String[] { "Landschaft" });
You can now replace your String "Landschaft" with a variable of your choice.
See also: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String,%20java.lang.String[])

Android sqlite data retriever

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"

How to create filter

I have a database table with multiple columns
I use custom List<> and populate it from database
What i want to do is filter what will go into the list from database depending on user input
for example if i had a table like this:
name|phone|date|address
User can specify any filter(by name, by phone, by date... or all of it) and only items that matches all criteria will go into the list
Is there a way to do this?
Method that returns all items from database
public List<MoviesDatabaseEntry> getAllMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
MoviesDatabaseEntry list = new MoviesDatabaseEntry();
list.set_id(Integer.parseInt(cursor.getString(0)));
list.set_title(cursor.getString(1));
list.set_runtime(cursor.getString(2));
list.set_rating(cursor.getDouble(3));
list.set_genres(cursor.getString(4));
list.set_type(cursor.getString(5));
list.set_lang(cursor.getString(6));
list.set_poster(cursor.getString(7));
list.set_url(cursor.getString(8));
list.set_director(cursor.getString(9));
list.set_actors(cursor.getString(10));
list.set_plot(cursor.getString(11));
list.set_year(cursor.getInt(12));
list.set_country(cursor.getString(13));
list.set_date(cursor.getInt(14));
// Adding to list
lists.add(list);
} while (cursor.moveToNext());
}
// return list
db.close();
cursor.close();
return lists;
}
You can filter the entries you get in the SQL query you are building in this line:
String selectQuery = "SELECT * FROM " + table;
To filter the dataset your retrieve, you would add a WHERE clause to it. When you would, for example, only want those entries where the rating is over 3, you would change this to:
String selectQuery = "SELECT * FROM " + table + " WHERE rating > 3";
SQL is a very powerful language which offers a lot of possibilities. It's an essential skill when you work with relational databases. When you want to learn it, I can recommend you the interactive tutorial website http://sqlzoo.net/
You have to change your database query for getting specific data from the query.
You have one function that returns all rows from database like so: getAllMovies(String table)
Here you are using:
String selectQuery = "SELECT * FROM " + table;
Make a new function like this:
public List<MoviesDatabaseEntry> getSelectedMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
Cursor cursor = db.query(true, TABLE_NAME, new String[] { <your row names> },
**check condition(as string)**, null,
null, null, null, null);
...
}
Now just call this function when required with your specific query string
Make as many functions as you want!

Problem with the Android List View Implementation from Database Records

Thanks a lot for the previous answered questions.Now, I am developing an application having the database implementation. I used the database queries to retrieve the data from Database but unable to display the retrieved data records as a list of an activity. Please suggest me with the sample code.
1)u need to add data to arraylist and set the arryalistobject to setlistadapter.2)
ArrayList results = new ArrayList();
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM MY_TABLE ",null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("KEY_ID"));
// System.out.println("this is first activity"+firstName);
String firstName = c.getString(c.getColumnIndex("First_Name"));
String lastName = c.getString(c.getColumnIndex("Last_Name"));
//System.out.println("this is first activity====age"+age);
results.add("" + firstName + ",lastName: " + lastName);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

Categories