У моего приложения есть RawMaterialFragment, которая отображает данные сырья в RecyClerview из базы данных комнаты.

Я пытаюсь создать подробное действие (MetrialItemView), чтобы отобразить подробную информацию об отдельном сырье, щелкнув или выбрав сырье из recyclerView.

Моя проблема заключается в том, как отправлять данные из адаптера и как получать данные в метриалитной активности и отобразить ее.

MaterialListAdapter:

public class MaterialListAdapter extends RecyclerView.Adapter<MaterialListAdapter.ViewHolder> {


    private final LayoutInflater mInflater;
    private FragmentRawMaterials mContext;
    private List<RawMaterialsEntity> mMaterial; // Cached copy of Materials
    RawMaterialsEntity mCurrent;


    public MaterialListAdapter(FragmentRawMaterials context) {
        mInflater = LayoutInflater.from(context.getActivity());
        mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.list_item, parent, false);
        return new ViewHolder(itemView);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView materialName;
        private final TextView materialBrand;
        private final TextView materialQuantity;
        LinearLayout parentLayout;


        private ViewHolder(View itemView) {
            super(itemView);
            materialName = itemView.findViewById(R.id.raw_material_name);
            materialBrand = itemView.findViewById(R.id.raw_material_brand);
            materialQuantity = itemView.findViewById(R.id.raw_material_quantity);

            parentLayout = itemView.findViewById(R.id.parent_layout);
        }
    }



    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (mMaterial != null) {
            mCurrent = mMaterial.get(position);
            holder.materialName.setText(mCurrent.getRawMaterialName());
            holder.materialBrand.setText(mCurrent.getRawMaterialBrand());
            holder.materialQuantity.setText(String.valueOf(mCurrent.getRawMaterialQuantity()));

        } else {
            // Covers the case of data not being ready yet.
            holder.materialName.setText("Name NA");
            holder.materialBrand.setText("Brand NA");
            holder.materialQuantity.setText("Quantity NA");
        }



       holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
                mContext.startActivity(intent);
            }
        });



    }


    public void setMaterial(List<RawMaterialsEntity> materials){
        mMaterial = materials;
        notifyDataSetChanged();
    }

    // getItemCount() is called many times, and when it is first called,
    // mWords has not been updated (means initially, it's null, and we can't return null).
    @Override
    public int getItemCount() {
        if (mMaterial != null)
            return mMaterial.size();
        else return 0;
    }
}

MaterialiteMView:

public class MaterialItemView extends AppCompatActivity {


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

}
}

Material_list_item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Raw Material Name:"
            style="@style/OtherTextViews"/>
        <TextView
            android:id="@+id/material_name_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Raw Material Brand:"
            style="@style/OtherTextViews"/>
        <TextView
            android:id="@+id/material_brand_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Unit Weight:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2000"
            style="@style/OtherTextViewsBody"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="gm"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Unit Cost:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="50"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cost per gm/ml:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0.1"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Available Quantity:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1000"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Total Cost:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="50000"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Supplier Name:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Pandah"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Supplier Email:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Pandah@panadh.com"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Supplier Phone:"
            style="@style/OtherTextViews"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+966555699517"
            style="@style/OtherTextViewsBody"/>

    </LinearLayout>

</LinearLayout>

Fragmentrawmaterials:

public class FragmentRawMaterials extends Fragment{

    private RawMaterialViewModel mMaterialViewModel;
    private static final int NEW_MATERIAL_ACTIVITY_REQUEST_CODE = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_raw_materials, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // Setup any handles to view objects here
        //FloatingActionButton fab to insert recipes
        TextView emptyViewText = view.findViewById(R.id.empty_raw__materials_view);
        FloatingActionButton fab = view.findViewById(R.id.fab_raw_materials);
        fab.setOnClickListener(view1 -> {
            Intent intent = new Intent(getActivity(), RawMaterialsEditor.class);
            startActivityForResult(intent, NEW_MATERIAL_ACTIVITY_REQUEST_CODE);
        });

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        //Decoration to add a line divider between recyclerView items
        DividerItemDecoration decoration =
                new DividerItemDecoration(Objects.requireNonNull(this.getActivity()),
                        R.drawable.border_line);
        recyclerView.addItemDecoration(decoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        final MaterialListAdapter adapter = new MaterialListAdapter(this);
        recyclerView.setAdapter(adapter);


        // Check if adapter list is empty, if so empty text view will appear.
        adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                if (adapter.getItemCount() == 0) {
                    recyclerView.setVisibility(View.GONE);
                    emptyViewText.setVisibility(View.VISIBLE);
                }
                else {
                    recyclerView.setVisibility(View.VISIBLE);
                    emptyViewText.setVisibility(View.GONE);
                }
            }
        });

        mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
        // Update the cached copy of the words in the adapter.
        mMaterialViewModel.getAllMaterials().observe(this, adapter::setMaterial);

    }



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

        if (requestCode == NEW_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            RawMaterialsEntity material = new RawMaterialsEntity(data
                    .getStringExtra(RawMaterialsEditor.EXTRA_REPLY_NAME),
                    data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_BRAND),
                    Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_WEIGHT)),
                    Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_COST)),
                    Integer.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_QUANTITY)),
                    data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_NAME),
                    data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_EMAIL),
                    data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_PHONE),
                    data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_UOM));
            mMaterialViewModel.insertMaterial(material);
            mMaterialViewModel.costPerGm();
            mMaterialViewModel.totalCost();
        } else {
            Toast.makeText(
                    Objects.requireNonNull(getActivity()).getApplicationContext(),
                    R.string.editor_insert_rm_failed,
                    Toast.LENGTH_LONG).show();
        }
    }

}
0
Khaled Almanea 6 Окт 2019 в 13:04

1 ответ

Лучший ответ

Каждый ряд данных datamodel () должен иметь идентификатор, а затем использовать putextra () whan, это случается

 holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
                intent.putExtra("ID",mCurrent.getID());
                mContext.startActivity(intent);
            }
        });

И подробно используйте getIntent () Activity

int id =getIntent().getIntExtra("ID",-1);

А затем получить данные строки подробностей с базой данных (ViewModel) по идентификатору и анализу его

0
Alireza aslami 7 Окт 2019 в 08:42