【问题标题】:how to update database using room persistance library and livedata如何使用房间持久性库和 livedata 更新数据库
【发布时间】:2018-03-20 06:01:41
【问题描述】:

我正在尝试使用 Room persistence LibraryLivedata 更新我的数据库。我对 java 很陌生,所以,通过手册和各种教程,我已经设置了 DAO、实体等。但我仍然在为如何实际添加数据而苦苦挣扎。

这是我的数据库定义:

@Entity
public class PlaceSaved {

  @PrimaryKey(autoGenerate = true)
  private int id;
  private String place;
  private String lati;
  private String longi;


  public PlaceSaved(String place, String lati, String longi) {
    this.place = place;
    this.lati = lati;
    this.longi = longi;
  }

  public String getPlace() {
    return place;
  }
  public void setPlace(String place) {
    this.place = place;
  }

  public String getLongi() {
    return longi;
  }
  public void setLongi(String longi) {
    this.longi = longi;
  }


  public String getLati() {
    return lati;
  }
  public void setLati(String lati) {
    this.lati = lati;
  }

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
}

DAO

@Dao
public interface DatabaseInterface {
  @Query("SELECT * FROM placesaved")
  LiveData<List<PlaceSaved>> getAllItems();

  @Insert
  void insertAll(PlaceSaved... placeSaveds);
  @Delete
  void delete(PlaceSaved... placeSaveds);
  @Update
  void update(PlaceSaved... placeSaveds);
}

适配器

public class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.RecyclerViewHolder>{
  private List<PlaceSaved> items;
  private View.OnClickListener ClickListener;

  public  PlacesAdapter(List<PlaceSaved> items){//}, View.OnClickListener ClickListener) {
        this.items = items;
        //this.ClickListener = ClickListener;
  }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new RecyclerViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.places_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
        PlaceSaved placeSaved = items.get(position);
        holder.itemTextView.setText(placeSaved.getPlace());
        holder.nameTextView.setText(placeSaved.getLati());
        holder.dateTextView.setText(placeSaved.getLongi());
/*        holder.dateTextView.setText(borrowModel.getBorrowDate().toLocaleString().substring(0, 11));
        holder.itemView.setTag(borrowModel);
        holder.itemView.setOnLongClickListener(longClickListener);*/
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public void addItems(List<PlaceSaved> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    static class RecyclerViewHolder extends RecyclerView.ViewHolder {
        private TextView itemTextView;
        private TextView nameTextView;
        private TextView dateTextView;

        RecyclerViewHolder(View view) {
            super(view);
            itemTextView = (TextView) view.findViewById(R.id.firstLine);
            nameTextView = (TextView) view.findViewById(R.id.secondLine);
            dateTextView = (TextView) view.findViewById(R.id.longitude);
        }
    }
}

ViewModel

public class PlacesViewModel  extends AndroidViewModel {
  private final LiveData<List<PlaceSaved>> PlacedatabaseList;

  private PlaceDatabase appDatabase;

  public PlacesViewModel(Application application) {
    super(application);

    appDatabase = PlaceDatabase.getDatabase(this.getApplication());

    PlacedatabaseList = appDatabase.PlacedatabaseInterface().getAllItems();
  }


  public LiveData<List<PlaceSaved>> getPlaceList() {
    return PlacedatabaseList;
  }

  public void deleteItem(PlaceSaved placeSaved) {
    new deleteAsyncTask(appDatabase).execute(placeSaved);
  }

  private static class deleteAsyncTask extends AsyncTask<PlaceSaved, Void, Void> {

    private PlaceDatabase db;

    deleteAsyncTask(PlaceDatabase appDatabase) {
      db = appDatabase;
    }

    @Override
    protected Void doInBackground(final PlaceSaved... params) {
      db.PlacedatabaseInterface().delete(params[0]);
      return null;
    }

  }
}

现在,我正在尝试使用 OnClickfab 将项目添加到数据库:

public class PlacesActivity extends AppCompatActivity {
  private PlacesViewModel viewModel;
  private PlacesAdapter placesAdapter;
  private RecyclerView recyclerView;
  FloatingActionButton fab, fab1, fab2, fab3;
  LinearLayout fabLayout1, fabLayout2, fabLayout3;
  boolean isFABOpen = false;
  View fabBGLayout;
  PlaceDatabase db;


  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.places_layout);

    viewModel = ViewModelProviders.of(this).get(PlacesViewModel.class);

    Runnable r =new Runnable() {
      @Override
      public void run() {
        recyclerView = findViewById(R.id.my_recycler_view);
        placesAdapter = new PlacesAdapter(new ArrayList<PlaceSaved>());//, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplication()));
        recyclerView.setAdapter(placesAdapter);
      }
    };

    Thread newThread = new Thread(r);
    newThread.start();

    fab1.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        //Dialog
/*
    Add location manually
*/
        AlertDialog.Builder placeLLDialog = new AlertDialog.Builder(PlacesActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        final View view = inflater.inflate(R.layout.place_add_dialog, null);

        placeLLDialog.setView(view);

        final EditText todo = view.findViewById(R.id.placeN);
        final EditText time = view.findViewById(R.id.placell);
        final EditText longi = view.findViewById(R.id.placell2);
        placeLLDialog.setTitle("Add Place with Latitude and Longitude")
          .setPositiveButton("Add", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialogInterface, int i) {
                if (!todo.getText().toString().equals("") &&
                  !time.getText().toString().equals("") &&
                  !longi.getText().toString().equals("")) {
                    Snackbar.make(view, "Running", Snackbar.LENGTH_LONG).show();

                  /* HERE I AM TRYING TO ADD THE DATA, WHICH IS NOT WORKING
                   final PlaceSaved placeSaved = new PlaceSaved(todo.getText().toString(),
                    time.getText().toString(), longi.getText().toString());
                    AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {
                      db.databaseInterface().insertAll(placeSaved);
                      items = db.databaseInterface().getAllItems();
                      runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                          adapter = new PlacesAdapter(items, db, null);
                          adapter.notifyDataSetChanged();
                          recyclerView.setAdapter(adapter);
                          closeFABMenu();
                        }
                      });
                    }
                });*/
                }
              }
          })
          .setNegativeButton("Cancel", null);

        AlertDialog alertDialog = placeLLDialog.create();
        alertDialog.show();
        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
      }
    });

由于我对java很陌生,所以我不知道如何将数据添加到数据库中,在fab1.setOnClickListner里面。

如果有人能提供帮助,我将不胜感激。

更新 我忘了添加数据库本身,这里是:

@Database(entities = {PlaceSaved.class},version = 1)
public abstract class PlaceDatabase extends RoomDatabase {
  private static PlaceDatabase INSTANCE;
  public static PlaceDatabase getDatabase(Context context){
    if (INSTANCE == null){
      INSTANCE = Room.databaseBuilder(context.getApplicationContext(), PlaceDatabase.class,
          "places_db").build();
    }
    return INSTANCE;
  }

  public abstract DatabaseInterface PlacedatabaseInterface();

【问题讨论】:

    标签: android android-room android-livedata


    【解决方案1】:

    创建类 AddBorrowViewModel

    public class AddBorrowViewModel extends AndroidViewModel
    {
         private PlaceDatabase appDatabase;
        public AddBorrowViewModel(@NonNull Application application) {
            super(application);
            appDatabase = PlaceDatabase.getDatabase(this.getApplication());
        }
    
        public void addBorrow(PlaceSaved placedSaved)
        {
            new addAsyncTask(appDatabase).execute(placedSaved);
    
        }
    
        private class addAsyncTask  extends AsyncTask<PlaceSaved , Void, Void>
        {
            private PlaceDatabase appDatabase_;
            addAsyncTask(PlaceDatabase appDatabase)
            {
                appDatabase_ = appDatabase;
            }
    
            @Override
            protected Void doInBackground(PlaceSaved... placedSaved) {
                appDatabase_.itemAndPersonModel().addBorrow(placedSaved[0]);
                return null;
            }
        }
    }
    

    在您的 PlacesActivity 中添加此变量

    私有 AddBorrowViewModel addBorrowViewModel;

    在 OnCreate 中添加此

    addBorrowViewModel = ViewModelProviders.of(this).get(AddBorrowViewModel.class);
    

    在onClickListener的alertDilaog之后的snackbar

    addBorrowViewModel.addBorrow(new PlaceSaved(
                                todo.getText().toString(),
                        time.getText().toString(), longi.getText().toString()
                        ));
    

    在您的 PlaceDatabase 中添加

    public abstract Dao itemAndPersonModel();
    

    【讨论】:

    • 您好,感谢您的回复,但这给出了错误:java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.myapp.AddBorrowViewModel.addBorrow(com.example.myapp. PlaceSaved)' 在 com.example.myapp.PlacesActivity$3$1.onClick(PlacesActivity.java:99) 处的空对象引用上
    • 另外,在我的帖子中,我忘了添加数据库。我已经更新了主要问题。
    • 在你的数据库类中添加这个 public abstract Dao itemAndPersonModel();
    • 嗨,很抱歉听起来很傻,但在我的原始应用程序中,没有 itemAndPersonModel。你能检查一下并告诉我我应该添加什么吗?
    • 兄弟它的抽象方法。你只声明它数据库其余的工作是你在哪里为它写定义
    猜你喜欢
    • 2018-03-18
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2018-01-22
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多