Room database + recyclerview, how to pass data to another activity and then retrieve information from database based on passed data

余生颓废 提交于 2020-07-22 10:53:06

问题


I'm trying to get Company id (&& Company name) in first activity, pass it into the second activity and there I'd like to retrieve all data from database based on that id (&& name), but the app crashes, below is the code. can someone provide me a working code snippet. Any kind of help will be appreciated.

AdapterCompany

public class AdapterCompany extends RecyclerView.Adapter<AdapterCompany.AdapterCompanyHolder> {
    private List<EntityCompany> entityCompanies = new ArrayList<>();

    private CompanyClickListener listener;

    public AdapterCompany(CompanyClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public AdapterCompanyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.company_list, parent, false);
        return new AdapterCompanyHolder(itemView, listener);
    }

    @Override
    public void onBindViewHolder(@NonNull AdapterCompanyHolder holder, int position) {
        EntityCompany currentEntityCompany = entityCompanies.get(position);
        holder.textViewCompany.setText(currentEntityCompany.getCompany());
        holder.textViewCompanyName.setText(currentEntityCompany.getCompany_name());
        holder.textViewCompanyDescription.setText(currentEntityCompany.getCompany_short_description());
        holder.imageViewCompanySrc.setImageURI(Uri.parse("android.resource://com.example.handyman/drawable/" + currentEntityCompany.getCompany_image_src()));
    }

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

    public void setEntityCompanies(List<EntityCompany> entityCompanies) {
        this.entityCompanies = entityCompanies;
        notifyDataSetChanged();
    }

    public static class AdapterCompanyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private CompanyClickListener listener;

        private TextView textViewCompany, textViewCompanyName, textViewCompanyDescription;
        private ImageView imageViewCompanySrc;

        public AdapterCompanyHolder(@NonNull View itemView, CompanyClickListener listener) {
            super(itemView);

            this.listener = listener;

            itemView.setOnClickListener(this);

            textViewCompany = itemView.findViewById(R.id.textViewCompany);
            textViewCompanyName = itemView.findViewById(R.id.textViewCompanyName);
            textViewCompanyDescription = itemView.findViewById(R.id.textViewCompanyDescription);
            imageViewCompanySrc = itemView.findViewById(R.id.imageViewCompanySrc);

        }

        @Override
        public void onClick(View view) {
            if (listener != null) {
                listener.onCompanyClick(getAdapterPosition());
            }
        }
    }

    interface CompanyClickListener {
        void onCompanyClick(int position);
    }
}

RepositoryCompany

public class RepositoryCompany {
    private DaoCompany daoCompany;
    private LiveData<List<EntityCompany>> allEntityCompany;

    public RepositoryCompany(Application application) {
        DatabaseHandyman databaseHandyman = DatabaseHandyman.getInstance(application);
        daoCompany = databaseHandyman.daoCompany();
        allEntityCompany = daoCompany.getAllEntityCompany();
    }

    public void insert(EntityCompany entityCompany) {
        new InsertEntityCompanyAsyncTask(daoCompany).execute(entityCompany);
    }

    public void update(EntityCompany entityCompany) {
        new UpdateEntityCompanyAsyncTask(daoCompany).execute(entityCompany);
    }

    public void delete(EntityCompany entityCompany) {
        new DeleteEntityCompanyAsyncTask(daoCompany).execute(entityCompany);
    }

    public LiveData<List<EntityCompany>> getAllEntityCompany() {
        return allEntityCompany;
    }

    private static class InsertEntityCompanyAsyncTask extends AsyncTask<EntityCompany, Void, Void> {
        private DaoCompany daoCompany;

        private InsertEntityCompanyAsyncTask(DaoCompany daoCompany) {
            this.daoCompany = daoCompany;
        }

        @Override
        protected Void doInBackground(EntityCompany... entityCompanies) {
            daoCompany.insert(entityCompanies[0]);
            return null;
        }
    }

    private static class UpdateEntityCompanyAsyncTask extends AsyncTask<EntityCompany, Void, Void> {
        private DaoCompany daoCompany;

        private UpdateEntityCompanyAsyncTask(DaoCompany daoCompany) {
            this.daoCompany = daoCompany;
        }

        @Override
        protected Void doInBackground(EntityCompany... entityCompanies) {
            daoCompany.update(entityCompanies[0]);
            return null;
        }
    }

    private static class DeleteEntityCompanyAsyncTask extends AsyncTask<EntityCompany, Void, Void> {
        private DaoCompany daoCompany;

        private DeleteEntityCompanyAsyncTask(DaoCompany daoCompany) {
            this.daoCompany = daoCompany;
        }

        @Override
        protected Void doInBackground(EntityCompany... entityCompanies) {
            daoCompany.delete(entityCompanies[0]);
            return null;
        }
    }
}

ViewModelCompany

public class ViewModelCompany extends AndroidViewModel {
    private RepositoryCompany repositoryCompany;
    private LiveData<List<EntityCompany>> allEntityCompany;

    public ViewModelCompany(@NonNull Application application) {
        super(application);
        repositoryCompany = new RepositoryCompany(application);
        allEntityCompany = repositoryCompany.getAllEntityCompany();
    }

    public void insert(EntityCompany entityCompany) {
        repositoryCompany.insert(entityCompany);
    }

    public void update(EntityCompany entityCompany) {
        repositoryCompany.update(entityCompany);
    }

    public void delete(EntityCompany entityCompany) {
        repositoryCompany.delete(entityCompany);
    }

    public LiveData<List<EntityCompany>> getAllEntityCompany() {
        return allEntityCompany;
    }
}

MainActivity

public class MainActivity extends AppCompatActivity implements AdapterCompany.CompanyClickListener {

    private List<EntityCompany> entityCompanies = new ArrayList<>();

    private ViewModelCompany viewModelCompany;

    @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_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        final AdapterCompany adapter = new AdapterCompany(this);
        recyclerView.setAdapter(adapter);

        viewModelCompany = new ViewModelProvider(this).get(ViewModelCompany.class);
        viewModelCompany.getAllEntityCompany().observe(this, new Observer<List<EntityCompany>>() {
            @Override
            public void onChanged(List<EntityCompany> entityCompanies) {
                adapter.setEntityCompanies(entityCompanies);
            }

        });
    }


    @Override
    public void onCompanyClick(int position) {

        EntityCompany entityCompany = entityCompanies.get(position);
        CompanyInformation.open(this, entityCompany.getId());

//        Intent intent = new Intent(this, CompanyInformation.class);
//        startActivity(intent);

    }
}

CompanyInformation

public class CompanyInformation extends AppCompatActivity {

    public static void open(MainActivity mainActivity, long entityCompanyId) {
        Intent intent = new Intent(mainActivity, CompanyInformation.class);
        intent.putExtra("CompanyId", entityCompanyId);
        mainActivity.startActivity(intent);
    }

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

        Intent intent = getIntent();
        if (intent !=null && intent.hasExtra("CompanyId")) {
            long entityCompanyId = intent.getLongExtra("CompanyId", -1 );
            Toast.makeText(this, "Company Id is " + entityCompanyId, Toast.LENGTH_SHORT).show();
        }
    }
}

Error

2020-06-27 11:01:34.937 12524-12524/com.example.handyman E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.handyman, PID: 12524
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at com.example.handyman.MainActivity.onCompanyClick(MainActivity.java:52)
    at com.example.handyman.AdapterCompany$AdapterCompanyHolder.onClick(AdapterCompany.java:76)
    at android.view.View.performClick(View.java:6294)
    at android.view.View$PerformClick.run(View.java:24770)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

来源:https://stackoverflow.com/questions/62607969/room-database-recyclerview-how-to-pass-data-to-another-activity-and-then-retr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!