2016-06-07 2 views
0

проверить, если строка уже существует в базе данных SQLite

LogCat error: 
 

 
FATAL EXCEPTION: main 
 
                     Process: com.sam.shoppingcart, PID: 31773 
 
                     android.database.sqlite.SQLiteException: near "Beef": syntax error (code 1): , while compiling: SELECT KEY_NAME FROM shop WHERE KEY_NAME=Corned Beef 
 
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) 
 
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:893) 
 
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:504) 
 
                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 
 
                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) 
 
                      at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) 
 
                      at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44) 
 
                      at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1339) 
 
                      at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1278) 
 
                      at com.sam.shoppingcart.SQLiteHandler.ifExists(SQLiteHandler.java:63) 
 
                      at com.sam.shoppingcart.CustomListAdapter$1.onClick(CustomListAdapter.java:77)

У меня есть ListView с помощью пользовательского адаптера с «Добавить» и «Удалить» кнопку. При нажатии кнопки «Добавить» в базу данных добавляются данные «Имя и цена» элемента LV. Я хочу проверить при добавлении, если элемент LV уже присутствует в БД или нет. Для этого я создал функцию ifExists (модель) в DBHandler. Но теперь при нажатии кнопки «Добавить» это дает мне ошибку. Что я делаю неправильно? PS: Я получил функцию от here.

public class MainActivity extends AppCompatActivity { 
 

 
    private ListView listView; 
 
    private ArrayList<Model> mListData; 
 
    private CustomListAdapter adapter; 
 

 
    @Override 
 
    protected void onCreate(Bundle savedInstanceState) { 
 

 
     super.onCreate(savedInstanceState); 
 
     setContentView(R.layout.activity_main); 
 

 
     listView = (ListView)findViewById(R.id.list); 
 

 

 
     mListData = new ArrayList<>(); 
 

 
     mListData.add(new Model("Beef Manhattan", "50")); 
 
     mListData.add(new Model("Chicken Fried Steak", "90")); 
 
     mListData.add(new Model("Corned Beef", "100")); 
 
     mListData.add(new Model("Domesticated Turkey", "80")); 
 
     mListData.add(new Model("Eggs Benedict", "10")); 
 
     mListData.add(new Model("French Dip", "20")); 
 
     mListData.add(new Model("Green Bean Casserole", "30")); 
 
     mListData.add(new Model("Potato Salad", "40")); 
 
     mListData.add(new Model("Pumpkin Pie", "60")); 
 
     mListData.add(new Model("Salisbury Steak", "70")); 
 

 
     adapter = new CustomListAdapter(this, R.layout.listrow, mListData); 
 
     listView.setAdapter(adapter); 
 

 

 

 
    } 
 

 
    @Override 
 
    public boolean onCreateOptionsMenu(Menu menu) { 
 
     // Inflate the menu; this adds items to the action bar if it is present. 
 
     getMenuInflater().inflate(R.menu.main, menu); 
 
     return true; 
 
    } 
 

 
    @Override 
 
    public boolean onOptionsItemSelected(MenuItem item) { 
 
     // Handle action bar item clicks here. The action bar will 
 
     // automatically handle clicks on the Home/Up button, so long 
 
     // as you specify a parent activity in AndroidManifest.xml. 
 
     int id = item.getItemId(); 
 

 
     //noinspection SimplifiableIfStatement 
 
     if (id == R.id.action) { 
 

 
      startActivity(new Intent(MainActivity.this, NextActivity.class)); 
 
      return true; 
 
     } 
 

 
     return super.onOptionsItemSelected(item); 
 
    } 
 

 
}
public class CustomListAdapter extends ArrayAdapter<Model> { 
 

 
    private Context mContext; 
 
    int resource; 
 
    private ArrayList<Model> mListData = new ArrayList<Model>(); 
 

 

 

 
    public CustomListAdapter(Context mContext, int resource, ArrayList<Model> mListData) { 
 
     super(mContext, resource, mListData); 
 
     this.resource = resource; 
 
     this.mContext = mContext; 
 
     this.mListData = mListData; 
 
    } 
 

 
    public void setListData(ArrayList<Model> mListData) { 
 
     this.mListData = mListData; 
 
     notifyDataSetChanged(); 
 
    } 
 

 
    @Override 
 
    public int getCount() { 
 
     return super.getCount(); 
 
    } 
 

 
    @Override 
 
    public View getView(final int position, View convertView, final ViewGroup parent) { 
 
     View v = convertView; 
 
     final ViewHolder holder; 
 
     if (v == null) { 
 
      holder = new ViewHolder(); 
 

 
      LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); 
 

 
       v = inflater.inflate(resource, parent, false); 
 

 
       holder.name = (TextView) v.findViewById(R.id.name); 
 
       holder.rate = (TextView) v.findViewById(R.id.rate); 
 
       holder.add = (Button) v.findViewById(R.id.add); 
 
       holder.remove = (Button) v.findViewById(R.id.remove); 
 

 

 
      v.setTag(holder); 
 
     } else { 
 
      holder = (ViewHolder) v.getTag(); 
 
     } 
 

 

 

 

 
     final Model item = mListData.get(position); 
 

 
      holder.name.setText(item.getName()); 
 
      holder.rate.setText(item.getRate()); 
 
      holder.add.setOnClickListener(new View.OnClickListener() { 
 
       @Override 
 
       public void onClick(View v) { 
 
        SQLiteHandler db = new SQLiteHandler(getContext()); 
 

 
        if(db.ifExists(item)){ 
 

 

 
         Toast.makeText(getContext(), "Already Present", Toast.LENGTH_SHORT).show(); 
 

 
        }else{ 
 
         db.addItems(holder.name.getText().toString(), holder.rate.getText().toString()); 
 
         Toast.makeText(getContext(), "Added", Toast.LENGTH_SHORT).show(); 
 
        } 
 

 

 
       } 
 
      }); 
 

 
      holder.remove.setOnClickListener(new View.OnClickListener() { 
 
       @Override 
 
       public void onClick(View v) { 
 
        SQLiteHandler db = new SQLiteHandler(getContext()); 
 
        db.deleteItem(item); 
 
        Toast.makeText(getContext(), "Removed", Toast.LENGTH_SHORT).show(); 
 

 
       } 
 
      }); 
 

 
     return v; 
 
    } 
 

 
    class ViewHolder { 
 

 
     TextView name; 
 
     TextView rate; 
 
     Button add; 
 
     Button remove; 
 
    } 
 

 
}
public class SQLiteHandler extends SQLiteOpenHelper { 
 

 
\t private static final String TAG = SQLiteHandler.class.getSimpleName(); 
 

 
\t // All Static variables 
 
\t // Database Version 
 
\t private static final int DATABASE_VERSION = 1; 
 

 
\t // Database Name 
 
\t private static final String DATABASE_NAME = "android_api"; 
 

 
\t // Profile Settings table name 
 
\t private static final String TABLE_SHOP = "shop"; 
 

 
\t // Profile Settings information names 
 
\t private static final String KEY_ID = "id"; 
 
\t private static final String KEY_NAME = "name"; 
 
\t private static final String KEY_PRICE = "price"; 
 

 

 
\t public SQLiteHandler(Context context) { 
 
\t \t super(context, DATABASE_NAME, null, DATABASE_VERSION); 
 
\t } 
 

 
\t // Creating Tables 
 
\t @Override 
 
\t public void onCreate(SQLiteDatabase db) { 
 

 
\t \t String CREATE_PROF_TABLE = "CREATE TABLE " + TABLE_SHOP + "("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_NAME+" TEXT, "+KEY_PRICE+" TEXT" + ")"; 
 

 
\t \t db.execSQL(CREATE_PROF_TABLE); 
 

 
\t \t Log.d(TAG, "Database tables created"); 
 
\t } 
 

 
\t // Upgrading database 
 
\t @Override 
 
\t public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
 
\t \t // Drop older table if existed 
 
\t \t db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHOP); 
 

 
\t \t // Create tables again 
 
\t \t onCreate(db); 
 
\t } 
 

 
\t // Check before adding item if item already exist 
 
\t SQLiteDatabase db = this.getWritableDatabase(); 
 
\t public boolean ifExists(Model model) { 
 
\t \t Cursor cursor = null; 
 
\t \t String checkQuery = "SELECT KEY_NAME FROM "+TABLE_SHOP+" WHERE KEY_NAME="+model.getName(); 
 
\t \t cursor= db.rawQuery(checkQuery,null); 
 
\t \t boolean exists = (cursor.getCount() > 0); 
 
\t \t cursor.close(); 
 
\t \t return exists; 
 
\t } 
 

 

 
    // Add items to db 
 
\t public void addItems(String name, String mobile){ 
 

 
\t \t SQLiteDatabase db = this.getWritableDatabase(); 
 

 
\t \t ContentValues values = new ContentValues(); 
 

 
\t \t values.put(KEY_NAME, name); 
 
\t \t values.put(KEY_PRICE, mobile); 
 

 
\t \t long id = db.insert(TABLE_SHOP, null, values); // insert to 1st row 
 
\t \t db.close(); // Closing database connection 
 

 
\t \t Log.d(TAG, "New products inserted into sqlite: " + id); 
 

 
\t } 
 

 

 

 

 
\t // Fetch all data 
 
\t public ArrayList<HashMap<String, String>> getProfDetails() 
 
    { 
 
     ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>(); 
 

 
     SQLiteDatabase db = this.getReadableDatabase(); 
 
     String selectQuery = "SELECT * FROM " + TABLE_SHOP; 
 
     Cursor res = db.rawQuery(selectQuery, null); 
 
     res.moveToFirst(); 
 

 
     while (res.isAfterLast() == false) 
 
     { 
 
      HashMap<String, String> hashmap= new HashMap<String, String>(); 
 
      hashmap.put("name", res.getString(res.getColumnIndex(KEY_NAME))); 
 
      hashmap.put("price", res.getString(res.getColumnIndex(KEY_PRICE))); 
 

 
      array_list.add(hashmap); 
 
      res.moveToNext(); 
 
     } 
 
     return array_list; 
 
    } 
 

 
\t // Getting Sum of "price" 
 
\t public int sumofPrice(){ 
 
\t \t SQLiteDatabase db = this.getReadableDatabase(); 
 
\t \t String selectQuery = "SELECT SUM(price) FROM " + TABLE_SHOP; 
 
\t \t Cursor cur = db.rawQuery(selectQuery, null); 
 
\t \t int total=0; 
 
\t \t if(cur.moveToFirst()) 
 
\t \t { 
 
\t \t \t total = cur.getInt(0); 
 
\t \t } 
 
\t \t return total; 
 
\t } 
 

 
\t // Delete single row 
 
\t public void deleteItem(Model model) { 
 
\t \t SQLiteDatabase db = this.getWritableDatabase(); 
 
\t \t db.delete(TABLE_SHOP, KEY_NAME + " = ?",new String[] { String.valueOf(model.getName()) }); 
 
\t \t db.close(); 
 
\t } 
 

 
\t // Delete whole table 
 
\t public void deleteTable() { 
 
\t \t SQLiteDatabase db = this.getWritableDatabase(); 
 
\t \t // Delete All Rows 
 
\t \t db.delete(TABLE_SHOP, null, null); 
 
\t \t db.close(); 
 

 
\t \t Log.d(TAG, "Deleted all info from sqlite"); 
 
\t } 
 

 
}

ответ

3

Проверьте ниже указанным способом для ifExists(),

 public boolean ifExists(Model model) 
    { 
     Cursor cursor = null; 
     String checkQuery = "SELECT " + KEY_NAME + " FROM " + TABLE_SHOP + " WHERE " + KEY_NAME + "= '"+model.getName() + "'"; 
      cursor= db.rawQuery(checkQuery,null); 
      boolean exists = (cursor.getCount() > 0); 
      cursor.close(); 
      return exists; 
    } 

Две вещи: во-первых, вы передавали переменную как значение для имени столбца, а во-вторых, вы передавали значение имени с пробелом и без котировки, чтобы оно разбило приложение.

Теперь попробуйте код выше.

+0

Отлично! Большое спасибо, @Vicky –

+0

В любое время ... Наслаждайтесь своим кодом .... – Vickyexpert

+0

Можете ли вы также помочь мне с другим запросом? @Vicky –

1

в вашей ifExists функционировать

String checkQuery = "SELECT KEY_NAME FROM "+TABLE_SHOP+" WHERE KEY_NAME="+model.getName(); 

изменить его

String checkQuery = "SELECT "+KEY_NAME+" FROM "+TABLE_SHOP+" WHERE "+KEY_NAME+"="+model.getName(); 
+0

Извините, но то же @Dixit ошибки –

1
private boolean hasRow(String id) { 
     String selectString = "SELECT * FROM " + tablename + " WHERE " + 
       id + " =?"; 
     sqliteDatabase = getReadableDatabase(); 
     Cursor cursor = sqliteDatabase.rawQuery(selectString, new String[] {id}); 

     boolean hasObject = false; 
     if(cursor.moveToFirst()){ 
      hasObject = true; 
     } 

     cursor.close(); 
     sqliteDatabase.close(); //Close the database 
     return hasObject; //return value. 
    } 

Это обнаружит первое появление и скажет да, что эта строка присутствует. Чтобы получить сколько строк присутствуют использование

while(cursor.moveToNext()) { 
count++; 
} 
Смежные вопросы