How can i get the all value of Recyclerview on Button click? - android

public class MainActivity extends Activity implements
GetDataContract.View,RecyclerItemClickListener {
private Presenter mPresenter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
CountryAdapter countryAdapter;
EditText etEnterName;
Button btAddItem;
List<CountryRes> allCountriesEditValue;
List<CountryRes> allCountriesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getView();
}
private void getView() {
/*presentator */
mPresenter = new Presenter(this);
/*initiliaze of id*/
recyclerView = (RecyclerView) findViewById(R.id.recycler);
etEnterName = (EditText) findViewById(R.id.etEnterName);
btAddItem = (Button) findViewById(R.id.btAddItem);
linearLayoutManager = new LinearLayoutManager(this);
/*initiliaze the arraylist*/
allCountriesData=new ArrayList<>();
recyclerView.setLayoutManager(linearLayoutManager);
btAddItem.setOnClickListener(new AddButtonClick());
}
#Override
public void onGetDataFailure(String message) {
Log.d("Status", message);
}
#Override
public void onGetDataSuccess(String message, List<CountryRes>
allCountriesData) {
/*add the value mannulay*/
CountryRes countryRes = new CountryRes();
countryRes.setName(etEnterName.getText().toString());
allCountriesData.add(countryRes);
countryAdapter = new CountryAdapter(getApplicationContext(),
allCountriesData, (RecyclerItemClickListener) this);
recyclerView.setAdapter(countryAdapter);
/*set the data in the room*/
AppDataBase database = AppDataBase.getAppDatabase(this);
DataGenerator.with(database).generateCats(allCountriesData);
Logger.displayCatsInLog(database.catDao().loadAll());
countryAdapter.notifyDataSetChanged();
}
/*on item click*/
#Override
public void onDashBoardItemClick(String pos) {
Bundle bundle = new Bundle();
bundle.putString("TABVALUE", pos);
Intent intent = new Intent(getApplicationContext(),
DynamicTabsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
private class AddButtonClick implements View.OnClickListener {
#Override
public void onClick(View view) {
mPresenter.getDataFromURL(getApplicationContext(), "");
}
}
}
class adapter
public class CountryAdapter extends
RecyclerView.Adapter<CountryAdapter.MyViewHolder> {
private Context context;
private List<CountryRes> list = new ArrayList<>();
private List<CountryRes> list_edit = new ArrayList<>();
private RecyclerItemClickListener onRecyclerItemClickListener;
public CountryAdapter(Context context, List<CountryRes> list,
RecyclerItemClickListener onRecyclerItemClickListener) {
this.context = context;
this.list = list;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
#Override
public CountryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView;
layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent,
false);
return new FooterViewHolder(layoutView,
onRecyclerItemClickListener);
}
#Override
public void onBindViewHolder(CountryAdapter.MyViewHolder holder, int
position) {
holder.tvCountryName.setText(list.get(position).getName());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName;
LinearLayout llListItem;
public MyViewHolder(View itemView) {
super(itemView);
tvCountryName = (TextView)
itemView.findViewById(R.id.tv_country_name);
llListItem = (LinearLayout)
itemView.findViewById(R.id.llListItem);
}
}
private class FooterViewHolder extends MyViewHolder {
public FooterViewHolder(View layoutView, final
RecyclerItemClickListener onRecyclerItemClickListener) {
super(layoutView);
llListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onRecyclerItemClickListener != null) {
onRecyclerItemClickListener.onDashBoardItemClick(tvCountryName.getText().toS
tring());
}
}
});
}
}
}
Interface
public interface RecyclerItemClickListener {
void onDashBoardItemClick(String pos);
}

Case 1: Inside ViewHolder if you need to understand exactly position of clicked item you could call getAdapterPosition().
Case 2: You just need to receive all items of adapter. It is simple, make getter method which will return the items.
Case 3: Send info to activity, first make some specific event listener of your view inside ViewHolder, then event triggers (user clicks or other) and you call your interface method which you passed inside adapter, that was implemented in activity.
Tell me if you need an example, i will do it.

Try this one,
Button button= (Button) findViewById(R.id.your_button_id);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
//create new ArrayList.
//ArrayList<CountryRes> showList=new ArrayList<>;
//now, put all stored data of a list in this arraylist.
showList.addAll(allCountriesData);
}
});

Related

How to place onClickListeners for views inside the items of recyclerview?

I am working with recyclerview and sqlite database. i want to place a button in cardview such that whenever user clicks on that button, the respective record should be deleted from the table.
This is my adapter class for recyclerview
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private Context mContext;
private Cursor mCursor;
private butttonsAdapetrListener mlistener;
private RecyclerView.ViewHolder v;
public CardAdapter(Context context, Cursor cursor ,butttonsAdapetrListener listener){
mContext=context;
mCursor=cursor;
mlistener=listener;
}
#NonNull
#Override
public CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.mycard,parent,false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CardViewHolder holder, int position) {
if(!mCursor.moveToPosition(position)){
return;
}
String name = mCursor.getString(mCursor.getColumnIndex("NAME"));
int total = mCursor.getInt(mCursor.getColumnIndex("TOTAL"));
int bunked = mCursor.getInt(mCursor.getColumnIndex("BUNK"));
int color = mCursor.getInt(mCursor.getColumnIndex("COLOR"));
long id= mCursor.getLong(mCursor.getColumnIndex("_id"));
holder.nameText.setText(name);
holder.totalText.setText(Integer.toString(total));
holder.bunkedText.setText(Integer.toString(bunked));
holder.colorText.setBackgroundColor(color);
holder.itemView.setTag(id);
v=holder;
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public class CardViewHolder extends RecyclerView.ViewHolder{
public TextView nameText;
public TextView totalText;
public TextView bunkedText;
public TextView colorText;
public Button delete;
public CardViewHolder(#NonNull View itemView) {
super(itemView);
nameText= itemView.findViewById(R.id.name);
totalText = itemView.findViewById(R.id.total_num);
bunkedText = itemView.findViewById(R.id.bunked_num);
colorText= itemView.findViewById(R.id.color);
delete= itemView.findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mlistener.deleteOnClick(v,getAdapterPosition());
}
});
}
}
public interface butttonsAdapetrListener{
void deleteOnClick(RecyclerView.ViewHolder v,long position);
}
public void swapCursor(Cursor newCursor){
if(mCursor!=null){
mCursor.close();
}
mCursor=newCursor;
if(newCursor!=null){
notifyDataSetChanged();
}
}
}
This is my main activity code to delete record from database
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase db;
private CardAdapter mAdapter;
private long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteOpenHelper proBunkerDatabaseHelper = new ProBunkerDatabaseHelper(this);
db = proBunkerDatabaseHelper.getWritableDatabase();
RecyclerView recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new CardAdapter(this, getCursor(), new CardAdapter.butttonsAdapetrListener() {
#Override
public void deleteOnClick(RecyclerView.ViewHolder v, long position) {
id = (long)v.itemView.getTag();
db.delete("MYTABLE","_id="+id,null);
mAdapter.swapCursor(getCursor());
}
});
recyclerView.setAdapter(mAdapter);
FloatingActionButton b = findViewById(R.id.fab);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,AddSubject.class);
startActivity(intent);
}
});
}
public Cursor getCursor(){
return db.query("MYTABLE",null,null,null,null,null,"_id ASC");
}
}
The main problem is the when I click on the delete button in any item it is deleting the item which is last in the cursor.
there are no compilation errors and runtime issues only the records are not deleting in correct order.
Try it like this:
Your interface:
public interface butttonsAdapetrListener{
void deleteOnClick(int id,long adapterPos);
}
Inside your CardViewHolder:
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = (int)view.getTag();
mlistener.deleteOnClick(id,getAdapterPosition());
}
});
In onBindViewHolder
holder.delete.setTag(id);
In MainActivity onCreate
mAdapter = new CardAdapter(this, getCursor(), new CardAdapter.butttonsAdapetrListener() {
#Override
public void deleteOnClick(int id, long position) {
db.delete("MYTABLE","_id="+id,null);
mAdapter.swapCursor(getCursor());
}
});
Another alternative
If you want your activity to be clean and not handle data from within.
Keep it for the adapter to handle the data being deleted and notifying any change.
Just create a listener for the button in the onbindviewholder method.

How do I detect if a button from an activity is clicked while inside a RecyclerView adapter

I have this method in my activity (CreatePhotostoryActivity):
#Override
public void showEditField(Moment oldMoment, final int index){
listRecycler.setVisibility(View.GONE);
editCaption.setVisibility(View.VISIBLE);
saveCancelNavbar.setVisibility(View.VISIBLE);
momentView.setVisibility(View.GONE);
photoStoryNavbar.setVisibility(View.GONE);
header.setVisibility(View.GONE);
Picasso.with(getApplicationContext()).load(oldMoment.photoUri).into(displayPhoto);
imageCaption.setText("");
imageCaption.setText(oldMoment.caption);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
}
});
saveText.setText("Save Moment");
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMoment(imageCaption.getText().toString(), index);
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", true);
startActivity(i);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", false);
startActivity(i);
}
});
}
In my RecyclerView adapter, showEditField is called using an interface, and it does work except that I am unable to detect whether saveButton or cancelButton was clicked. This is how it's called in the onBindViewHolder method of my RecyclerView adapter (RVAdapter):
((RecyclerView.ViewHolder) momentViewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapterCallback.showEditField(moments.get(position), position);
Intent intent = ((CreatePhotostoryActivity) mContext).getIntent();
Boolean isSaved = intent.getExtras().getBoolean("isSaved");
if (isSaved) {
holder.momentCaption.setText(moments.get(position).caption);
holder.momentPlaceholder.setVisibility(View.GONE);
holder.momentCaption.setVisibility(View.VISIBLE);
} else {
holder.momentPlaceholder.setVisibility(View.VISIBLE);
holder.momentCaption.setVisibility(View.GONE);
}
notifyDataSetChanged();
});
Do note my attempt of using an intent to find out which button was clicked. It doesn't work. momentCaption remains gone and momentPlaceHolder remains visible even though saveButton was clicked. The app also crashes afterwards.
Edit: I think calling this mAdapterCallback.showEditField(moments.get(position), position); before setting the values of momentCaption and momentPlaceholder is problematic, since showEditField calls other methods (e.g. closeEditMoment() before the intent is retrieved from the adapter.
Create an interface with two methods like saveBtnClick() and cancelBtnClick().
Implement the interface in your Activity.
Implement Click listener for both the buttons in the ViewHolder of your RecyclerView and call the Appropriate methods using Inteface's Object.
//Interface
public interface ManageButtonClicks
{
void saveBtnClick();
}
//Activity
public class MainActivity extends AppCompactActivity implements ManageButtonClicks
{
ManageButtonClicks manageButtonClicks=this;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
//Do the operations
adapter = new MyAdapter(this,adapterList,manageButtonClicks);
recyclerView.setAdapter(adapter);
}
void saveBtnClick()
{
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
}
}
//Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ManageButtonClicks manageButtonClicks;
public MyAdapter(Context context, List< ModelClass > data, ManageButtonClicks manageButtonClicks)
{
inflater = LayoutInflater.from(context);
this.mDataList = data;
this.ctx = context;
util = new Util(ctx);
this.manageButtonClicks = manageButtonClicks;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewGroup nonPrimeRow = (ViewGroup) inflater.inflate(R.layout.rowlayout, parent, false);
MyViewHolder_NON_PRIME holderNonPrime = new MyViewHolder_NON_PRIME(nonPrimeRow);
return holderNonPrime;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position)
{
ModelClass current = mDataList.get(position);
MyViewHolder_NON_PRIME holder_not_prime = (MyViewHolder_NON_PRIME) holder;
holder_not_prime.setdata(current);
}
class MyViewHolder extends RecyclerView.ViewHolder
{
public MyViewHolder(View itemView)
{
super(itemView);
}
}
public class MyViewHolder_NON_PRIME extends MyViewHolder
{
private Button btnSave;
public MyViewHolder_NON_PRIME(View view)
{
super(view);
btnSave = (MonteButton) view.findViewById(R.id.btnSave);
}
public void setdata(final ModelClass current)
{
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
manageButtonClicks.saveBtnClick();
}
});
}
}
You have a global variable inside recyclerView adapter:
RecyclerViewAdapter {
private boolean isSaveButtonClicked = false;
private boolean isCancelButtonClicked = false;
public void saveButtonClicked(){
isSaveButtonClicked = true;
}}
public void cancelButtonClicked(){
isCancelButtonClicked = true;
}}
When your activity call onclickListeners , you will notice your adapter.
CreatePhotostoryActivity(){
private RecyclerView adapter;
onSaveButtonClicked(){
adapter.saveButtonClicked();
}
onCancelButtonClicked(){
adapter.cancelButtonClicked();
}
}

How to pass the view Id from Recycler Adapter to Activity?

I am trying to pass view Id from Recyclerview Adapter to Activity,when the Recycler view List item is clicked.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter{
public interface OnRecyclerItemClickListener {
void onRecyclerItemClick(User data,int id);
}
List<User> dataSource;
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private Context context;
public ActiveBeepsAdapter(List<User> dataArgs, OnRecyclerItemClickListener onRecyclerItemClickListener,Context context) {
this.dataSource = dataArgs;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_active_message, parent, false);
ViewHolder viewHolder = new ViewHolder(view, onRecyclerItemClickListener);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
User user = dataSource.get(position);
holder.tvId.setText(user.getId());
Picasso.with(context)
.load(user.getProfilePicUrl())
.placeholder(R.drawable.bg_logo)
.error(R.drawable.bg_logo)
.transform(new CircleTransform())
.into(holder.ivUserProfile);
}
#Override
public int getItemCount() {
return dataSource.size();
}
#NonNull
#Override
public String getSectionName(int i) {
return String.valueOf(dataSource.get(i).getId().charAt(0));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private OnRecyclerItemClickListener onRecyclerItemClickListener;
User data = new User();
TextView tvId;
ImageView ivUserProfile;
public ViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(itemView);
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
tvId = (TextView)itemView.findViewById(R.id.tvName);
ivUserProfile = (ImageView)itemView.findViewById(R.id.ivProfilePic);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,id);
}
}
}
Suppose, If the Profile Image is clicked, the view id should sent to activity..
And My Activity
#EActivity
public class ActiveMessage extends AppCompatActivity implements Adapter.OnRecyclerItemClickListener{
#ViewById(R.id.toolbar)
Toolbar toolbar;
#ViewById(R.id.rvactiveMessage)
FastScrollRecyclerView rvmessage;
List<User> allUser;
#ViewById(R.id.toolbar_title)
TextView tv_toolbar;
#AfterViews
protected void init(){
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_drop_down_black_24dp));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tv_toolbar.setText("Active Message");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
allUser = new ArrayList<>();
User user;
String fullName[] = {"ajay","kamal","akhil"};
String id[] = {"its_ajay","its_kamal","its_akhil"};
for(int i=0;i<id.length;i++){
user = new User();
user.setId(id[i]);
user.setFullName(fullName[i]);
allUser.add(user);
}
Adapter adapter = new Adapter(allUser,this,getApplicationContext());
rvmessage.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvmessage.setAdapter(activeBeepsAdapter);
}
#Override
public void onRecyclerItemClick(User data,int id) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (id == R.id.tvName){
Log.d("Id",data.getId());
}
}
public void noInternet(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.alert_dialog);
dialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_active_message);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
In my Activity, If the ProfileImage is clicked, pop up the dialog box.
Also, i need to check if there is Internet Connection when the list Item is clicked.
In adapter onClick method instead of id pass view:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,v);
}
Now in Activity
#Override
public void onRecyclerItemClick(User data,View view) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (view.getId() == R.id.tvName){
Log.d("Id",data.getId());
}
}

How can add EventListener on my Adapter?

I have an Android Activity that have a RecycleView. I want to add an event listener, so I have build this code:
public class ResultActivity extends AppCompatActivity {
private List<Result> lista;
private RecyclerView recyclerView;
private ResultsAdapter pAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results_activity);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//recupero la lista delle medication
ResultDAO manager = new ResultDAO(this);
lista=manager.getResults();
pAdapter = new ResultsAdapter(lista, new ResultsAdapter.OnItemClickListener() {
#Override
public void onItemClick(Result item) {
try{
//recupero i dati della lista in pagina
final Dialog dialog = new Dialog(ResultActivity.this);
//setting custom layout to dialog
dialog.setContentView(R.layout.result_modal);
dialog.setTitle("Parametri");
}catch(Exception e){
Log.e("","");
}
}
});
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(pAdapter);
}
}
This is my custom adapter:
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.MyViewHolder> {
private List<Result> list;
private final OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(Result item);
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView startDate, endDate,examination;
Result result;
public MyViewHolder(View view) {
super(view);
startDate = (TextView) view.findViewById(R.id.startDate);
endDate = (TextView) view.findViewById(R.id.endDate);
examination = (TextView) view.findViewById(R.id.examination);
}
}
public ResultsAdapter(List<Result> list,OnItemClickListener listener)
{
this.listener=listener;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.results_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Result result = list.get(position);
holder.startDate.setText(result.getDateStart()!=null ? result.getDateStart() : "");
holder.endDate.setText(result.getDateEnd()!=null ? result.getDateEnd() : "");
holder.examination.setText(result.getInfo().getDisplayName());
}
#Override
public int getItemCount() {
return list.size();
}
}
Now if I try to start my application and I try to click on one or more item, the method OnClick, does not start.
How can I fixed it?
Read this answer for better understanding
Use below code in Adapter class :-
holher.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// your code
}
});
Check this blog post.
http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
It allows you to add 'on-click-listeners' in a much simpler, reusable way.
Example:
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// Do your thing
}
});

Recycler View Not Refreshing

I'm doing a RecyclerView example. The thing is that when I add the first item on the list it shows the item correctly on the recyclerview but the next items I add aren't showing on the recycle view.
Please help me.
Adapter code is:
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
private ArrayList<Person> mData;
LayoutInflater inflater;
public PersonAdapter() {
}
public PersonAdapter(Context context, ArrayList<Person> data) {
inflater = LayoutInflater.from(context);
update(data);
}
public void update(ArrayList<Person> data) {
mData = data;
notifyDataSetChanged();
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
PersonViewHolder holder = new PersonViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
Person person = mData.get(position);
holder.ivImagen.setImageResource(R.drawable.ic_action_android);
holder.tvNombre.setText(person.getName());
holder.tvApellido.setText(person.getLast_name());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
ImageView ivImagen;
TextView tvNombre;
TextView tvApellido;
public PersonViewHolder(View itemView) {
super(itemView);
ivImagen = (ImageView) itemView.findViewById(R.id.cr_iv_imagen);
tvNombre = (TextView) itemView.findViewById(R.id.cr_tv_name);
tvApellido = (TextView) itemView.findViewById(R.id.cr_tv_last_name);
}
}}
Main Activity Code is:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ArrayList<Person> persons = new ArrayList<>();
EditText et_name;
EditText et_last_name;
RecyclerView rv_names;
PersonAdapter adapter;
Button btAgregar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.tv_name);
et_last_name = (EditText) findViewById(R.id.tv_last_name);
btAgregar = (Button) findViewById(R.id.bt_agregar);
rv_names = (RecyclerView) findViewById(R.id.rv_nombres);
LinearLayoutManager manager = new LinearLayoutManager(this);
rv_names.setLayoutManager(manager);
adapter = new PersonAdapter(this, persons);
rv_names.setAdapter(adapter);
btAgregar.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Person person = new Person(et_name.getText().toString(), et_last_name.getText().toString());
persons.add(person);
Toast.makeText(this, "Items: " + String.valueOf(persons.size()), Toast.LENGTH_SHORT).show();
} }
Try this code for onClick function
#Override
public void onClick(View v) {
Person person = new Person(et_name.getText().toString(), et_last_name.getText().toString());
persons.add(person);
adapter.update(persons);
Toast.makeText(this, "Items: " + String.valueOf(persons.size()), Toast.LENGTH_SHORT).show();
}
UPDATE:
In Adapter code, try the following changes..
public void update(ArrayList<Person> data) {
mData.clear();
mData.addAll(data)
notifyDataSetChanged();
}
In the onClick you are adding a person, but you are not passing the updated list to the adapter by calling the adapter's update method. Might this be the reason?
i just added called adapter.notifyDataSetChanged();

Categories

Resources