简体   繁体   English

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

[英]How do i get my id out through my repository?

I have a room database running in the background on a AsyncTask that when called it inserts the certain class that I have as a entity.我有一个房间数据库在AsyncTask的后台运行,当它被调用时,它会插入我作为实体的某个类。 The request in my CustomerDao can return a long as an id.我的CustomerDao的请求可以返回一个 long 作为 id。

The thing is though that I'm using a repository to save my class into the room database and for that I need a AsyncTask and some void to be able to reach my insert function.问题是我正在使用存储库将我的课程保存到房间数据库中,为此我需要一个 AsyncTask 和一些 void 才能达到我的插入功能。

My question now though is how do I get this long out to my MainViewController via the repository and the AsyncTask ?我现在的问题是如何通过存储库和AsyncTask将这么长的时间发送到我的MainViewController I am not able to request a long from a new InsertAsync task?我无法从新的 InsertAsync 任务中请求 long 吗? so how do I then return my id all the way to the MainActivity ?那么我如何将我的 id 一直返回到MainActivity

Tell me what code you need I'm happy to help though right now I will send you my Main and my Repository.告诉我您需要什么代码,我很乐意为您提供帮助,但现在我会将我的 Main 和我的存储库发送给您。

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();
        }
    }
}

Repository:存储库:

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;
        }
    }
}

First of all use a single ASyncTask to handle both delete and insert (and probably more in future) is wrong.首先,使用单个ASyncTask来处理删除和插入(将来可能还会更多)是错误的。 You should know that AsyncTask is just a worker and since you using Repository pattern it should not contain any logic.您应该知道AsyncTask只是一个工作者,并且由于您使用Repository模式,它不应该包含任何逻辑。 You should create a task that return long:您应该创建一个返回 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]);;
        }
    }

Second of all since you use repository pattern you can just format the response needed inside the repository itself:其次,由于您使用存储库模式,您只需格式化存储库本身所需的响应:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 Class 中的值放入我的 TextViewField - How do I get the Value out of my Class into my TextViewField 如何从我的testng报告中获取控制台输出? - How do I get the console output out of my testng report? 如何让我的程序从 do while 循环中打印出我的所有输入? - How do I get my program to print out all of my input from a do while loop? 如何搜索我的JList? - How do I search through my JList? 如何使用带有 Retrofit 的 MVVM 将存储库实施到我的项目中 - How do I implement the repository to my project using MVVM with Retrofit 如何使我的“ Date”对象在每次调用时都打印出不同的值? - How do I get my “Date” object to print out different values each time I call it? 我如何获得我的程序来更新其涵盖100%的产品销售量的百分比 - How do i get my program to update the % of how much the product sales it covers out off 100% 如何获取我的代码以打印出更改? 我使用了模数,但只打印了剩余的数 - How do i get my code to print out the change? I used modulus yet it's only printing out the remainder 我如何让我的 System.out.prints 相互对齐? - How do i get my System.out.prints to line up under each other? 如何从Java文件中获取值并进行计算? - How do I get values out of my file in Java and calculate them?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM