I want to get some data from my database I have created using my application. Here is my code
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.select_to_delete);
database = new DatabaseHandler(this);
bundle = getIntent().getExtras();
date = bundle.getString("DATE");
SQLiteDatabase db=database.getWritableDatabase();
Cursor cur=db.rawQuery("SELECT " +TITLE+ " FROM " +TABLE_NAME + " WHERE " + CDATE + "=" + date,null);
int i = cur.getCount();
if(cur !=null){
if (cur.moveToFirst()){
do{
tdate = cur.getString(cur.getColumnIndex("DATE"));
titlearray.add(tdate);
}while(cur.moveToNext());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titlearray);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
}
My table has 5 columns (id, title, date, time, descrption). and have 4 raws. The table is created in another class.
When I run this application it doesn't get the data from the sql table and show it in listview. When I debug it, it shows i=1 and the it returns false to if (cur.moveToFirst()). So it doesn't go inside that if part.
What could my mistake be?
place apostrophe (') around your date
Cursor cur=db.rawQuery("SELECT " +TITLE+ " FROM " +TABLE_NAME + " WHERE " + CDATE + "='" + date+"'",null);
N.B. I am assuming your table creation and other field names are accurate. Also recheck those
Use selection args and you will be avoiding tons of problems:
Cursor cur=db.rawQuery("SELECT " +TITLE+ " FROM " +TABLE_NAME + " WHERE " + CDATE + " = ?", new String[] { date });
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { TITLE}, CDATE + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
if (cursor.moveToFirst()) {
do {
//add to the array
} while (cursor.moveToNext());
}
Related
This question already has an answer here:
Method to excute query and return results
(1 answer)
Closed 9 years ago.
App won't run. This occurs recurrently:
04-05 21:29:09.570: E/AndroidRuntime(1069): Caused by: java.lang.IllegalArgumentException:
Cannot bind argument at index 1 because the index is out of range.
The statement has 0 parameters.
Main - Calling method
Cursor wow = db.trying("Gold");
text = (TextView) findViewById(R.id.textView13);
String quantity = wow.getString(0); //
text.setText(quantity);
DB Handler - Method
public Cursor trying(String vg){
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q, new String[] {vg});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
The problem is
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
In your query you had already specify the parameter for where condition .After that you are again passing it to query
Cursor cursor = db.rawQuery(q, new String[] {vg});
This makes the confusion .So try to change your query
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(q, new String[] {vg});
OR you go for another approach
String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name=" + "'" + vg +"'";
Cursor cursor = db.rawQuery(q, null);
if(cursor != null && cursor.getCount()>0){
cursor.moveToFirst();
//do your action
//Fetch your data
}
else {
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
return;
}
Refer
Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}
name = namebox.getText().toString();
db.open();
Cursor c1 = db.executequery("SELECT _id FROM " + DATABASE_TABLE_CUSTOMER + " where name='" +name+"'" );
_id = c1.getInt(c1.getColumnIndex("name"));
Cursor c2 = db.executequery("SELECT amount FROM " + DATABASE_TABLE_CUSTOMER
+
" where _id=" + _id);
Double amount = c2.getDouble(c2.getColumnIndex("amount"));
Cursor c3 = db.executequery("SELECT arrear FROM " + DATABASE_TABLE_CUSTOMER + " where CUSTOMER_ID =" + _id);
arrear = c3.getDouble(c3.getColumnIndex("arrear"));
db.close();
This is giving me a bad request for field error. The method executequery on my adapter looks like this:
public Cursor executequery(String query) throws SQLException
{
Cursor mCursor = db.rawQuery(query, null);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
Can anyone please tell me what Im doing wrong. Im new at this.
You are being inconsistent when dealing with Cursor1. getColumnIndex("name") cannot succeed because IDs, not names are being SELECTed. It should read getColumnIndex("_id").
Actually I am working on this for the last 3 or 4 weeks but have not able to resolve it.
I am working on Sqlite Database in android in which I have used a date picker control in my activity Once a user sets a date then i'll stored the date into the string and then sends it to the database it is working fine but when i tried to retrieve the date on the basis of date set on date picker control then it doesn't give me the desired output it show the only a line which is opening a database on my catlog.
Database Class
//Table Definition with Columns
private static final String CREATE_MYCOMPANY =
"create table company " + " (" + "_id" + " integer primary key autoincrement, "
+ "company_date" +" date);";
//Insert Method
public long create(String str) {
ContentValues args = new ContentValues();
args.put(KEY_COMPANY_DATE, str);
return mDb.insert(MYCOMPANY, null,args);
}
//Method For Fetching the row on the basis of Date.//
public Cursor fetchdate(String datr) throws SQLException, ParseException {
Cursor mCursor =
mDb.query(true, MYCOMPANY, new String[] {KEY_COMPANY_ID,
KEY_COMPANY_DATE}, KEY_COMPANY_DATE /*+" BETWEEN date('2012-6-10') AND date('2012-6-14')"*/
+ " = " + datr, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Activity Class Code
//Date picker
DatePicker dt = (DatePicker)findViewById(R.id.datePicker1);
//Converting the Date into the string format
String day = String.valueOf(dt.getYear())+"-" +String.valueOf(dt.getMonth() + 1)
+"-"+String.valueOf(dt.getDayOfMonth());
//Method for displaying the rows of table on date basis
public void DisplayAllCmpData(){
employeeTable.open();
try{
Cursor c = employeeTable.fetchdate("2012-6-13");
if (c.moveToFirst())
{
do {
System.out.println("bool2");
DisplayCmpTitle(c);
} while (c.moveToNext());
}
}catch(Exception e){
System.out.println(e);
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
employeeTable.close();
}
//Function For Displaying the all record.//
public void DisplayCmpTitle(Cursor c)
{
System.out.println("bool");
Toast.makeText(this,
"ID: " + c.getString(0) + "\n" +
"DATE: " + c.getString(1)
, Toast.LENGTH_LONG).show();
}
Thanks for any help in advance!!!!!!
mDb.query(true, MYCOMPANY, new String[] {KEY_COMPANY_ID,
KEY_COMPANY_DATE}, KEY_COMPANY_DATE /*+" BETWEEN date('2012-6-10') AND date('2012-6-14')"*/
+ " = '" + datr+"'", null,
null, null, null, null);
I have a database table with several columns in it. I want to select certain rows by comparing a string entered by a user and select records based on their entry. I have the following code:
SearchbyIngredient.Java
final Button searchbutton1 = (Button) findViewById(R.id.searchbutton1);
searchbutton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Cursor temp = dbIngredientHelper.getDrinks(textView.getText().toString());
String ingred = temp.getString(0);
Context context = getApplicationContext();
iadapter = new IngredientAdapter(temp);
myListView.setAdapter(iadapter);
}
});
}
IngredientHelper.Java
public Cursor getDrinks(String drinkName) throws SQLException{
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME2);
String selection = COLUMN_INGRED1 + "= ' " + drinkName + "'";
String[] asColumnsToReturn = new String[] { COLUMN_ID2, COLUMN_DRINKNAME, COLUMN_INGRED1, COLUMN_AMT1, COLUMN_INGRED2, COLUMN_AMT2, COLUMN_INGRED3, COLUMN_AMT3, COLUMN_INGRED4, COLUMN_AMT4 };
Cursor mCursor2 = queryBuilder.query(dbSqlite, asColumnsToReturn, selection, null, null, null, COLUMN_DRINKNAME);
/*Cursor mCursor = dbSqlite.query(true, TABLE_NAME2, new String[]{
COLUMN_DRINKNAME},
COLUMN_INGRED1 + "= ' " + drinkName + "'", null, null, null, null, null);
if (mCursor != null){
mCursor.moveToFirst();
}*/
mCursor2.moveToFirst();
return mCursor2;
}
My question is regarding
String selection = COLUMN_INGRED1 + "= ' " + drinkName + "'";
This code currently works, however it only finds entries with the user's text in COLUMN_INGRED1 (only a single column in the code). How can I format the statement or make a series of statements so that it also looks for the user's text in COLUMN_INGRED2, COLUMN_INGRED3 and COLUMN_INGRED4? Thank you
Standard SQL applies, use an OR:
COLUMN_INGRED1 + "= ' " + drinkName + "' OR " COLUMN_INGRED2 + "= '" +drinkName + "'" ...;
Note that = will do an exact match, you might want to look into the LIKE operator.