Zaktualizuj określone pole podmiotu w pokoju Androida

Używam android room persistence library dla mojego nowego projektu. Chcę zaktualizować jakieś pole tabeli. Próbowałem jak w moim Dao-

Metoda 1:

@Dao
public interface TourDao {
    @Update
    int updateTour(Tour tour);
}

Ale kiedy próbuję zaktualizować za pomocą tej metody, to aktualizuje każde pole encji, gdzie pasuje do podstawowej wartości klucza obiektu tour. Użyłem @Query

Metoda 2:

@Query("UPDATE Tour SET endAddress = :end_address  WHERE id = :tid)
     int updateTour(long tid, String end_address);

To działa, ale jest zbyt długie zapytanie w moim przypadku, ponieważ mam wiele pól w moim encji. I chcesz wiedzieć, jak mogę zaktualizować niektóre pola (nie wszystkie), takie jak method 1 gdzie id = 1; (id jest automatycznym generowaniem klucza podstawowego).

Entity:

@Entity
public class Tour {
    @PrimaryKey(autoGenerate = true)
    public long id;
    private String startAddress;
    private String endAddress;
    //constructor, getter and setter
}
Author: Abu Mohammad Rasel, 2017-08-21

3 answers

Chcę wiedzieć, jak mogę zaktualizować niektóre pola (nie wszystkie), takie jak Metoda 1, Gdzie id = 1

Użyj @Query, tak jak w metodzie 2.

Jest zbyt długie zapytanie w moim przypadku, ponieważ mam wiele pól w moim encji

Następnie mają mniejsze byty. Można też nie aktualizować pól pojedynczo, ale zamiast tego mają bardziej gruboziarniste interakcje z bazą danych.

Nie ma w pokoju nic, co zrobi to, czego szukasz.
 23
Author: CommonsWare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-21 11:54:43

Zgodnie z SQLite Update Docs :

<!-- language: lang-java -->
@Query("UPDATE tableName SET 
    field1 = :value1,
    field2 = :value2, 
    ...
    //some more fields to update
    ...
    field_N= :value_N
    WHERE id = :id)

int updateTour(long id, 
               Type value1, 
               Type value2, 
               ... ,
               // some more values here
               ... ,
               Type value_N);

Przykład:

Entity:

@Entity(tableName = "orders")
public class Order {

@NonNull
@PrimaryKey
@ColumnInfo(name = "order_id")
private int id;

@ColumnInfo(name = "order_title")
private String title;

@ColumnInfo(name = "order_amount")
private Float amount;

@ColumnInfo(name = "order_price")
private Float price;

@ColumnInfo(name = "order_desc")
private String description;

// ... methods, getters, setters
}

Dao:

@Dao
public interface OrderDao {

@Query("SELECT * FROM orders")
List<Order> getOrderList();

@Query("SELECT * FROM orders")
LiveData<List<Order>> getOrderLiveList();

@Query("SELECT * FROM orders WHERE order_id =:orderId")
LiveData<Order> getLiveOrderById(int orderId);

/**
* Updating only price
* By order id
*/
@Query("UPDATE orders SET order_price=:price WHERE order_id = :id")
void update(Float price, intid);

/**
* Updating only amount and price
* By order id
*/
@Query("UPDATE orders SET order_amount = :amount, price = :price WHERE order_id =:id")
void update(Float amount, Float price, int id);

/**
* Updating only title and description
* By order id
*/
@Query("UPDATE orders SET order_desc = :description, order_title= :title WHERE order_id =:id")
void update(String description, String title, int id);

@Update
void update(Order order);

@Delete
void delete(Order order);

@Insert(onConflict = REPLACE)
void insert(Order order);
}
 10
Author: Jurij Pitulja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-29 21:08:44

Jeśli chcesz zaktualizować informacje o użytkowniku dla określonego identyfikatora użytkownika "x",

  1. musisz utworzyć klasę dbManager , która zainicjalizuje bazę danych w swoim konstruktorze i działa jako mediator między twoim viewmodelem a DAO, a także .
  2. ViewModel zainicjuje instancję dbManager, aby uzyskać dostęp do bazy danych. Kod powinien wyglądać tak:

       @Entity
        class User{
        @PrimaryKey
        String userId;
        String username;
        }
    
        Interface UserDao{
        //forUpdate
        @Update
        void updateUser(User user)
        }
    
        Class DbManager{
        //AppDatabase gets the static object o roomDatabase.
        AppDatabase appDatabase;
        UserDao userDao;
        public DbManager(Application application ){
        appDatabase = AppDatabase.getInstance(application);
    
        //getUserDao is and abstract method of type UserDao declared in AppDatabase //class
        userDao = appDatabase.getUserDao();
        } 
    
        public void updateUser(User user, boolean isUpdate){
        new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
        }
    
    
    
        public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
    
    
         private UserDao userDAO;
         private boolean isInsert;
    
         public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
           this. userDAO = userDAO;
           this.isInsert = isInsert;
         }
    
         @Override
         protected Void doInBackground(User... users) {
           if (isInsert)
        userDAO.insertBrand(brandEntities[0]);
           else
        //for update
        userDAO.updateBrand(users[0]);
        //try {
        //  Thread.sleep(1000);
        //} catch (InterruptedException e) {
        //  e.printStackTrace();
        //}
           return null;
         }
          }
        }
    
         Class UserViewModel{
         DbManager dbManager;
         public UserViewModel(Application application){
         dbmanager = new DbMnager(application);
         }
    
         public void updateUser(User user, boolean isUpdate){
         dbmanager.updateUser(user,isUpdate);
         }
    
         }
    
    
    
    
    Now in your activity or fragment initialise your UserViewModel like this:
    
    UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    

    Następnie po prostu zaktualizuj swoją pozycję użytkownika w ten sposób, Załóżmy, że twój identyfikator użytkownika to 1122 i nazwa użytkownika jest "xyz", które należy zmienić na"zyx".

    Get a useritem of ID 1122 User object

User user = new user();
 if(user.getUserId() == 1122){
   user.setuserName("zyx");
   userViewModel.updateUser(user);
 }

To jest surowy kod, mam nadzieję, że ci pomoże.

Happy coding

 0
Author: Kunal Parte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 10:38:55