如何通过我的存储库获取我的id?

时间:2018-03-16 08:38:44

标签: java android repository android-room

我有一个在AsyncTask后台运行的房间数据库,当它被调用时会插入我作为实体的某个类。我CustomerDao中的请求可以返回一个id作为id。

事情是,我正在使用存储库将我的类保存到房间数据库中,为此我需要一个AsyncTask和一些无法访问我的插入功能。

我现在的问题是如何通过存储库和MainViewController将这个问题延长到我的AsyncTask?我无法从新的InsertAsync任务请求长时间?那么如何将我的ID一直返回MainActivity

告诉我你需要什么代码我很乐意提供帮助,但我现在会将你的主存储库和存储库发送给你。

MainActivity:

package com.example.jenso.paperseller;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    FloatingActionButton fab;
    private CustomerViewModel mCustomerViewModel;
    public static final int NEW_CUSTOMER_ACTIVITY_REQUEST_CODE = 1;
    private static final  String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        RecyclerView recyclerView = findViewById(R.id.recycler);

        final PapperRecyclerAdapter adapter = new PapperRecyclerAdapter(this);

        fab = findViewById(R.id.fab);

        mCustomerViewModel = ViewModelProviders.of(this).get(CustomerViewModel.class);

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT ) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            }
        }).attachToRecyclerView(recyclerView);

        mCustomerViewModel.getmAllCustomers().observe(this, new Observer<List<Customer>>() {
            @Override
            public void onChanged(@Nullable List<Customer> customers) {
                adapter.setCustomer(customers);
            }
        });

        recyclerView.setAdapter(adapter);
        fab.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CreateCustomer.class);
                startActivityForResult(intent, NEW_CUSTOMER_ACTIVITY_REQUEST_CODE);
            }
        });
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    public void onActivityResult(final int requestCode, final int resultCode, final Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == NEW_CUSTOMER_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            String[] mCustomerSave = data.getStringArrayExtra(CreateCustomer.EXTRA_REPLY);
            Customer customer = new Customer(mCustomerSave[0],mCustomerSave[1],mCustomerSave[2],mCustomerSave[3]);
            Long id  = mCustomerViewModel.insert(customer);
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    R.string.empty_not_saved,
                    Toast.LENGTH_LONG).show();
        }
    }
}

存储库:

package com.example.jenso.paperseller;

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.os.AsyncTask;

import java.util.List;

public class CustomerRepository {
    private CustomerDao mCustomerDao;
    private LiveData<List<Customer>> mAllCustomers;

    public CustomerRepository(Application application) {
            CustomerDatabase db = CustomerDatabase.getDatabase(application);

            mAllCustomers = mCustomerDao.getAllCustomers();
            mCustomerDao = db.customerDao();
    }

    LiveData<List<Customer>> getAllCustomers(){
        return mAllCustomers;
    }
    //public void deleteOneCustomer(int id){new insertAsyncTask(mCustomerDao).}

    public void insert (Customer customer){
        new insertAsyncTask(mCustomerDao).execute(customer);
    }

    public void delete(Customer customer) {
        new insertAsyncTask(mCustomerDao).execute(customer);
    }

    private static class insertAsyncTask extends AsyncTask<Customer, Void, Void> {
        private CustomerDao mAsyncTaskDao;

        insertAsyncTask(CustomerDao dao) {
            mAsyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(final Customer... params) {
            mAsyncTaskDao.insertAll(params[0]);

            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

首先使用单个ASyncTask来处理删除和插入(以及将来可能更多)是错误的。您应该知道AsyncTask只是一个工作者,因为您使用Repository模式,它不应该包含任何逻辑。您应该创建一个返回long的任务:

 private static class DeleteTask extends AsyncTask<Customer, Void, Long> {
        private CustomerDao dao;

        DeleteTask (CustomerDao dao) {
            this.dao = dao;
        }

        @Override
        protected Long doInBackground(final Customer... params) {
            return dao.delete(params[0]);;
        }
    }

其次,因为您使用存储库模式,您只需格式化存储库本身所需的响应:

public long delete(Customer customer) {
        new insertAsyncTask(mCustomerDao).execute(customer);
        return customer.id; //Return Primary key
    }