如何使用room persistance library和livedata更新数据库

时间:2018-03-20 06:01:42

标签: android android-room android-livedata

我正在尝试使用会议室持久性库 Livedata 更新我的数据库。我是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;
    }

  }
}

现在,我正在尝试使用OnClick的{​​{1}}将项目添加到数据库中:

fab

因为我是java的新手,所以我无法找到如何将数据添加到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); } }); 内的数据库。

如果有人帮忙,我将不胜感激。

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

fab1.setOnClickListner

1 个答案:

答案 0 :(得分:0)

创建类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中添加此变量

private AddBorrowViewModel addBorrowViewModel;

OnCreate中的

添加此

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

快餐栏后的alertDilaog

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

在您的PlaceDatabase中添加

public abstract Dao itemAndPersonModel();