I am working on an Android app.
There is an activity with two independent recyclerviews.
The first one is horizontal and has its own adapter. The second one is vertical and has also its own adapter.
The first time the activity is started, both recyclerviews show all items from their respective sources.
But later I need to filter the items to be shown on the second recycler view depending on the selected item from the first recyclerview.
At the first adapter, when an item is clicked I get the id from it, which I could use to filter the items from the second recyclerview.
Which is the best way to pass the id from the first recyclerview clicked item to the second recyclerview with no need to reload the activity?
Here is the way I am getting the id from the first adapter:
class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
Integer pos;
public MenuClickListener(int pos) {
this.pos = pos;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_favourite:
String positi = marcaList.get(pos).getnombre();
Integer positid = marcaList.get(pos).getId();
return true;
default:
}
return false;
}
}
Both recyclerviews are populated from a remote database.
EDIT
FRAGMENT CODE
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "MainActivity";
private static final String URL_PRODUCTS = "https://.../Api.php";
SwipeRefreshLayout mSwipeRefreshLayout;
//a list to store all the products
List<Marca> marcaList;
//the recyclerview
RecyclerView recyclerView;
RecyclerView recyclerView1;
public List<Dispositivo> dispositivos;
EditText cadenaNf,cadenaCf;
private GridLayoutManager gridLayout;
private DispositivoAdapter adapter;
private Button botonbuscar;
private String cadenaC,cadenaN;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home, container, false);
//getting the recyclerview from xml
recyclerView = v.findViewById(R.id.recyclerMarcas);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
marcaList = new ArrayList<>();
loadProducts();
// SwipeRefreshLayout
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// dispositivos.clear();
// Fetching data from server
// getDispositivosFromDB(0);
}
});
cadenaNf = (EditText) getActivity().findViewById(R.id.cadenaNtxt);
cadenaNf.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ANTES DE ESCRIBIR CADENA N "+ charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ESCRIBIENDO CADENA N "+ charSequence);
if(charSequence.length() >3 ){
dispositivos.clear();
getDispositivosBusquedaFromDB(0, charSequence.toString());
}
if(charSequence.length()== 0 ){
dispositivos.clear();
getDispositivosFromDB(0);
}
Log.d("SEARCH string", "pulsado search submit N FFF CHANGE "+ charSequence);
}
@Override
public void afterTextChanged(Editable editable) {
dispositivos.clear();
Log.d("SEARCH string", "pulsado search submit N FFF "+editable );
Log.d("SEARCH string", "pulsado search ENVIADA CADENA N "+ editable);
}
});
cadenaCf = (EditText) getActivity().findViewById(R.id.cadenaCtxt);
cadenaCf.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ANTES DE ESCRIBIR CADENA C "+ charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("SEARCH string", "pulsado search ESCRIBIENDO CADENA C "+ charSequence);
Log.d("SEARCH string", "pulsado search submit N FFF CHANGE "+ charSequence);
if(charSequence.length() >3 ){
dispositivos.clear();
getDispositivosBusquedaFromDB(0, charSequence.toString());
}
if(charSequence.length()== 0 ){
dispositivos.clear();
getDispositivosFromDB(0);
}
}
@Override
public void afterTextChanged(Editable editable) {
dispositivos.clear();
Log.d("SEARCH string", "pulsado search submit CCC FFF "+editable );
Log.d("SEARCH string", "pulsado search ENVIADA CADENA C "+ editable);
}
});
// getData();
recyclerView1 = (RecyclerView) v.findViewById(R.id.recyclerView1);
dispositivos = new ArrayList<>();
gridLayout = new GridLayoutManager(getActivity(), 2);
recyclerView1.setLayoutManager(gridLayout);
adapter = new DispositivoAdapter(getActivity(), dispositivos);
dispositivos.clear();
recyclerView1.setAdapter(adapter);
getDispositivosFromDB(0);
return v;
}
private void getDispositivosBusquedaFromDB(int id, final String busqueda) {
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA ESTOY BUSCANDO: "+busqueda);
dispositivos.clear();
mSwipeRefreshLayout.setRefreshing(true);
Log.d("estoy en directorio= ",busqueda);
Log.d("Texto buscado= ",busqueda);
AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... addressesIds) {
String URL = "https://._busca.php?id="+busqueda;
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(URL)
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
Log.d("Texto buscado=estoy ",busqueda);
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i < array.length(); i++) {
Log.d("Texto buscado loop= ",busqueda);
JSONObject object = array.getJSONObject(i);
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
Dispositivo dispositivo = new Dispositivo(object.getInt("id_dispositivo"),
object.getString("usuario_dispositivo"),
object.getString("fecha_dispositivo"),
object.getString("precio_dispositivo"),
object.getString("garantia"),
object.getString("estado"),
object.getString("estado_publicacion"),
object.getString("localizacion"),
object.getString("comentarios"),
object.getString("modelo_dispositivo"),
object.getString("foto_dispositivo"),
object.getString("foto2"),
object.getString("foto3"),
object.getString("foto4"),
object.getString("foto5"),
object.getString("hora_dispositivo"),
object.getString("modelo_del_dispositivo"),
object.getString("logo_marca")
);
dispositivos.add(dispositivo);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
recyclerView1.swapAdapter(adapter, true);
mSwipeRefreshLayout.setRefreshing(false);
}
};
asyncTask.execute(id);
}
private void getDispositivosFromDB(int id) {
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA SIN BUSCAR: ");
dispositivos.clear();
mSwipeRefreshLayout.setRefreshing(true);
AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... addressesIds) {
// Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);
//******** HERE I NEED THE ID RECEIVED FROM ADAPTER 1 // String id = (id received from adapter1)
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("...todos.php?id="+id)
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA busqueda: " + i);
Log.d("DISPOSITIVOS", "DISPOSITIVO: " + object);
Dispositivo dispositivo = new Dispositivo(object.getInt("id_dispositivo"),
object.getString("usuario_dispositivo"),
object.getString("fecha_dispositivo"),
object.getString("precio_dispositivo"),
object.getString("garantia"),
object.getString("estado"),
object.getString("estado_publicacion"),
object.getString("localizacion"),
object.getString("comentarios"),
object.getString("modelo_dispositivo"),
object.getString("foto_dispositivo"),
object.getString("foto2"),
object.getString("foto3"),
object.getString("foto4"),
object.getString("foto5"),
object.getString("hora_dispositivo"),
object.getString("modelo_del_dispositivo"),
object.getString("logo_marca")
);
dispositivos.add(dispositivo);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
};
asyncTask.execute(id);
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject marca = array.getJSONObject(i);
//adding the product to product list
marcaList.add(new Marca(
marca.getInt("id"),
marca.getString("nombre"),
marca.getString("icono")
));
}
//creating adapter object and setting it to recyclerview
MarcasAdapter adapter = new MarcasAdapter(getActivity(), marcaList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
@Override
public void onRefresh() {
dispositivos.clear();
getDispositivosFromDB(0);
}
public void onResume(){
super.onResume();
Log.d("HOLA PERFIL", "BUSCANDO ONCREATEA CCAA:ONRESUME ANTES DE CLEAR ");
Log.d("HOLA PERFIL", "BUSCANDO ONCREATEA CCAA:ONRESUME DESPUES DE CLEAR ");
// Set title bar
((MainActivity) getActivity())
.setActionBarTitle("Portada de Jogua");
}
}
ADAPTER 1 CODE MarcasAdapter
public class MarcasAdapter extends RecyclerView.Adapter<MarcasAdapter.ProductViewHolder> {
private Context mCtx;
private List<Marca> marcaList;
private SharedPreferences mPref;
public MarcasAdapter(Context mCtx, List<Marca> marcaList) {
this.mCtx = mCtx;
this.marcaList = marcaList;
}
@Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.marcas_list, null);
return new ProductViewHolder(view);
}
@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Marca marca = marcaList.get(position);
String url = "https://jogua.es/administrar/application/admin/iconos/";
//loading the image
Glide.with(mCtx)
.load(url+marca.geticono())
.into(holder.imageView);
}
@Override
public int getItemCount() {
return marcaList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewTitle;
ImageView imageView;
public ProductViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
showPopupMenu(v, position);
Log.d("HOLA PERFIL", "RESPONSE 2 valor=" + position);
}
private void showPopupMenu(View view, int poaition) {
PopupMenu popup = new PopupMenu(mCtx, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_context_directorio, popup.getMenu());
popup.setOnMenuItemClickListener(new MenuClickListener(poaition));
popup.show();
}
class MenuClickListener implements PopupMenu.OnMenuItemClickListener {
Integer pos;
public MenuClickListener(int pos) {
this.pos = pos;
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_favourite:
String positi = marcaList.get(pos).getnombre();
Integer positid = marcaList.get(pos).getId();
return true;
default:
}
return false;
}
}
}
}
ADAPTER 2 CODE DispositivosAdapter
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.mpidesarrollo.jogua.R;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
public class DispositivoAdapter extends RecyclerView.Adapter<DispositivoAdapter.ViewHolder> {
private Context context;
private List<Dispositivo> dispositivos;
private String emailsegundo;
private SharedPreferences mPref;
private static final String PREF_NAME = "dispositivo";
private static final String BACK_STACK_ROOT_TAG = "detalle_disp";
public DispositivoAdapter(Context context, List<Dispositivo> dispositivos) {
this.context = context;
this.dispositivos = dispositivos;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.dispositivo_card,parent,false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.txtnombre.setText(dispositivos.get(position).getmodelo_del_dispositivo());
String precio = dispositivos.get(position).getprecio_dispositivo().toString();
String newString = precio.replace(".", ",");
holder.txtPrecio.setText(newString+" €");
String url_foto = "https://jogua.es/administrar/application/admin/dispositivos/"+dispositivos.get(position).getfoto_dispositivo();
Glide.with(context).load(url_foto).into(holder.imageView);
String url_logoMarca = "https://jogua.es/administrar/application/admin/iconos/"+dispositivos.get(position).getlogo_marca();
Glide.with(context).load(url_logoMarca).into(holder.logoMarca);
}
@Override
public int getItemCount() {
return dispositivos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView txtnombre,txtPrecio;
public ImageView imageView;
public ImageView logoMarca;
public ViewHolder(View itemView) {
super(itemView);
txtnombre = (TextView) itemView.findViewById(R.id.txtnombre);
txtPrecio = (TextView) itemView.findViewById(R.id.txtprecio);
imageView = (ImageView) itemView.findViewById(R.id.foto);
logoMarca = (ImageView) itemView.findViewById(R.id.logoMarca);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
mPref = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = mPref.edit();
Log.d("DISPOSITIVO", "dispositivo pulsado"+position );
editor.putInt("ID_DISPOSITIVO", dispositivos.get(position).getid_dispositivo());
editor.putString("FOTO_DISPOSITIVO", dispositivos.get(position).getfoto_dispositivo());
editor.putString("FOTO2", dispositivos.get(position).getfoto2());
editor.putString("FOTO3", dispositivos.get(position).getfoto3());
editor.putString("FOTO4", dispositivos.get(position).getfoto4());
editor.putString("FOTO5", dispositivos.get(position).getfoto5());
editor.apply();
DetalleDispositivoFragment firstFragment = new DetalleDispositivoFragment();
((MainActivity)context).getSupportFragmentManager().beginTransaction()
.addToBackStack(BACK_STACK_ROOT_TAG)
.replace(R.id.content_frame, firstFragment).commit();
//showPopupMenu(v,position);
}
}
}