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

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[])

Related

contentResolver returns null

Instead of using direct query to db im using contentResolver but it returns null. And i dont know do i need to add some code or there is a mistake in mine.
private void displayDatabaseInfo() {
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PetEntry._ID,
PetEntry.COLUMN_PET_NAME,
PetEntry.COLUMN_PET_BREED,
PetEntry.COLUMN_PET_GENDER,
PetEntry.COLUMN_PET_WEIGHT };
// Perform a query on the provider using the ContentResolver.
// Use the {#link PetEntry#CONTENT_URI} to access the pet data.
Cursor cursor = getContentResolver().query(
PetEntry.CONTENT_URI, // The content URI of the words table
projection, // The columns to return for each row
null, // Selection criteria
null, // Selection criteria
null); // The sort order for the returned rows
Log.v(LOG_TAG, "Проверка курсора " + cursor);
TextView displayView = (TextView) findViewById(R.id.text_view_pet);
if (cursor != null){
try {
// Create a header in the Text View that looks like this:
//
// The pets table contains <number of rows in Cursor> pets.
// _id - name - breed - gender - weight
//
// In the while loop below, iterate through the rows of the cursor and display
// the information from each column in this order.
displayView.setText("The pets table contains " + cursor.getCount() + " pets.\n\n");
displayView.append(PetEntry._ID + " - " +
PetEntry.COLUMN_PET_NAME + " - " +
PetEntry.COLUMN_PET_BREED + " - " +
PetEntry.COLUMN_PET_GENDER + " - " +
PetEntry.COLUMN_PET_WEIGHT + "\n");
// Figure out the index of each column
int idColumnIndex = cursor.getColumnIndex(PetEntry._ID);
int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME);
int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED);
int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER);
int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT);
// Iterate through all the returned rows in the cursor
while (cursor.moveToNext()) {
// Use that index to extract the String or Int value of the word
// at the current row the cursor is on.
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currentBreed = cursor.getString(breedColumnIndex);
int currentGender = cursor.getInt(genderColumnIndex);
int currentWeight = cursor.getInt(weightColumnIndex);
// Display the values from each column of the current row in the cursor in the TextView
displayView.append(("\n" + currentID + " - " +
currentName + " - " +
currentBreed + " - " +
currentGender + " - " +
currentWeight));
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
}
Before that i got an error null exception. After added if/else statement exceptions dissapeared but anyway it doesnt work and returns null
Problem was in ContentProvider. I have changed code and now it works.
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Get readable database
SQLiteDatabase database = mDbHelper.getReadableDatabase();
// This cursor will hold the result of the query
Cursor cursor;
// Figure out if the URI matcher can match the URI to a specific code
int match = sUriMatcher.match(uri);
switch (match) {
case PETS:
// For the PETS code, query the pets table directly with the given
// projection, selection, selection arguments, and sort order. The cursor
// could contain multiple rows of the pets table.
cursor = database.query(PetEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
case PET_ID:
// For the PET_ID code, extract out the ID from the URI.
// For an example URI such as "content://com.example.android.pets/pets/3",
// the selection will be "_id=?" and the selection argument will be a
// String array containing the actual ID of 3 in this case.
//
// For every "?" in the selection, we need to have an element in the selection
// arguments that will fill in the "?". Since we have 1 question mark in the
// selection, we have 1 String in the selection arguments' String array.
selection = PetEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
// This will perform a query on the pets table where the _id equals 3 to return a
// Cursor containing that row of the table.
cursor = database.query(PetEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Cannot query unknown URI " + uri);
}
return cursor;
}

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.

SQLite, return data as an array

I have an SQLite Database in my android application with the following structure:
public void onCreate(SQLiteDatabase db) {
String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
"("+
_ID + " INTEGER PRIMARY KEY , " +
NOTE + " TEXT" +
")";
db.execSQL(CREATE_LISTS_TABLE);
}
And this works, in that I can insert data into it without a problem. However I need to store the notes inside an array. I currently have the following query:
public List<String> getAllNotes() {
List<String> notes = new ArrayList<>();
String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;
SQLiteDatabase db = getReadableDatabase();
if(db!=null)
{
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
cursor.moveToNext();
}
cursor.close();
}
db.close();
return notes;
}
However, this gives the following error:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I was wondering how to fix this, I have read the android developer stuff but I can't seem to get anything to work.
Thanks in advance
Check the value of "NOTE", and use it in:
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));
I think a best way to make the call should be something like this:
// Check the cursor
if(cursor != null) {
if (cursor.moveToFirst()) {
// Variables to be used
String note;
// Col position
int colNote = cursor.getColumnIndex(NOTE);
do {
// Get the information
note = cursor.getString(colNote);
// Add the note
notes.add(note);
} while (cursor.moveToNext());
}
// Close the cursor
cursor.close();
}
Because you are fetching only integer and string from database, instead of using ArrayList , you can try using HashMap. So you can get the value by just giving the key. Below simple code will work for ArrayList too with minor changes..
Try this
HashMap<Integer,String> notes = new HashMap<Integer,String>() ;
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
while (cursor.moveToNext())
{
int i = cursor.getInt(0);
String s = cursor.getString(1);
notes.put (i,s) ;
}
cursor.close();

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);

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!

Categories