Adding recyclerview - android

I would like to create a simple application which has two activities. Activity A has recyclerview, and Activity B uploads the input data of edittexts. Creating recyclerview and passing data work well, but the view is not created more than 1. I would like to know what did I do wrong.
Activity A which has recyclerview.
public class MainActivity extends AppCompatActivity {
private ArrayList<MainData> list;
private MainAdapter adapter;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
list = (ArrayList<MainData>) getIntent().getSerializableExtra("list");
adapter = new MainAdapter(list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Activity B which uploads data.
public class upload extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(upload.this, MainActivity.class);
ArrayList<MainData> list = new ArrayList<>();
EditText edit = (EditText) findViewById(R.id.edittext_name);
EditText edit_main = (EditText) findViewById(R.id.edittext_main);
list.add(new MainData(edit.getText().toString(), edit_main.getText().toString()));
intent.putExtra("list",list);
startActivity(intent);
finish();
}
});
Adapter :
public MainAdapter.CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
CustomViewHolder holder = new CustomViewHolder(view);
return holder;
}
public void onBindViewHolder(#NonNull MainAdapter.CustomViewHolder holder, int position) {
//holder.iv_profile.setImageResource(list.get(position).getIv_profile());
holder.tv_name.setText(list.get(position).getTv_name());
holder.tv_content.setText(list.get(position).getTv_content());
holder.itemView.setTag(position);
#Override
public int getItemCount() {
return (null != list ? list.size() : 0);
}
public void remove(int position) {
try {
list.remove(position); //
notifyItemRemoved(position);
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView iv_profile;
protected TextView tv_name;
protected TextView tv_content;
public CustomViewHolder(#NonNull View itemView) {
super(itemView);
this.iv_profile = (ImageView) itemView.findViewById(R.id.iv_profile);
this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
this.tv_content = (TextView) itemView.findViewById(R.id.tv_content);
}
}

Related

Get selected item position in Recyclerview

I am using Recyclerview. I added a menu with Recyclerview. I want to make a switch case in Recyclerview. So when I click on item 1, when I click on item 2, I click on step 3. When I click on my item .. I want to call a function. Currently I tried to read the position of the items with getAdapterPosition, but the output is always -1. For example, when I click on model, when I click on model2, I want to call a function.
Main2Activity
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView navRecyclerView;
LinearLayoutManager layoutManager;
ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
NavigationAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView.setNavigationItemSelectedListener(this);
navRecyclerView = findViewById(R.id.navRecyclerView);
navRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
navRecyclerView.setLayoutManager(layoutManager);
DividerItemDecoration divider = new DividerItemDecoration(
navRecyclerView.getContext(),
DividerItemDecoration.VERTICAL
);
divider.setDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.diveder_recycler));
navRecyclerView.addItemDecoration(divider);
initArray();
adapter = new NavigationAdapter(this, arrayList);
navRecyclerView.setAdapter(adapter);
private void initArray() {
NavigationDataModel model = new NavigationDataModel();
model.setIcon(R.mipmap.avatar);
model.setTitle("Hesabım");
arrayList.add(model);
NavigationDataModel model2 = new NavigationDataModel();
model2.setIcon(R.mipmap.sss3);
model2.setTitle("S.S.S");
arrayList.add(model2);
}
NavigationAdapter
public class NavigationAdapter extends RecyclerView.Adapter<NavigationAdapter.ViewHolder> {
Context context;
ArrayList<NavigationDataModel> arrayList = new ArrayList<>();
public NavigationAdapter(Context context, ArrayList<NavigationDataModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.navigationrecyclerview_adapter11, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.navTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
System.out.println("asdasdadasd" + position);
}
});
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.navIcon.setImageResource(arrayList.get(position).getIcon());
holder.navIconNew.setImageResource(arrayList.get(position).getIcon());
holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
holder.navTitle.setText(arrayList.get(position).getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView navIcon, navIconNew;
TextView navTitle;
LinearLayout rootView;
public ViewHolder(View itemView) {
super(itemView);
rootView = itemView.findViewById(R.id.rootView);
navIcon = itemView.findViewById(R.id.navIcon);
navIconNew = itemView.findViewById(R.id.navIconNew);
navTitle = itemView.findViewById(R.id.navTitle);
Toast.makeText(context, String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.navIcon.setImageResource(arrayList.get(position).getIcon());
holder.navIconNew.setImageResource(arrayList.get(position).getIcon());
holder.rootView.setBackgroundColor(arrayList.get(position).getColor());
holder.navTitle.setText(arrayList.get(position).getTitle());
holder.navTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use position herer
}
});
}

Adding item dynamically to recyclerview

I am building a notepad app. I am trying to add another item to the recyclerview as soon as the new note is saved by the user.
public class NotePad extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_pad);
final FloatingActionButton button =
(FloatingActionButton)findViewById(R.id.save_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveData();
}
});
}
// To Send Note Title to MainActivity
public void SendData() {
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
Log.d("Check","str:"+str);
Intent intent = new Intent(NotePad.this,MainActivity.class);
intent.putExtra(EXTRA_MESSAGE, str);
startActivity(intent);
}
// To Save Note Content
public void SaveData() {
FileOutputStream outputStream;
try {
EditText editText = findViewById(R.id.textView3);
final String str = editText.getText().toString();
String content = findViewById(R.id.textView).toString();
Log.d("Test","inside try block");
outputStream = openFileOutput(str, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
Log.d("Test","save done");
SendData();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I am saving a note and sending the title(str) that is to be displayed in recyclerview row to MainActivity as shown above.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<String> notes = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
String title = intent.getStringExtra(NotePad.EXTRA_MESSAGE);
Log.d("Check","title added"+title);
notes.add(title);
BuildRecyclerView();
}
public void BuildRecyclerView() {
recyclerView = (RecyclerView)findViewById(R.id.recycle_list);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MyAdapter(notes);
recyclerView.setAdapter(mAdapter);
}
But whenever I add a new note it overwrites the first entry in the recyclerview instead of occupying the next row of the recyclerview. This is my adapter code:
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<String> Notes_list = new ArrayList<String>();
public MyAdapter(ArrayList<String> notes) {
Notes_list = notes;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_items,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int
position) {
holder.mTextView.setText(Notes_list.get(position));
}
#Override
public int getItemCount() {
return Notes_list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.view_holder);
}
}
}
Because you pass last item to MainActivity and generate a new RecyclerView with passed item. You have to keep notes array on first class and pass whole array to MainActivity with intent.

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

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

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