2014-11-18 4 views
0

Я запускаю приложение на устройстве. Ниже приведен класс вспомогательной базы данных, который я создал.Создана база данных, но записи нет записей.

public class DatabaseHandler extends SQLiteOpenHelper { 

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

    // Database Name 
    @SuppressLint("SdCardPath") 
    private static final String DATABASE_NAME = "/mnt/sdcard/destinationManager.db"; 

    // Contacts table name 
    private static final String TABLE_DESTINATIONS = "Destination"; 

    // Contacts Table Columns names 
    private static final String KEY_ID = "id"; 
    private static final String KEY_ADDRESS = "adress"; 
    private static final String KEY_CITY = "city"; 
    private static final String KEY_COUNTRY = "country"; 
    private static final String KEY_CONTACT = "contact"; 

    public DatabaseHandler(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    // Creating Tables 
    @Override 
    public void onCreate(SQLiteDatabase db) { 
     String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_DESTINATIONS 
       + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ADDRESS 
       + " TEXT," + KEY_CITY + " TEXT," + KEY_COUNTRY + "TEXT," 
       + KEY_CONTACT + "TEXT)"; 
     db.execSQL(CREATE_CONTACTS_TABLE); 
    } 

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

     // Create tables again 
     onCreate(db); 
    } 

    /** 
    * All CRUD(Create, Read, Update, Delete) Operations 
    */ 

    // Adding new contact 
    public void addDestination(Destination destination) { 
     SQLiteDatabase db = this.getWritableDatabase(); 

     ContentValues values = new ContentValues(); 
     values.put(KEY_ADDRESS, destination.getAddress()); 
     values.put(KEY_CITY, destination.getCity()); 
     values.put(KEY_COUNTRY, destination.getCountry()); 
     values.put(KEY_CONTACT, destination.getContact()); 

     // Inserting Row 
     db.insert(TABLE_DESTINATIONS, null, values); 
     db.close(); // Closing database connection 
    } 

    // Getting single contact 
    Destination getDestination(int id) { 
     SQLiteDatabase db = this.getReadableDatabase(); 

     Cursor cursor = db.query(TABLE_DESTINATIONS, new String[] { KEY_ID, 
       KEY_ADDRESS, KEY_CITY, KEY_COUNTRY, KEY_CONTACT }, KEY_ID 
       + "=?", new String[] { String.valueOf(id) }, null, null, null, 
       null); 
     if (cursor != null) 
      cursor.moveToFirst(); 

     Destination destination = new Destination(); 
     destination.setid(Integer.parseInt(cursor.getString(0))); 
     destination.setAddress(cursor.getString(1)); 
     destination.setCity(cursor.getString(2)); 
     destination.setCountry(cursor.getString(3)); 
     destination.setContact(cursor.getString(4)); 

     return destination; 
    } 

    // Getting All Contacts 
    public ArrayList<Destination> getAllDestinations() { 
     ArrayList<Destination> contactList = new ArrayList<Destination>(); 
     // Select All Query 
     String selectQuery = "SELECT * FROM " + TABLE_DESTINATIONS; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       Destination destination = new Destination(); 
       destination.setid(Integer.parseInt(cursor.getString(0))); 
       destination.setAddress(cursor.getString(1)); 
       destination.setCity(cursor.getString(2)); 
       destination.setCountry(cursor.getString(3)); 
       destination.setContact(cursor.getString(4)); 

       // Adding contact to list 
       contactList.add(destination); 
      } while (cursor.moveToNext()); 
     } 

     // return contact list 
     return contactList; 
    } 

    // Updating single contact 
    public int updateContact(Destination destination) { 
     SQLiteDatabase db = this.getWritableDatabase(); 

     ContentValues values = new ContentValues(); 
     values.put(KEY_ADDRESS, destination.getAddress()); 
     values.put(KEY_CITY, destination.getCity()); 
     values.put(KEY_COUNTRY, destination.getCountry()); 
     values.put(KEY_CONTACT, destination.getContact()); 

     // updating row 
     return db.update(TABLE_DESTINATIONS, values, KEY_ID + " = ?", 
       new String[] { String.valueOf(destination.getid()) }); 
    } 

    // Deleting single contact 
    public void deleteDestination(Destination destination) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(TABLE_DESTINATIONS, KEY_ID + " = ?", 
       new String[] { String.valueOf(destination.getid()) }); 
     db.close(); 
    } 

    // Getting contacts Count 
    public int getDestinationCount() { 
     Cursor cursor = null; 
     int count = 0; 
     SQLiteDatabase db = null; 
     try { 
      String countQuery = "SELECT * FROM " + TABLE_DESTINATIONS; 
      db = this.getWritableDatabase(); 
      cursor = db.rawQuery(countQuery, null); 
      synchronized (db) { 
       count = cursor.getCount(); 
      } 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } finally { 
      if (db != null && db.isOpen()) { 
       cursor.close(); 
       db.close(); 
      } 
     } 
     // return count 
     return count; 
    } 
} 

База данных создает, но я не могу вставлять записи, хотя ошибка не возникает. После insetting записи, я читаю базу данных и подсчета записей, но получение 0.

Destination destination = new Destination(); 
      destination.setAddress(address.getText().toString()); 
      destination.setCity(city.getText().toString()); 
      destination.setCountry(country.getText().toString()); 
      destination.setContact(MyApplication.GetData().getContacts()); 
      DatabaseHandler db = new DatabaseHandler(
        DestinationDetailActivity.this); 
      db.addDestination(destination); 
      int count = db.getDestinationCount(); 
+0

Почему вы завершаете свой 'rawQuery' в' catch (Exception ex) '. Я на 99% уверен, что у вас есть источник вашей проблемы. –

+0

Так что вы предлагаете? – Nitish

+0

Почему голос? – Nitish

ответ

1
KEY_COUNTRY + "TEXT," 
    + KEY_CONTACT + "TEXT)"; 

Вы недостающие пробелы здесь между именем столбца и типом. Добавьте пробелы. Удалите приложение, чтобы была удалена старая база данных с именами столбцов, такими как countryTEXT, и onCreate() выполняется снова.

+0

В этом была проблема. Сильное наблюдение. благодаря – Nitish

Смежные вопросы