I got a searching function inside my app.
It works almost properly, my problem is it is only catching results that similiar to the searchWord from the begining.
For example:
If searchWord is "ada", the results will be contains all the records that START WITH "ada" but not those that contains "ada" somewhere inside them.
I know it must be just a little modification but this is the first piece of database handling i ever did.
So how must i modify this to search for any contains, and not for starts with?
code:
public Cursor getMatchingFromContacts(String searchWord) throws SQLException {
String queryString = "SELECT _id, full_name FROM "
+ SF_CONTACT_TABLE;
if (searchWord != null) {
searchWord = searchWord.trim() + "%";
queryString += " WHERE " + FULL_NAME + " LIKE ?";
}
String params[] = { searchWord };
if (searchWord == null) {
params = null;
}
try {
Cursor cursor = db.rawQuery(queryString,
params);
if (cursor != null) {
cursor.moveToFirst();
return cursor;
}
} catch (SQLException e) {
Log.e("AutoCompleteDbAdapter", e.toString());
throw e;
}
return null;
}
Just modify your block here:
if (searchWord != null) {
searchWord = "%" + searchWord.trim() + "%";
queryString += " WHERE " + FULL_NAME + " LIKE ?";
}
Try this..
if (searchWord != null)
{
searchWord = "%" + searchWord + "%";
queryString += " WHERE " + FULL_NAME + " LIKE ?";
}
Related
I have given a statement in DBAdapter class as follows
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date ='"+ date +"' AND T.Trans_Type='debit' ORDER BY T.Entry_Time asc";
return db.rawQuery(sql, new String[]{KEY_ACCNO,KEY_ACCCUSTNAME,KEY_TRANSAMOUNT});
My activity calling is given below
public void onClick(View v) {
try {
db.open();
Cursor c = db.gettranscation();
if (c.moveToFirst()) {
do {
DisplayDetails(c);
} while (c.moveToNext());
}
db.close();
} catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Error ", " "+e.getMessage());
}
}
private void DisplayDetails(Cursor c) {
Log.e("",
"KEY_ACCID Id : " + c.getString(0) + "\n" + "KEY_TRANSDATE :"
+ c.getString(1) + "\n" + "KEY_TRANSTYPE : " + c.getString(2));
}
});
But I am getting this error :
Cannot bind argument at index 3 because the index is out of range. The
statement has 0 parameters.
What is the error in my code ??
try this....
String sql = "SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt
FROM TransactionTable T
LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID
WHERE T.Trans_Date =? AND T.Trans_Type=?
ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{"18-08-2014", "debit"});
You're not putting well "SelectionArgs". To put it well in the query you have to add the character "?" where you want this argument.
The official documentation Here
Example:
String sql = "SELECT * FROM USER WHERE id = ?";
db.rawQuery(sql, new String[]{idUser});
EDIT
You aren't using never SelectionArgs because you are binding params directly.
Try this.
return db.rawQuery(sql,null);
I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.
I am trying to do Order by to fetch the records from higher to lower values , but the sorting is not happening, i am getting the records randomly.
Here is my code , please let me know , where i am going wrong:
public void fetchTopRecords() {
int i = 0;
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " ASC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
i++;
} while (c.moveToNext());
}
}
use the below code it will work :
public void fetchTopRecords() {
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " DESC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
} while (c.moveToNext());
}
}
I want to check if a couple of values exists in the database. If they do, the method should return TRUE or FALSE if the cursor is null. But the problem is that it returns TRUE all the time despite the values are not in the database! What have I missed?
// This method check if the combination image path and contact name already exists in database
public boolean checkContentDatabase(String imageFilePath, String contactName) {
String query = "Select * from " + DB_TABLE+ " where " + TABLE_IMAGE_PATH + "='" + imageFilePath + "' and " + TABLE_CONTACT_NAME + "='" + contactName +"' ;";
Cursor c = db.rawQuery(query, null);
if(c != null) // Exists in database
{
return true;
}
else
{
return false;
}
}
Replace your if condition with:
if(c.getCount() > 0)
{
return true;
}
else
{
return false;
}
use c != null && c.getCount() > 0 instead of c != null
public boolean checkContentDatabase(String imageFilePath, String contactName) {
String query = "Select * from " + DB_TABLE+ " where " + TABLE_IMAGE_PATH + "='" + imageFilePath + "' and " + TABLE_CONTACT_NAME + "='" + contactName +"' ;";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.isAfterLast() == false) {
return true;
}
else
{
return false;
}
}
The cursor is not null, because its been created successfully. Only your result set does not exist. Try using "SELECT 1 FROM..." and then check if the result equals 1.
i'm populating a list view to view my record, i've the following code...
super.onCreate(savedInstanceState);
setContentView(R.layout.total);
ArrayList<Object> results = new ArrayList<Object>();
// -- SQLiteOpenHelper dbHelper = new DatabaseHelper(this, SAMPLE_DB_NAME, null, 1);
SQLiteDatabase myDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READONLY, null);
try {
/* Create the Database (no Errors if it already exists) */
myDB.execSQL("PRAGMA foreign_keys = ON;");
// -- openOrCreateDatabase(name, mode, factory)
// myDB = dbHelper.getReadableDatabase();
Cursor c = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAME, null, null, null, null, null, null);
Cursor d = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAMES, null, null, null, null, null, null);
/* Check if our result was valid. */
if (c != null && d != null) {
c.moveToFirst(); // it's very important to do this action otherwise your Cursor object did not get work
d.moveToFirst();
char cust_name = (char) c.getColumnIndex("cust_name");
char pro_name = (char) d.getColumnIndex("pro_name");
int pro_price = (int) d.getColumnIndex("pro_price");
/* Check if at least one Result was returned. */
if (c.isFirst() && d.isFirst()) {
int i = 0;
/* Loop through all Results */
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_name + " (" + pro_name + ": " + pro_price + ")");
} while (c.moveToNext()&& d.moveToNext());
}
}
} catch (SQLiteException e) {
} finally {
if (myDB != null)
myDB.close();
}
// -- android.R.layout.simple_list_item_1 is object which belong to ListActivity itself
// -- you only need to add list object in your main layout file
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, results));
}
total.xml
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="380dp"
android:cacheColorHint="#00000000" >
</ListView>
the data is successfully inserted to sqlite (confirmed from adb shell)...it gives me garbage value...can any one please figure out the issue....Thanks in advance
That is not garbage values references(memory) addresses, use below code it will work.
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_nameColumnIndex + " (" + pro_nameColumnIndex + ": " + pro_priceColumnIndex + ")");
} while (c.moveToNext()&& d.moveToNext());
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, (String[]) results.toArray(new String[0])));
Try changing the way you read your cursors. Something like that might be better:
//Get the indexes
int cust_name = cursor.getColumnIndex("cust_name");
int pro_name = cursor.getColumnIndex("pro_name");
int pro_price = cursor.getColumnIndex("pro_price");
try {
if(cursor.moveToFirst()){
while (!cursor.isAfterLast()) {
//Get the data
String cust_nameColumnIndex = cursor.getString(cust_name);
String pro_nameColumnIndex = cursor.getString(pro_name);
int pro_priceColumnIndex = cursor.getInt(pro_price);
//Move to next cursor item
cursor.moveToNext();
}
}
else {
Log.i(TAG, "Empty cursor");
//Do whatever
}
} catch (Exception e) {
Log.i(TAG, "Exception while reading cursor: " + e.getMessage());
//Do whatever
}
finally {
cursor.close();
}