How to pass data from a activity to a recycler view adapter in android

牧云@^-^@ 提交于 2020-08-10 21:16:11

问题


I'm trying to design a page where address are stored in recycler view -> cardview.

When the user clicks the add address button from the Activity A the user is navigated to the add address page in Activity B. Here the user can input customer name, address line 1 and address line two.

And once save button is clicked in Activity B, a cardview should be created under the add address button in the Activity A.

This design is just like the amazon mobile app add address option.

Could anyone give me an example hoe to pass the saved data from activity to recycler adapter. I know how to pass data from recycler adapter to activity with putExtra etc..

Kindly help me. Million Thanks in advance!

Code In Activity A(Where the Add address button is available and where the recycler view is present)

public class ProfileManageAdressFragment extends AppCompatActivity {

    RecyclerView recyclerView;
    ProfileManageAddressRecyclerAdapter adapter;
    ArrayList<ProfileManageAddressGetterSetter> reviews;


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

        Button addAddress = findViewById(R.id.addNewAddress);
        reviews = new ArrayList<>();
        addAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ProfileManageAdressFragment.this, AddNewAddress.class);
                startActivity(intent);
                
            }
        });
    }
}

Piece of Code that is responsible for adding a card view in Activity A. Kindly let me know how to invoke this below code on button click in Activity

reviews.add(new ProfileManageAddressGetterSetter("Customer Name", "address line 1", "address line 2"));
                recyclerView = findViewById(R.id.addressRecyclerView);
                recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(ProfileManageAdressFragment.this));
                adapter = new ProfileManageAddressRecyclerAdapter(this, reviews);
                recyclerView.setAdapter(adapter);

Code in the Recycler adapter

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

    private ArrayList<ProfileManageAddressGetterSetter> mDataset = new ArrayList<>();
    private Context context;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private TextView customer_name, address_one, address_two;
        private Button edit, remove;

        public ViewHolder(View v) {
            super(v);
            customer_name = (TextView) v.findViewById(R.id.customerName);
            address_one = (TextView) v.findViewById(R.id.addressLineOne);
            address_two = v.findViewById(R.id.addressLineTwo);
            
        }
    }

    public ProfileManageAddressRecyclerAdapter(View.OnClickListener profileManageAdressFragment, ArrayList<ProfileManageAddressGetterSetter> dataset) {
        mDataset.clear();
        mDataset.addAll(dataset);
    }

    @Override
    public ProfileManageAddressRecyclerAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_manage_address, parent, false);
        ProfileManageAddressRecyclerAdapter.ViewHolder vh = new ProfileManageAddressRecyclerAdapter.ViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull ProfileManageAddressRecyclerAdapter.ViewHolder holder, int position) {
        ProfileManageAddressGetterSetter profileManageAddressGetterSetter = mDataset.get(position);
        holder.address_one.setText(profileManageAddressGetterSetter.getAddress_line_1());
        holder.address_two.setText(profileManageAddressGetterSetter.getGetAddress_line_2());
        holder.customer_name.setText(profileManageAddressGetterSetter.getContractor_name());
    }


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

}

enter image description here - After trying the call from adapter using intent as mentioned above ended up with a 0.

Code in the Activity B

public class AddNewAddress extends AppCompatActivity {

    private EditText customer_name, address_one, address_two;
    private TextView cancel;
    private Button add_address;

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

        customer_name = findViewById(R.id.customerName);
        address_one = findViewById(R.id.addressOne);
        address_two = findViewById(R.id.addressTwo);
        add_address = findViewById(R.id.addAddress);
        cancel = findViewById(R.id.completeCancel);

        String cancel_text = "Cancel";

        SpannableString spanableObject = new SpannableString(cancel_text);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Toast.makeText(AddNewAddress.this, "Clicked", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.BLUE);
            }
        };

        spanableObject.setSpan(clickableSpan, 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        cancel.setText(spanableObject);

        cancel.setMovementMethod(LinkMovementMethod.getInstance());

        final ProfileManageAdressFragment profileManageAdressFragment = new ProfileManageAdressFragment();
        add_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddNewAddress.this, ProfileManageAdressFragment.class);
                startActivity(intent);
            }
        });
    }

    private void setFragment(android.support.v4.app.Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.main_frame, fragment).commit();
    }
}

Update 1:

Kindly check my updated Recycler adapter. When I run this 0 is displayed in the text area as shown in the attached image. I'm new to android. Kindly help with example.


回答1:


I finally achieved my goal with the use of ActivityResult. Now I'm able to pass data from Activity to Cardview.

Solution: When button is clicked in Activity A, I start the activity with startResultActivity(). Later, when the Activity B i triggered. The end-user inputs the data and that data is passed with the use of putExtra() and once the save button is clicked in Activity B next setResult() in Activity B and finish().

Finally i define onActivityResult() in Activity A to get the result. Works well!!




回答2:


I would create a global variable and then store all the data in that variable and simply just call that variable in adapter.

declare a global variable and assign null value to it:

public static String checking = null;

a then store data in when you need it:

checking = check.getText().toString();

then call it in your adapter class.




回答3:


first make interface listener inside listener make function with parameter like this

interface YourRecycleViewClickListener {
    fun onItemClickListener(param1:View, param2: String)
}

now extend your activity

class YourActivity:YourRecycleViewClickListener{
    override fun onItemClickListener(param1:View, param2: String) {
        //do any thing
    }
}

third step make interface constract in your recycle adapter

class YourAdapter(
    private val listener: YourRecycleViewClickListener){

    holder.constraintLayout.setOnClickListener{
      listener.onItemClickListener(param1,param2)
    }

}

this is by kotlin lang and by java is same but change syntax

that all to do



来源:https://stackoverflow.com/questions/62684880/how-to-pass-data-from-a-activity-to-a-recycler-view-adapter-in-android

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