Обновление Android Studio sqlite - PullRequest
0 голосов
/ 16 мая 2019

Я создал таблицу sqlite, в которую я могу вставить данные для своего приложения Trip. Я пытаюсь обновить строки, но я не могу понять это. Я много искал, но я делаю что-то не так в части обновления, и я не знаю что.

public static final String DATABASE_NAME = "triptracker.db";
public static final String TABLE_NAME = "trip_table";
public static final String COL_1 = "trip_id";
public static final String COL_2 = "trip_title";
public static final String COL_3 = "trip_description";
public static final String COL_4 = "trip_image";
public static final String COL_5 = "trip_location";

Когда я вставляю данные:

public boolean insertData(String title, String description, String location) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, title);
        contentValues.put(COL_3, description);
        // contentValues.put(COL_4, image);
        contentValues.put(COL_5, location);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;

    }


//When I'm updating the database

public boolean update(String title, String description, String location){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, title);
        contentValues.put(COL_3, description);
        contentValues.put(COL_5, location);
        db.update(TABLE_NAME,contentValues, "location=?", new String[]{location} );
        return true;

    }

// I need to press a button in order to save the data
        saveItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

              if(!editLocation.getText().toString().equals("") && !editTitle.getText().toString().equals("") && !editDescription.getText().toString().equals("")){
                    boolean insert = myDb.update(editLocation.getText().toString(),
                            editDescription.getText().toString(),
                            editTitle.getText().toString());
                }
                else {
                    Toast.makeText(singlemomentactivity.this, "Your moment is not added ", Toast.LENGTH_LONG);
                }

Ответы [ 3 ]

3 голосов
/ 16 мая 2019

Попробуйте, может быть, ключевая ссылка - это проблема.Но дай мне знать, когда попробуешь.

public static final String DATABASE_NAME = "triptracker.db";
 public static final String TABLE_NAME = "trip_table";
public static final String COL_1 = "trip_id";
public static final String COL_2 = "trip_title";
public static final String COL_3 = "trip_description";
public static final String COL_4 = "trip_image";
public static final String COL_5 = "trip_location";
public static final String COL_6 = "ID";


//oncreate method of SQLite DB

@Override
public void onCreate(SQLiteDatabase db) {

    //Create Search Table

    String EXAMPLE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
            + COL_6 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COL_1 + " TEXT UNIQUE,"
            + COL_2 + " TEXT,"
            + COL_3 + " TEXT,"
            + COL_4 + " TEXT,"
            + COL_5 + " TEXT,"
            + ")";

    db.execSQL(EXAMPLE_TABLE);
  }


public boolean update(String title, String description, String location){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, title);
    contentValues.put(COL_3, description);
    contentValues.put(COL_5, location);

     //code for only if location is updated
     if(//location needs to be updated){

      ContentValues values = new ContentValues();
            values.put(COL_5,location);
            db.update(SarathCityLocalDatabase.EXAMPLE_TABLE,values,COL_6 + " = ?",new String[]{location});
     }
    return true;

}
2 голосов
/ 16 мая 2019

Попробуйте обновить эту строку:

db.update(TABLE_NAME,contentValues, "location=?", new String[]{location} );

Для этого:

db.update(TABLE_NAME,contentValues, "trip_location=?", new String[]{location} );
1 голос
/ 16 мая 2019

Передать значение столбца trip_id в качестве параметра:

public boolean update(String tripid, String title, String description, String location){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, title);
    contentValues.put(COL_3, description);
    contentValues.put(COL_5, location);
    return db.update(TABLE_NAME,contentValues, COL_1 + " = ?", new String[]{tripid}) > 0;
}

и вызвать метод:

boolean insert = myDb.update(
  <pass the id's value here>,
  editTitle.getText().toString(),
  editDescription.getText().toString(),
  editLocation.getText().toString()
);

Я изменил порядок параметров, потому что он неверен в вашем коде.
Также ваш метод update() вернет true, если строка будет обновлена ​​с условием > 0

...