Trouble refreshing listview after deleting item in Android Studio - android

I have a problem refreshing the cardviews in a listview after deleting or editing one cardview, I have tried with the .notifyDataSetChanged() but didn't work. I'm really new in Android Studio.
Here is my code:
RegistroActivity
public class RegistroActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private List<Registro> items = new ArrayList<>();
private RegistroAdapter registroAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
RegistroModel registroModel = new RegistroModel();
Cursor query = registroModel.showReg(HomeActivity.database);
if (query.moveToFirst()) {
do {
Registro expense = new Registro(query.getInt(0), query.getString(1), query.getFloat(2), query.getFloat(3), query.getString(4), query.getString(5) );
items.add(expense);
} while (query.moveToNext());
}
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setPadding(8, 8, 8, 8);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RegistroAdapter(items);
recyclerView.setAdapter(adapter);
}
}
I fill the data from a model with a simple select * from, and send the data to the adapter. Here is my adapter:
public class RegistroAdapter extends RecyclerView.Adapter<RegistroAdapter.RegistroViewHolder> {
private List<Registro> items;
public static class RegistroViewHolder extends RecyclerView.ViewHolder {
public ImageView color;
public TextView descr;
public TextView precio;
public TextView cantidad;
public ImageButton delete_expense;
public ImageButton edit_expense;
public Context cont;
public RegistroViewHolder(View v, Context context) {
super(v);
color = (ImageView) v.findViewById(R.id.card_image);
descr = (TextView) v.findViewById(R.id.description);
precio = (TextView) v.findViewById(R.id.precio);
cantidad = (TextView) v.findViewById(R.id.cantidad);
delete_expense = (ImageButton) v.findViewById(R.id.delete_button);
edit_expense = (ImageButton) v.findViewById(R.id.edit_button);
cont = context;
}
}
public RegistroAdapter(List<Registro> items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public RegistroViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.registro_card, viewGroup, false);
return new RegistroViewHolder(v, viewGroup.getContext());
}
//
#Override
public void onBindViewHolder(RegistroViewHolder viewHolder, final int i) {
String gramos = viewHolder.cont.getResources().getString(R.string.gramos);
String fecha = viewHolder.cont.getResources().getString(R.string.fecha);
String desc = viewHolder.cont.getResources().getString(R.string.tvDesc);
viewHolder.color.setImageResource(R.color.fondoCard);
viewHolder.descr.setText(fecha + " " + items.get(i).getDate() + "\n" + "\n" + " " + items.get(i).getDesc());
viewHolder.precio.setText(items.get(i).getPrice().toString() + " " + items.get(i).getMoneda() );
viewHolder.cantidad.setText(items.get(i).getAmount().toString() + " " + gramos );
viewHolder.edit_expense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), EditRegistroActivity.class);
int pos = items.get(i).getId();
intent.putExtra("position", pos);
v.getContext().startActivity(intent);
}
});
viewHolder.delete_expense.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = items.get(i).getId();
try{
SQLiteDatabase conn = HomeActivity.database.getWritableDatabase();
int n = conn.delete("registro","id="+pos, null);
if (n == 1){
Toast.makeText(v.getContext(), v.getContext().getString(R.string.mensajeEliminarexito), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(v.getContext(),v.getContext().getString(R.string.mensajeErrorEliminar) , Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(v.getContext(), "Error. ID=" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
I set the data within the elements in the card-view, this card-view has two Image-buttons to delete and edit each item in the card-view. I set the onClickListener for them. It edits and deletes completely fine but it doesn't refresh the information.

The reason is that you are making any changes on SQLite db and not in the adapter's items List. Adapter works only with the dataset you have passed to it when initializing it in your RegistroActivity. Therefore, when you want to change something you need to change SQLite to store modification permanently and refresh the dataset in adapters to allow user see the changes.
In your case, try adding three lines of code that are given below:
viewHolder.delete_expense.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = items.get(i).getId();
try{
SQLiteDatabase conn = HomeActivity.database.getWritableDatabase();
int n = conn.delete("registro","id="+pos, null);
items.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, item.size());
if (n == 1){
Toast.makeText(v.getContext(), v.getContext().getString(R.string.mensajeEliminarexito), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(v.getContext(),v.getContext().getString(R.string.mensajeErrorEliminar) , Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(v.getContext(), "Error. ID=" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
});

Just remove your item from adapter before notifying, like this
items.remove(i);
When you remove item from db it will not update you list, because your adapter holds data from passed before list.

Related

Data are not deleted from database

First of all I have to tell I am still learning Android studio and maybe I missed some important and obvious staff.
Now I am facing with problem with my database, or maybe RecycleViwe i am not sure.
I my app, I am trying insert data into db and only in case if data is empty. I did it and I think that works.
Now I am trying to implement new method to read data and delete. For now I can show data in my recycleView.
My problem come with delete method. When I start app, and when delete some items it is show like everything is fine. But when I start app again, data appears again like nothing was happened.
I am not sure what cause this problem. Hope some of you guys can help me?
Below you will find parts of code. If you want to see more, feel free to ask me.
In this part of code, I call my data and showing them in recycleView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pondeljak = (Button) findViewById(R.id.buttonPonedeljak);
utorak = (Button) findViewById(R.id.buttonUtorak);
sreda = (Button) findViewById(R.id.buttonSreda);
cetvrtak = (Button) findViewById(R.id.buttonCetvrtak);
petak = (Button) findViewById(R.id.buttonPetak);
View view = getLayoutInflater().inflate(R.layout.casovi,null);
alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(view);
db = new DataDays(this);
alertDialog = alertDialogBuilder.create();
recyclerView = (RecyclerView) view.findViewById(R.id.recycleCasoviID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
casoviList = new ArrayList<>();
casoviItems = new ArrayList<>();
casoviList = db.getCasoviPonedeljak();
for (Casovi c: casoviList){
Casovi casovi = new Casovi();
casovi.setRedniBrCasa(c.getRedniBrCasa());
casovi.setNzaivCasa(c.getNzaivCasa());
casoviItems.add(casovi);
}
recycleViewAdapter = new RecycleViewAdapter(this, casoviItems);
recyclerView.setAdapter(recycleViewAdapter);
recycleViewAdapter.notifyDataSetChanged();
pondeljak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (db.casoviCountPondeljak() == 0){
Intent intent = new Intent(MainActivity.this, Unos_casova.class);
intent.putExtra("Dan", "Pondeljak");
startActivity(intent);
}else {
alertDialog.show();
}
}
});
Here is my recycleView and there is also my deletemethod. For sure core fore delete method could be written in a more simple way but I copied some of my last trials.
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
private Context context;
private List<Casovi> casoviItems;
public RecycleViewAdapter(Context context, List<Casovi> casoviItems) {
this.context = context;
this.casoviItems = casoviItems;
}
#Override
public RecycleViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prikaz_casova, parent,false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder( RecycleViewAdapter.ViewHolder holder, int position) {
Casovi casovi = casoviItems.get(position);
holder.redniBrCasPrikaz.setText(casovi.getRedniBrCasa());
holder.nazivCasPrikaz.setText(casovi.getNzaivCasa());
}
#Override
public int getItemCount() {
return casoviItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView redniBrCasPrikaz;
public TextView nazivCasPrikaz;
public Button delteBtn;
public Button editBtn;
public CardView cardView;
public int id;
public ViewHolder(View view, Context ctx) {
super(view);
context = ctx;
redniBrCasPrikaz = (TextView) view.findViewById(R.id.rednibrojCasaID);
nazivCasPrikaz = (TextView) view.findViewById(R.id.nazivcasaID);
delteBtn = (Button) view.findViewById(R.id.obrisiCasBtnID);
editBtn = (Button) view.findViewById(R.id.izmeniCasBtnID);
cardView = (CardView) view.findViewById(R.id.carViewID);
delteBtn.setOnClickListener(this);
editBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.obrisiCasBtnID:
int position = getAdapterPosition();
Casovi casovi = casoviItems.get(position);
deleteItem(casovi.getId());
notifyItemRemoved(getAdapterPosition());
break;
}
}
public void deleteItem (final int id){
DataDays db = new DataDays(context);
db.deleteCas(id);
casoviItems.remove(getAdapterPosition());
}
}
}
And here are some parts of Data Base. As I told you I am not sure what can be a problem, maybe some of these method are written in a wrong way.
public void addCasovePonedeljak (Casovi casovi){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.DAN, "Ponedeljak");
values.put(Constants.REDNI_CAS, casovi.getRedniBrCasa());
values.put(Constants.CAS, casovi.getNzaivCasa());
db.insert(Constants.TABLE_NAME, null, values);
}
public List<Casovi> getCasoviPonedeljak(){
SQLiteDatabase db = this.getReadableDatabase();
List<Casovi> casoviList = new ArrayList<>();
String pondeljakQuery = "SELECT * FROM " + Constants.TABLE_NAME + " WHERE " + Constants.DAN + " = " + " 'Ponedeljak' ";
Cursor cursor = db.rawQuery(pondeljakQuery, null);
if (cursor.moveToFirst()){
do {
Casovi casovi = new Casovi();
//casovi.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.ID))));
//casovi.setDan(cursor.getString(cursor.getColumnIndex(Constants.DAN)));
casovi.setNzaivCasa(cursor.getString(cursor.getColumnIndex(Constants.CAS)));
casovi.setRedniBrCasa(cursor.getString(cursor.getColumnIndex(Constants.REDNI_CAS)));
casoviList.add(casovi);
}while (cursor.moveToNext());
}
return casoviList;
}
public void deleteCas(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TABLE_NAME, Constants.CAS + " = ?",
new String[] {});
db.close();
}
public int casoviCountPondeljak() {
String countQuery = "SELECT * FROM " + Constants.TABLE_NAME;
//String countQuery = "SELECT COUNT(*) FROM " + Constants.TABLE_NAME + " WHERE " + Constants.DAN + " = '" + "Ponedeljak' ";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery,null);
//cursor.moveToFirst();
return cursor.getCount();
}
}
Your delete method is wrong.. You are passing parameter id but not using the id in your method as
public void deleteCas(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TABLE_NAME, Constants.CAS + " = ?",
new String[] {});
db.close();
}
It should be
public void deleteCas(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Constants.TABLE_NAME, Constants.CAS + " = ?",
new String[] {id.toString()});
db.close();
}
Syntax not tested

how to get all listview checked item on buttonclick?

setContentView(R.layout.activity_violation);
db = new DatabaseHelper(this);
sqLiteDatabase = db.getReadableDatabase();
spinner = (Spinner) findViewById(R.id.spinner1);
loadspinnerdata();
txtTexts = (TextView) findViewById(R.id.texts);
btnBack = (Button) findViewById(R.id.btnBack);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listviewData();
}
});
strSelectedItem = spinner.getSelectedItem().toString();
listview = (ListView) findViewById(R.id.listView);
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.list_header, listview, false);
listview.addHeaderView(header, null, false);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_query = "select _id,section,offence,fine from tblSection";
Cursor clistview = sqLiteDatabase.rawQuery(list_query, null);
listadapter = new ListAdapter(this, clistview, 0);
listview.setAdapter(listadapter);private void listviewData() {
int cntChoice = listview.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i))
{
checked += listview.getItemAtPosition(i).toString() + "\n";
}
else if(!sparseBooleanArray.get(i))
{
unchecked+= listview.getItemAtPosition(i).toString() + "\n";
}
}
I am using cursorAdapter in order to populate listview from database?so I am not getting position as i get from getView method in arrayAdapter
public class ListAdapter extends CursorAdapter{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
ArrayAdapter<String> objects;
private boolean chkItem;
CompoundButton.OnCheckedChangeListener myCheckChangList;
public ListAdapter(Context context, Cursor c, int _id) {
super(context, c,_id);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.listview_item,viewGroup,false);
}
public class ViewHolder{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
boolean chkItem;
boolean selected = false;
public ViewHolder(boolean chkItem){
super();
this.chkItem=chkItem;
}
public ViewHolder() {
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder=null;
holder = new ViewHolder();
holder.tvSection = (TextView) view.findViewById(R.id.txtSection);
holder.tvOffence = (TextView) view.findViewById(R.id.txtOffence);
holder.tvId = (TextView) view.findViewById(R.id.txtId);
holder.tvFine = (TextView) view.findViewById(R.id.txtFine);
holder.chkBox = (CheckBox) view.findViewById(R.id.checkBox);
holder.chkBox.setOnCheckedChangeListener(myCheckChangList);
view.setTag(holder);
strFine=cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String strSection = cursor.getString(cursor.getColumnIndexOrThrow("section"));
String strOffence = cursor.getString(cursor.getColumnIndexOrThrow("offence"));
int strFine = cursor.getInt(cursor.getColumnIndexOrThrow("fine"));
holder.tvSection.setText(strSection);
holder.tvOffence.setText(strOffence);
holder.tvFine.setText(String.valueOf(strFine));
final ViewHolder finalHolder = holder;
}
I tried this but this isn't working.I tried checkbox.setOnclicklistener which gives me the checked row value single item but not multiple checked item.I tried sparseboolean array also.
If you are trying to get selected values from listing using checkbox,try this way it will work
public class CardViewActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Student> studentList;
private Button btnSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSelection = (Button) findViewById(R.id.btnShow);
studentList = new ArrayList<Student>();
for (int i = 1; i <= 15; i++) {
Student st = new Student("Student " + i, "androidstudent" + i
+ "#gmail.com", false);
studentList.add(st);
}
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(studentList);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<Student> stList = ((CardViewDataAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
Student singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
data = data + "\n" + singleStudent.getName().toString();
/*
* Toast.makeText( CardViewActivity.this, " " +
* singleStudent.getName() + " " +
* singleStudent.getEmailId() + " " +
* singleStudent.isSelected(),
* Toast.LENGTH_SHORT).show();
*/
}
}
Toast.makeText(CardViewActivity.this,
"Selected Students: \n" + data, Toast.LENGTH_LONG)
.show();
}
});
}
}
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
On clicking outside the adapter, use the following code. "ListAdapter" should be the Adapter class name.
ListAdapter.unCheck((ViewGroup)view.getParent());
If your on clicking is inside the adapter, then ignore the above code and use the below one.
unCheck((ViewGroup)view.getParent());
make the following function in Adapter.
public static void unCheck(ViewGroup vg) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if (v instanceof CheckBox) {
((CheckBox) v).setChecked(true);
} else if (v instanceof ViewGroup) {
unCheck((ViewGroup) v);
}
}
}
The above function will checked all the checkBox of the list view. Have Fun. Take Care.

How to increment TextView value outside ListView when ListView button is clicked in Android

I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});

Add new cardview dynamically on button click in android

I am using a cardview with recyclerview with hardcoded values such as string arrays. But now i want to add new cardview on each button click with user enter values and user select image and keep remain all cardviews on app exit.I mean to say that cardview should be added one by one only.Any solution plz guide me.
cardview Adapter class
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static ArrayList<FeddProperties> dataSet;
private static Context context;
public CardViewDataAdapter(Context context, ArrayList<FeddProperties> os_versions) {
this.context = context;
dataSet = os_versions;
}
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewDataAdapter.ViewHolder viewHolder, int i) {
FeddProperties fp = dataSet.get(i);
viewHolder.vehicleNumber.setText(fp.getTitle());
viewHolder.iconView.setImageResource(fp.getThumbnail());
viewHolder.feed = fp;
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView vehicleNumber;
public ImageView iconView;
public FeddProperties feed;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
vehicleNumber = (TextView) itemLayoutView
.findViewById(R.id.vehiclenumber);
iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), InformingUser.class);
v.getContext().startActivity(intent);
((MainActivity) context).getSupportFragmentManager().beginTransaction().replace
(R.id.containerView, new InformingUser()).commit();
//Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
}
Java file....
private void initContrls()
{
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, 0);
vehiclecatory = prefs.getString("vehicle_category", "");
vehicletype = prefs.getString("vehicle_type", "");
String versions = prefs.getString("city", "")+" "+prefs.getString("dis", "")+" "+prefs.getString("number", "");
String vehicleCompany = prefs.getString("company", "")+" "+prefs.getString("model", "");
if(vehiclecatory.equals("1"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.contwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.comfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.comheavy;
}
}
else if (vehiclecatory.equals("2"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.nontwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.nonfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.nonheavy;
}
}
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < 2; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions);
feed.setVehicleCompany(vehicleCompany);
feed.setThumbnail(icons);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
mAdapter = new CardViewDataAdapter(context,os_versions);
recyclerView.setAdapter(mAdapter);
}
here there is an example to add cardview dinamically
In this example cardview are create with for:
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Some Primary Text " + index,
"Secondary " + index);
results.add(index, obj);
}
but you can inser into onClick action :)

View Changes While scrolling RecyclerView

I'm using RecyclerView, I have one ImageButton as Child view, I'm changing the background of that ImageButton on click.
Now my problem is when change Image of ImageButton by clicking and than scroll up again scroll to the top, the state of set to the initial stage. I tried everything but its not happening. help me with that.
My Adapter class
public class ViewAllAdapter extends RecyclerView.Adapter<ProductHolder> {
int[] objects;
Context context;
Boolean flag = false;
public ViewAllAdapter(int[] objects, Context context) {
super();
this.objects = objects;
this.context = context;
}
#Override
public int getItemCount() {
return objects.length;
}
#Override
public void onBindViewHolder(final ProductHolder arg0, int arg1) {
arg0.title.setText("Product" + arg1 + 1);
arg0.aPrice.setPaintFlags(arg0.aPrice.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
arg0.aPrice.setText("\u20B9" + " " + "5000");
arg0.off.setText("56% off");
arg0.price.setText("\u20B9" + " " + "2300");
arg0.mainImage.setImageResource(objects[arg1]);
arg0.ratings.setRating(4f);
arg0.clickme.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,
ProductDetailsPage.class);
startActivity(i);
}
});
arg0.wish.setBackgroundResource(R.drawable.heart);
arg0.wish.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!flag) {
arg0.wish.setBackgroundResource(R.drawable.heartfade);
YoYo.with(Techniques.Tada).duration(550)
.playOn(arg0.wish);
Toast.makeText(context, "Product Added to wish list..",
Toast.LENGTH_SHORT).show();
flag = true;
} else {
arg0.wish.setBackgroundResource(R.drawable.heart);
Toast.makeText(context,
"Product Removed to wish list..",
Toast.LENGTH_SHORT).show();
flag = false;
}
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
LayoutInflater inflater = LayoutInflater.from(arg0.getContext());
View view = inflater.inflate(R.layout.viewall_item, arg0, false);
return new ProductHolder(view);
}
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView title;
protected TextView aPrice;
protected TextView off;
protected TextView price;
protected ImageView mainImage;
protected RatingBar ratings;
protected ImageButton wish;
protected RelativeLayout clickme;
public ProductHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.productName);
aPrice = (TextView) itemView
.findViewById(R.id.productActualPrice);
off = (TextView) itemView.findViewById(R.id.offPrice);
price = (TextView) itemView.findViewById(R.id.productPrice);
mainImage = (ImageView) itemView
.findViewById(R.id.productImage);
wish = (ImageButton) itemView.findViewById(R.id.addToWishList);
ratings = (RatingBar) itemView
.findViewById(R.id.productRatings);
clickme = (RelativeLayout) itemView
.findViewById(R.id.clickToGO);
}
}
}
And in My MainActicity I'm doing
rv = (RecyclerView) findViewById(R.id.gvViewAll);
rv.setHasFixedSize(true);
GridLayoutManager glm = new GridLayoutManager(getApplicationContext(),
2);
rv.setLayoutManager(glm);
final ViewAllAdapter adp = new ViewAllAdapter(productImage,
getApplicationContext());
rv.setAdapter(adp);
rvh = (RecyclerViewHeader) findViewById(R.id.header);
rvh.attachTo(rv, true);
Thanks for any help.
As per your Custom RecyclerView adapter, I suggest you to use HashMap to store Values. After all Data Model is best option to load data in to RecyclerView.
HashMap<Integer, Integer> hashMapTest = new HashMap<>();
When user click on ImageButton then add following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hashMapTest.get(position) != null && hashMapTest.get(position) != false) {
// Code of Product Added to wish list..
hashMapTest.put(getPosition(), 1);
} else {
// Code of Product Removed to wish list..
hashMapTest.put(getPosition(), 0);
}
}
});
In your onBindViewHolder(ProductHolder holder, int position) add following code
if(hashMapTest.get(position) != null && hashMapTest.get(position) != false) {
// Show your ImageButton color Product Added to wish list..
} else {
// Show your ImageButton color Product Removed to wish list..
}
Hope it helps you.

Categories

Resources