Androd SQLite display data read from a CursorAdapter class and a ListView in ViewHolder instead.
I wanted a CheckBox for each line, which can put specific updates the database record.
The thing does not work well because when I activate the first line CheckBox you change that appear on the screen last line record.
long _id = todo.getID(); //
checkBoxFavorite.setTag(_id);
checkBoxFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
//Update database row
}
else if (!isChecked)
{
//Update database row
}
}
});
Try this.
public class MainActivity extends AppCompatActivity{
private RecyclerView recyclerView;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
TestAdapter adapter = new TestAdapter();
recyclerView.setAdapter(adapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
}
class TestViewHolder extends RecyclerView.ViewHolder
{
CheckBox checkBox;
public TestViewHolder(View view)
{
super(view);
checkBox=(CheckBox)view.findViewById(R.id.checkbox);
}
public void addDetail(int positon)
{
checkBox.setText(list.get(positon));
}
}
class TestAdapter extends RecyclerView.Adapter<TestViewHolder>
{
public TestAdapter()
{
}
#Override
public TestViewHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.recycler_item,null);
return new TestViewHolder(view);
}
#Override
public void onBindViewHolder(TestViewHolder viewHolder, int i)
{
viewHolder.addDetail(i);
}
#Override
public int getItemCount() {
return list.size();
}
}}
you have to use the setTag() and getTag(), on the view you can check out from this blog post Link
This is not a stright forward answer but it will get started.
Related
I have a basic RecyclerView list and added a ItemTouchHelper in order to drag and drop list items.
The problem I have with it is that it runs onMove on every single list item it passes and it's lagging the app real hard.
Is there a way to implement it so that onMove only runs when I release my hold on a RecyclerView list item?
Thanks.
MainActivity.java
public class pillar_sort extends AppCompatActivity {
private MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize layout
super.onCreate(savedInstanceState);
setContentView(R.layout.pillar_sort);
final SharedPreferences sharedPref = // Get SharedPreferences
final ArrayList<String> modules = // Import a list
final ArrayList<Boolean> visibility = // Import a list
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, modules, visibility, cardcolor, txtcolor);
recyclerView.setAdapter(adapter);
VerticalSpaceItemDecoration decor = new VerticalSpaceItemDecoration();
recyclerView.addItemDecoration(decor);
ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP|ItemTouchHelper.DOWN, 0) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder dragged, #NonNull RecyclerView.ViewHolder target) {
int position_dragged = dragged.getAdapterPosition();
int position_target = target.getAdapterPosition();
Collections.swap(modules,position_dragged,position_target);
adapter.notifyItemMoved(position_dragged,position_target);
adapter.notifyDataSetChanged();
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
});
helper.attachToRecyclerView(recyclerView);
}
MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
// Variables go here
MyRecyclerViewAdapter( /* a lot of data to pass onto the adapter */ ) {
// get data from MainActivity and put on variables
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
CardView card = view.findViewById(R.id.card);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position){
// Put data to TextViews and set card color
}
#Override
public int getItemCount() {
return modules.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ImageButton image_visibility;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.rowText);
image_visibility = itemView.findViewById(R.id.imageButton);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
I have used Spinner in Recyclerview.I have one button in Mainactivity. when i click that button, i need get all selected item from each row of recyclerview.getSelectedItem() method will return the selected item from spinner but i think only for single item it is working.
I think no need to use setOnItemSelectedListener.
My code is :
public class MainActivity extends AppCompatActivity {
RecyclerView recycler_view;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler_view=findViewById(R.id.recycler_view);
button = findViewById(R.id.button);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(mLayoutManager);
setAdapter();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
private void setAdapter( ) {
recycler_view.setVisibility(View.VISIBLE);
StudentsListAdapter studentsListAdapter = new StudentsListAdapter(this);
recycler_view.setAdapter(studentsListAdapter);
// runLayoutAnimation(recycler_view, mSelectedItem);
}
}
Adapter:
public class StudentsListAdapter extends RecyclerView.Adapter<StudentsListAdapter.MyViewHolder> {
String[] list={"Microbiology","Pharmacology","Microbiology","Forensic Medicine"};
String[] studentsName={"Student1","Student2","Studen3","Student4"};
Context ctx;
private ArrayAdapter<String> dataAdapter;
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.text_name)
TextView text_name;
#BindView(R.id.spinner1)
Spinner spinner1;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public StudentsListAdapter(Context ctx ) {
this.ctx = ctx;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.student_list_item, parent, false);
return new MyViewHolder(itemView);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
holder.text_name.setText(studentsName[position]);
dataAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner1.setAdapter(dataAdapter);
Log.d("Holder ",""+ holder.spinner1.getSelectedItem());
}
#Override
public int getItemCount() {
return studentsName.length;
}
}
I guess you need to add an checkbox to know which of the items are selected.
Arraylist selectedStudent = new Arraylist();
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
holder.text_name.setText(studentsName[position]);
dataAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner1.setAdapter(dataAdapter);
Log.d("Holder ",""+ holder.spinner1.getSelectedItem());
//checkbox listener
holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (isChecked){
selectedStudent.add(studentsName[position]);
}
}
});
}
In your activity, you can access your variable selectedStudent
StudentsListAdapter studentListAdapter;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < studentListAdapter.selectedStudent.size()-1 ; i++) {
Log.d("studentSelected".""+studentListAdapter.selectedStudent.get(i));
}
}
});
Use another List with the size of the Spinner list and add the default values of each spinner to the list. Whenever you change the value in the spinner change the value in the selected values list also.
now add a new method in the adapter to get the selected values list. and call that method on the button click
I am trying to load recyclerview with data from SQLite database contents. But it is not working
This is what i have done
Activity class
public class ViewMembership extends AppCompatActivity {
private RecyclerView recyclerView;
private membership_view_recycler_adapter m;
private DBHelper dbHelper;
public List<membership_recycler_model> membershipList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_membership);
dbHelper=new DBHelper(this);
////////////////////////////////////////////////////////////////////////////
recyclerView=(RecyclerView) findViewById(R.id.View_Membership_Recycler);
m=new membership_view_recycler_adapter(membershipList);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(m);
prepare_membership();
//////////////////////////////////////////////////////////////////////////
}
public void prepare_membership()
{
System.out.println("#######################Prepare_membership called");
membershipList=dbHelper.membership_for_recycler_view();
m.notifyDataSetChanged();
}}
Adapter class
public class membership_view_recycler_adapter extends RecyclerView.Adapter<membership_view_recycler_adapter.MyViewHolder> {
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,region;
public MyViewHolder(View itemView) {
super(itemView);
name=(TextView) itemView.findViewById(R.id.membership_name_textview);
region=(TextView) itemView.findViewById(R.id.membership_region_textview);
}
}
public membership_view_recycler_adapter(List<membership_recycler_model> membership_list) {
this.membership_list = membership_list;
}
private List<membership_recycler_model> membership_list;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.membership_view_row,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
membership_recycler_model membership=membership_list.get(position);
holder.name.setText(membership.getMembership_name());
holder.region.setText(membership.getRegion());
}
#Override
public int getItemCount() {
return membership_list.size();
}}
I've got no compilation errors, application is not throwing any exceptions. dbHelper.membership_for_recycler_view() is returning appropriate values. I am kinda new in Android. I did this with the help of a tutorial. What have I done wrong?
I think the problem here is you are calling prepare_membership()
function later and passing data to your adapter before with an empty list. Try to make following changes :
Add a new method in your adapter -
public void refreshData(List<membership_recycler_model> membership_list){
this.membership_list = membership_list;
notifyDataSetChanged();
}
Inside your prepare_membership() function call this method after fetching the list from db i.e m.refreshData(membershipList)
`
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
}
});
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();