Set values ​back to start - java

If I click the button CHECKOUT a pop up shows up. In this pop up, you have the chance to abort the transaction. So if you abort the transaction all the values for the Items (French fires, Water, Burger) should be 0 again as seen in the picture below. Right now when i abort the transaction the values stay the way i configured them before. Can you help me with that?
OrderActivity.java
package com.nfc.netvision;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import static android.widget.Toast.*;
public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {
RecyclerView recyclerView;
ArrayList<ModelOrder> orderArrayList;
TextView textView_order_price;
TextView textView_order_count;
Dialog epicDialog;
Button btnCheckout;
Button btnAbort;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
recyclerView = findViewById(R.id.recyclerview_order_scroll);
textView_order_price = findViewById(R.id.textView_order_price);
textView_order_count = findViewById(R.id.textView_order_count);
btnCheckout = (Button) findViewById(R.id.btnCheckout);
orderArrayList = new ArrayList<>();
orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager recLiLayoutManager = layoutManager;
recyclerView.setLayoutManager(recLiLayoutManager);
OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);
recyclerView.setAdapter(adapter);
epicDialog = new Dialog(this);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showWaitingPopUp();
}
});
}
private void showWaitingPopUp() {
epicDialog.setContentView(R.layout.order_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
btnAbort = (Button) epicDialog.findViewById(R.id.btnAbort);
btnAbort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.show();
}
#Override
public void onTotalChanged(String result) {
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.GERMANY);
textView_order_price.setText( n.format(Integer.parseInt(result)));
}
#Override
public void onCountChanged(String result) {
textView_order_count.setText(result);
}
}
OrderAdapter.java
package com.nfc.netvision;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.w3c.dom.Text;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
private int totalAmount;
private int totalItems;
private Context mContext;
private ArrayList<ModelOrder> nList;
private TotalListener listener;
interface TotalListener{
void onTotalChanged(String result);
void onCountChanged(String result);
}
OrderAdapter(Context context, ArrayList<ModelOrder> list, TotalListener listener) {
mContext = context;
nList = list;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final ModelOrder orderItem = nList.get(position);
ImageView image = holder.item_image;
final TextView name, place, price;
name = holder.item_name;
place = holder.item_place;
price = holder.item_price;
image.setImageResource(orderItem.getImage());
name.setText(orderItem.getName());
place.setText(orderItem.getPlace());
price.setText(orderItem.getPrice());
holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() > 0) {
orderItem.setCounter(orderItem.getCounter()-1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), false);
countItems(orderItem.getCounter(), false);
}
}
});
holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() < 9) {
orderItem.setCounter(orderItem.getCounter() + 1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), true);
countItems(orderItem.getCounter(), true);
}
}
});
}
#Override
public int getItemCount() {
return nList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView item_image;
TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.order_item_image);
item_name = itemView.findViewById(R.id.order_item_name);
item_place = itemView.findViewById(R.id.order_item_place);
item_price = itemView.findViewById(R.id.order_item_price);
order_item_minus = itemView.findViewById(R.id.order_item_minus);
order_item_plus = itemView.findViewById(R.id.order_item_plus);
order_item_count = itemView.findViewById(R.id.order_item_count);
}
}
private void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
listener.onTotalChanged(totalAmount+ "");
}
private void countItems(int pCounter, boolean pUpDown){
if (pUpDown){
totalItems = totalItems + 1;
}
else{
totalItems = totalItems - 1;
}
listener.onCountChanged(totalItems+ "");
}
}

They stay the way there were because inside your abort button's onClick you just dismiss the dialog and do not change the list values.
I suggest iterating through the list and setting all counters to 0.
Also, don't forget to notify your RecyclerView that you modified something, in this case you reset all counters to 0. Otherwise, you won't see the changes in your app.
private void showWaitingPopUp() {
epicDialog.setContentView(R.layout.order_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
btnAbort = epicDialog.findViewById(R.id.btnAbort);
btnAbort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set all orders count to 0
for (ModelOrder modelOrder: orderArrayList) {
modelOrder.setCounter(0);
}
// Notify RecyclerView about the changes
adapter.notifyDataSetChanged();
epicDialog.dismiss();
}
});
epicDialog.show();
}
I noticed you didn't have the adapter as a global variable so declare it as such:
public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {
// other variables
// Change adapter variable to global
OrderAdapter adapter;
// ...
Side notes: I also noticed that you passed your activity twice inside your OrderAdapter constructor.
OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);
You can simply just do:
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);
Then inside your constructor:
OrderAdapter(Context context, ArrayList<ModelOrder> list) {
mContext = context;
nList = list;
// You can simply cast the context to the listener
listener = (TotalListener) context;
}
Hope my answer helps, happy coding!
Edit: I moved my answers to OP's other questions in the chat.

Related

Can't make the button add a new item on the RecyclerList, only works once

Been working on this code for a while and as im new to recyclerList I can't seem to figure out why the button works only once.
Here is the adapter:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AdaptadorLista extends RecyclerView.Adapter<AdaptadorLista.ViewHolderLista> {
ArrayList<ComponentesLista> listaComponentes;
public AdaptadorLista(ArrayList<ComponentesLista> listaComponentes) {
this.listaComponentes = listaComponentes;
}
#NonNull
#Override
public ViewHolderLista onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_lista, parent, false);
return new ViewHolderLista(view);
}
#Override
public void onBindViewHolder(ViewHolderLista holder, int position) {
holder.textViewDescripcion.setText(String.valueOf(listaComponentes.get(position).getDescripcion()));
holder.textViewDinero.setText(String.valueOf(listaComponentes.get(position).getDinero()));
holder.textViewCantidad.setText(String.valueOf(listaComponentes.get(position).getCantidad()));
}
#Override
public int getItemCount() {
return listaComponentes.size();
}
public class ViewHolderLista extends RecyclerView.ViewHolder {
private TextView textViewCantidad, textViewDescripcion, textViewDinero;
public ViewHolderLista(#NonNull View itemView) {
super(itemView);
textViewCantidad= (TextView) itemView.findViewById(R.id.textMuestraCantidad);
textViewDescripcion = (TextView) itemView.findViewById(R.id.textMuestraDescripcion);
textViewDinero = (TextView) itemView.findViewById(R.id.textMuestraPrecio);
}
}
}
Here is the object it works with:
public class ComponentesLista {
private String descripcion;
private String cantidad;
private String dinero;
public ComponentesLista() {
}
public ComponentesLista(String descripcion, String cantidad, String dinero) {
this.descripcion = descripcion;
this.cantidad = cantidad;
this.dinero = dinero;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getDinero() {
return dinero;
}
public void setDinero(String dinero) {
this.dinero = dinero;
}
}
And here is the main method (It's not the main method, it's another screen I use after a button press but it shouldn't be the issue right?)
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class PantallaLista extends AppCompatActivity {
ArrayList<ComponentesLista> componentesLista;
RecyclerView recyclerLista;
//int cont = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
// Seccion ArrayList Lista
componentesLista=new ArrayList<>();
recyclerLista= (RecyclerView) findViewById(R.id.recyclerViewLista);
recyclerLista.setLayoutManager(new LinearLayoutManager(this));
// Botones
Button nuevo = (Button) findViewById(R.id.nuevoButton);
nuevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
llenarLista();
}
});
Button guardarVolver = (Button) findViewById(R.id.terminarButton);
guardarVolver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PantallaLista.this, MainActivity.class);
startActivity(intent);
}
});
}
private void llenarLista () {
EditText textoGetDescripcion = (EditText) findViewById(R.id.textInputProducto);
EditText textoGetCantidad = (EditText) findViewById(R.id.textInputCantidad);
EditText textoGetPrecio = (EditText) findViewById(R.id.textInputPrecio);
componentesLista.add(new ComponentesLista(textoGetDescripcion.getText().toString(), textoGetPrecio.getText().toString(), textoGetCantidad.getText().toString()));
AdaptadorLista adapter = new AdaptadorLista(componentesLista);
recyclerLista.setAdapter(adapter);
//System.out.println(textoGetDescripcion.getText().toString() + textoGetPrecio.getText().toString() + textoGetPrecio.getText().toString());
}
}
You are setting an adapter every time you add the item to the list. Whenever you are adding a new item to the list, you've to use adapter.notifyItemInserted(position)
Here's the activiy
public class PantallaLista extends AppCompatActivity {
ArrayList<ComponentesLista> componentesLista;
RecyclerView recyclerLista;
AdaptadorLista adapter;
//int cont = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
// Seccion ArrayList Lista
componentesLista=new ArrayList<>();
recyclerLista= (RecyclerView) findViewById(R.id.recyclerViewLista);
recyclerLista.setLayoutManager(new LinearLayoutManager(this));
adapter = new AdaptadorLista(componentesLista);
recyclerLista.setAdapter(adapter);
// Botones
Button nuevo = (Button) findViewById(R.id.nuevoButton);
nuevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
llenarLista();
}
});
Button guardarVolver = (Button) findViewById(R.id.terminarButton);
guardarVolver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(PantallaLista.this, MainActivity.class);
startActivity(intent);
}
});
}
private void llenarLista () {
EditText textoGetDescripcion = (EditText) findViewById(R.id.textInputProducto);
EditText textoGetCantidad = (EditText) findViewById(R.id.textInputCantidad);
EditText textoGetPrecio = (EditText) findViewById(R.id.textInputPrecio);
ComponentesLista tempData = new ComponentesLista(textoGetDescripcion.getText().toString(), textoGetPrecio.getText().toString(), textoGetCantidad.getText().toString())
adapter.addNewItems(tempData);
}
}
heres the adapter
public class AdaptadorLista extends RecyclerView.Adapter<AdaptadorLista.ViewHolderLista> {
ArrayList<ComponentesLista> listaComponentes;
public AdaptadorLista(ArrayList<ComponentesLista> listaComponentes) {
this.listaComponentes = listaComponentes;
}
public addNewItems(ComponentesLista tempComponent){
this.listaComponentes.add(tempComponent);
notifyDataSetChanged();
}
#NonNull
#Override
public ViewHolderLista onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_lista, parent, false);
return new ViewHolderLista(view);
}
#Override
public void onBindViewHolder(ViewHolderLista holder, int position) {
holder.textViewDescripcion.setText(String.valueOf(listaComponentes.get(position).getDescripcion()));
holder.textViewDinero.setText(String.valueOf(listaComponentes.get(position).getDinero()));
holder.textViewCantidad.setText(String.valueOf(listaComponentes.get(position).getCantidad()));
}
#Override
public int getItemCount() {
return listaComponentes.size();
}
public class ViewHolderLista extends RecyclerView.ViewHolder {
private TextView textViewCantidad, textViewDescripcion, textViewDinero;
public ViewHolderLista(#NonNull View itemView) {
super(itemView);
textViewCantidad= (TextView) itemView.findViewById(R.id.textMuestraCantidad);
textViewDescripcion = (TextView) itemView.findViewById(R.id.textMuestraDescripcion);
textViewDinero = (TextView) itemView.findViewById(R.id.textMuestraPrecio);
}
}
}
please tell if you are not understanding something.

CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder' Error

I have a android studio project and use 'com.timehop.stickyheadersrecyclerview:library:0.4.3#aar'
library it works fine but when I create a new project using same code It show me the following error in line 26 StickyRecyclerHeadersAdapter<CustomAdapter.MyHeadingViewHolder> { of CustomAdapter class:
Type parameter 'com.vatexpress.service.CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder'
and also show me following error in line 75 recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(customAdapter));of ManinActivity class:
Type parameter 'com.vatexpress.service.CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder'
Here is my CustomAdapter class:
package com.vatexpress.service;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyChildViewHolder>
implements Filterable,
StickyRecyclerHeadersAdapter<CustomAdapter.MyHeadingViewHolder> {
private Context context;
private Activity activity;
private ArrayList<Model> dataholder;
ArrayList<Model> backup;
MyDatabaseHelper obj = null;
String code, nature, name, sd, vat, vds, vat_ref, vds_ref, about;
public static final int CHILD_LIST = 1;
public static final int HEADER = 2;
CustomAdapter(Activity activity, Context context, ArrayList<Model> dataholder){
this.activity = activity;
this.context = context;
this.dataholder = dataholder;
backup=new ArrayList<>(dataholder);
}
#NonNull
#Override
public MyChildViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyChildViewHolder holder, final int position) {
// if (holder instanceof MyChildViewHolder) {
final Model temp=dataholder.get(position);
holder.service_code.setText(dataholder.get(position).getService_code());
holder.service_name.setText(dataholder.get(position).getService_name());
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, DetailActivity.class);
obj = new MyDatabaseHelper(context);
Cursor cursor = obj.getData(temp.id);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
code = cursor.getString(0);
nature = cursor.getString(2);
name = cursor.getString(1);
sd = cursor.getString(3);
vat = cursor.getString(4);
vds = cursor.getString(5);
vat_ref = cursor.getString(6);
vds_ref = cursor.getString(7);
about = cursor.getString(8);
} while (cursor.moveToNext());
}
}
intent.putExtra("code", code);
intent.putExtra("nature", nature);
intent.putExtra("servicename", name);
intent.putExtra("sd", sd);
intent.putExtra("vat", vat);
intent.putExtra("vds", vds);
intent.putExtra("vat_ref", vat_ref);
intent.putExtra("vds_ref", vds_ref);
intent.putExtra("about", about);
activity.startActivityForResult(intent, 1);
}
});
// }
// else if(holder instanceof MyHeadingViewHolder) {
// MyHeadingViewHolder myHeadingViewHolder = (MyHeadingViewHolder) holder;
// myHeadingViewHolder.heading.setText(dataholder.get(position).service_heading);
// }
}
#Override
public long getHeaderId(int position) {
return dataholder.get(position).getSection();
}
#Override
public MyHeadingViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.heading_layout, parent, false);
return new MyHeadingViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(MyHeadingViewHolder myHeadingViewHolder, int i) {
myHeadingViewHolder.heading.setText(dataholder.get(i).getService_heading());
}
#Override
public int getItemCount() {
return dataholder.size();
}
#Override
public Filter getFilter() {
return filter;
}
Filter filter=new Filter() {
#Override
// background thread
protected FilterResults performFiltering(CharSequence keyword)
{
ArrayList<Model> filtereddata=new ArrayList<>();
if(keyword.toString().isEmpty())
filtereddata.addAll(backup);
else
{
for(Model obj : backup)
{
if(obj.getService_name().toString().toLowerCase().contains(keyword.toString().toLowerCase()))
filtereddata.add(obj);
}
}
FilterResults results=new FilterResults();
results.values=filtereddata;
return results;
}
#Override // main UI thread
protected void publishResults(CharSequence constraint, FilterResults results)
{
dataholder.clear();
dataholder.addAll((ArrayList<Model>)results.values);
notifyDataSetChanged();
}
};
// #Override
// public int getItemViewType(int position) {
// if (dataholder.get(position).typeHeading)
// {
// return HEADER;
// }
// else {
// return CHILD_LIST;
// }
// }
class MyChildViewHolder extends RecyclerView.ViewHolder {
TextView service_code, service_name;
LinearLayout mainLayout;
MyChildViewHolder(#NonNull View itemView) {
super(itemView);
service_code = itemView.findViewById(R.id.service_code);
service_name = itemView.findViewById(R.id.service_name);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
class MyHeadingViewHolder extends RecyclerView.ViewHolder {
TextView heading;
public MyHeadingViewHolder(#NonNull View itemView) {
super(itemView);
heading = itemView.findViewById(R.id.heading_name);
}
}
}
Here is my MainActivity class:
package com.vatexpress.service;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public final class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT =1000 ;
RecyclerView recyclerView;
TextView noSearchResultsFoundText;
EditText editText;
ImageView clearQueryImageView ;
ImageView voiceSearchImageView;
MyDatabaseHelper myDB;
ArrayList<Model> dataholder;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.search_list);
noSearchResultsFoundText = findViewById(R.id.no_search_results_found_text);
myDB = new MyDatabaseHelper(MainActivity.this);
try {
myDB.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDB.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
storeDataInArrays();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customAdapter = new CustomAdapter(MainActivity.this,this, dataholder);
recyclerView.setAdapter(customAdapter);
recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(customAdapter));
editText = (EditText) findViewById(R.id.search_edit_text);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
customAdapter.getFilter().filter(s.toString());
if (editText.getText().toString().isEmpty()){
clearQueryImageView.setVisibility(View.GONE);
voiceSearchImageView.setVisibility(View.VISIBLE);
}else{
clearQueryImageView.setVisibility(View.VISIBLE);
voiceSearchImageView.setVisibility(View.GONE);
}
}
});
voiceSearchImageView = findViewById(R.id.voice_search_query);
//button clic to show speech to text dilog
voiceSearchImageView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
} );
clearQueryImageView = findViewById(R.id.clear_search_query);
clearQueryImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText.setText("");
}
});
}
private void speak() {
//intent is show speech to text dialog
Intent intent= new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH );
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault() );
intent.putExtra( RecognizerIntent.EXTRA_PROMPT, "HI speak something" );
// Start intent
try {
//in there was no errror
//show dilog
startActivityForResult( intent, REQUEST_CODE_SPEECH_INPUT);
}
catch(Exception e){
//show messageof error and show
Toast.makeText( this,""+e.getMessage(), Toast.LENGTH_SHORT ).show();
}
}
//recive voice input and handle it
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult( requestCode, resultCode, data );
switch (requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if(resultCode==RESULT_OK && null!=data){
//get text arry form voice intent
ArrayList<String> result=data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS );
//set to text view
editText.setText( result.get( 0 ) );
}
break;
}
}
}
public void storeDataInArrays(){
dataholder = new ArrayList<>();
String code = "";
boolean firstTime = true;
int section = 0, count = 0;
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
noSearchResultsFoundText.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
if (firstTime) {
code = cursor.getString(1);
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), true, section);
firstTime = false;
dataholder.add(obj);
}
else
{
if (!code.equals(cursor.getString(1))) {
section = count;
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), true, section);
dataholder.add(obj);
code = cursor.getString(1);
}
else
{
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), false, section);
dataholder.add(obj);
}
}
count++;
}
noSearchResultsFoundText.setVisibility(View.GONE);
}
}
}
Please gives me solution how can I solve this!

recycler view does not refresh and show data

in my recycler view , when data get added , recycelr view does not show it until user close the activity and open it another time.
I think it has something to do with notifydataetchanger.
please help me with this
the only thing that worked by now was to creating an Intent .
but it makes app to loob very bad
my adaptor
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Rec_adaptor_aza extends RecyclerView.Adapter<Rec_adaptor_aza.ViewHolder> {
Context context;
public Rec_adaptor_aza(Context context, List<Model_aza> list_aza) {
this.context = context;
this.list_aza = list_aza;
}
List<Model_aza> list_aza;
#NonNull
#Override
public Rec_adaptor_aza.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.rec_row_aza,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Rec_adaptor_aza.ViewHolder holder, int position) {
Model_aza modelAza =list_aza.get(position);
holder.txt_name.setText(modelAza.getName_aza());
holder.txt_semat.setText(modelAza.getSemat_aza());
holder.txt_saat_voood.setText(modelAza.getSaaat_vorood_aza());
holder.txt_saat_khoroo.setText(modelAza.getSaat_khorooj_aza());
}
#Override
public int getItemCount() {
return list_aza.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_name,txt_semat,txt_saat_voood,txt_saat_khoroo;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txt_name=itemView.findViewById(R.id.txt__person__name);
txt_semat=itemView.findViewById(R.id.txt__person__semat);
txt_saat_voood=itemView.findViewById(R.id.txt__person__enter);
txt_saat_khoroo=itemView.findViewById(R.id.txt__person__out);
}
}
}
my model class
package com.example.myapplication;
public class Model_aza {
private String name_aza;
private String semat_aza;
private String saaat_vorood_aza;
public String getName_aza() {
return name_aza;
}
public void setName_aza(String name_aza) {
this.name_aza = name_aza;
}
public String getSemat_aza() {
return semat_aza;
}
public void setSemat_aza(String semat_aza) {
this.semat_aza = semat_aza;
}
public String getSaaat_vorood_aza() {
return saaat_vorood_aza;
}
public void setSaaat_vorood_aza(String saaat_vorood_aza) {
this.saaat_vorood_aza = saaat_vorood_aza;
}
public String getSaat_khorooj_aza() {
return saat_khorooj_aza;
}
public void setSaat_khorooj_aza(String saat_khorooj_aza) {
this.saat_khorooj_aza = saat_khorooj_aza;
}
private String saat_khorooj_aza;
}
My activity
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Activity_Gozaresh_giri extends AppCompatActivity {
private static final String TAG = "gozaresh_activity";
List<Model_aza> list_aza;
Rec_adaptor_aza rec_adaptor_aza;
public static Context context;
SQLiteDatabase sqLiteDatabase;
ImageButton btn__add__field, btn__add__field1;
final DataBase_aza dataBase_aza = new DataBase_aza(this);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
}
my data base
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DataBase_aza extends SQLiteOpenHelper {
public DataBase_aza(#Nullable Context context) {
super(context, "datbase_aza", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table if not exists database_aza (_id integer primary key autoincrement,_name varcher(55) not null,_semat varcher(55) not null, _vorood varcher(6) not null, _khorooj varchar(22) not null, id__item__gozaresh integer(55))");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long insert_info(String name, String semat, String vorood, String khorooj, int id) {
ContentValues cv = new ContentValues();
cv.put("_name", name);
cv.put("_semat", semat);
cv.put("_vorood", vorood);
cv.put("_khorooj", khorooj);
cv.put("id__item__gozaresh", id);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
return sqLiteDatabase.insert("database_aza", null, cv);
}
public Cursor cursor(int id) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery("SELECT * FROM database_aza where id__item__gozaresh="+id, null);
}
}
I want recycler view to show data as soon as user clicks on add button
after adding entry just notify data set changed to adapter like below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
rec_adaptor_aza = new Rec_adaptor_aza(this, list_aza);
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(rec_adaptor_aza);
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
rec_adaptor_aza.notifyDataSetChanged();
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
rec_adaptor_aza.notifyDataSetChanged(); // change here
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
}
Use it like below:-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Rec_adaptor_aza adapter = new Rec_adaptor_aza(this, list_aza); // Add
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(adapter);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Model_aza modelAza = new Model_aza(); // Add
modelAza.setName_aza(name_aza);// Add
modelAza.setSemat_aza(semat_aza);// Add
modelAza.setSaaat_vorood_aza(saat_vorood_aza);// Add
modelAza.setSaat_khorooj_aza(saat_khorooj_aza);// Add
list_aza.add(modelAza);// Add
adapter.notifyDataSetChanged();// Add
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
adapter.notifyDataSetChanged();// Add
}
Just add the below code, in your clickListner, you need to add the same object in your list, and after adding you need to notify the adapter about the inserted item, by using notifyDataSetChanged().
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
/*
* Adding entered data in list*/
Model_aza mm=new Model_aza();
mm.setName_aza(name_aza);
mm.setSemat_aza(semat_aza);
mm.setSaaat_vorood_aza(saat_vorood_aza);
mm.setSaat_khorooj_aza(saat_khorooj_aza);
list_aza.add(mm);
rec_adaptor_aza.notifyDataSetChanged();
}
});
Set layoutmanager before set the adapter to recylerview in your activity, like below
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
// set layout manager before set adapter
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));

How can i show the recycle view data from listview to next intent activity by id in card view this is my code please check and show the result

How can I show the recycle view data from ListView to next intent activity by id in card view this is my code please check and show the result
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.tanuj.recycleview.Product;
import com.example.tanuj.recycleview.R;
import java.util.List;
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private TextView textViewTitle,textViewShortDesc,textViewRating,textViewPrice;
private Context mCtx;
private List<Product> productList;
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.product_list, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
Glide.with(mCtx)
.asBitmap()
.load(product.getImage())
.into(holder.imageView);
holder.textViewTitle.setText(product.getTitle());
holder.textViewShortDesc.setText(product.getShortdesc());
holder.textViewRating.setText(String.valueOf(product.getRating()));
holder.textViewPrice.setText(String.valueOf(product.getPrice()));
holder.textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = "{}";
Intent intent = new Intent(mCtx,GalleryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mCtx.startActivity(intent);
}
});
//Set on click on description
holder.textViewShortDesc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mCtx,"You are click On Description : " +textViewShortDesc,Toast.LENGTH_SHORT).show();
}
});
//Set on click on price
holder.textViewPrice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mCtx,"You are click On Price",Toast.LENGTH_SHORT).show();
}
});
holder.textViewRating.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(mCtx,"You are click on rating",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewShortDesc, textViewRating, textViewPrice;
ImageView imageView;
public ProductViewHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
textViewShortDesc = itemView.findViewById(R.id.textViewShortDesc);
textViewRating = itemView.findViewById(R.id.textViewRating);
textViewPrice = itemView.findViewById(R.id.textViewPrice);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
Please make your product class(or model class) implements Parcelable. Android Studio will provide you implementation of parcelable.
Now you can send any your product object in intent extras like Example

Recyclerview change item color outside adapter

Currently I'm trying figure out how to change an RecyclerView item color outside adapter. I'm just manipulating the position, and works fine! But I must swipe the page to color update, and I don't know what I should do to fix this problem.
Check my code:
MainActivity.java
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
player_prev = findViewById(R.id.prev);
player_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((currentPos-1) > 0) {
killMediaPlayer();
initAudio(getApplicationContext(),
RecyclerViewAdapter.mData.get(currentPos - 1).getURL());
currentPos -= 1;
RecyclerViewAdapter.OldselectedPos = RecyclerViewAdapter.selectedPos;
RecyclerViewAdapter.selectedPos = currentPos;
adapter.notifyDataSetChanged();
}
});
...
}
RecyclerViewAdapter.java
package etes.xdda.music;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
MainActivity activity;
static List<mList> mData;
Dialog myDialog;
public static int selectedPos = RecyclerView.NO_POSITION;
public static int OldselectedPos = RecyclerView.NO_POSITION;
private LinearLayout menu_dialog, menu_dialog2;
public static TextView song_detail;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
#Override
public void onClick(View view) { }
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(activity).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(activity);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
OldselectedPos = selectedPos;
selectedPos = vHolder.getAdapterPosition();
notifyItemChanged(selectedPos);
notifyItemChanged(OldselectedPos);
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
menu_dialog2 = v.getRootView().findViewById(R.id.menu_dialog2);
menu_dialog2.setVisibility(v.VISIBLE);
song_detail = v.getRootView().findViewById(R.id.song_detail);
song_detail.setVisibility(v.VISIBLE);
String newName;
newName = mData.get(vHolder.getAdapterPosition()).getName();
if (newName.length() > 42) {
newName = newName.substring(0, 38) + "...";
}
song_detail.setText(newName);
activity.killMediaPlayer();
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,205);
activity.updateNotificationBar("mzPlay", mData.get(vHolder.getAdapterPosition()).getName());
MainActivity.currentPos = vHolder.getAdapterPosition();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
//Toast.makeText(activity, String.valueOf(holder), Toast.LENGTH_LONG).show();
if(selectedPos == position){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = itemView.findViewById(R.id.name_list);
tv_author = itemView.findViewById(R.id.author_list);
img = itemView.findViewById(R.id.img_music);
}
}
}
Video: https://ntcdn.stream/20181009_2342010.mp4
The problem is: I must swipe the page to item colors be updated, how can I update the colors without page swipe?
Storing andoid classes in static variables is really a very bad practice. You should interact with your adapter the regular way, using a non static field, for example:
//This will go in your onCreate() for example
MyAdapter adapter = new MyAdapter(parameters);
...
adapter.highligtedItemPosition = 10;
adapter.notifyItemChanged(10);
and later in your onBindViewHolder() react according to what background you want set:
if(position == highligtedItemPosition ){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
in this example you must add an integer field:
int highligtedItemPosition;
to your adapter to store the position of the item you want to change the color of.
UPDATE:
You are not calling notifyItemChange() or notifyDataSetChanged() from your activity, so the adapter needs to "wait" for the scrolling action to "see" the changes. You should call notifyItemChange() or notifyDataSetChanged() from your player_prev's OnClickListener instead. So the adapter will reflect the changes immediately.

Categories

Resources