RecyclerView cardview from dialogfragment in fragment page - android

I need to create recyclerview cardview in fragment from the data that is written in a DiagloFragment
What would you do? How can I create a recycler view with the list once I press the button "HECHO"?
IMAGE CAPTURE DATA
Can you explain to me what should I do or even post an example please (done by you or posted somewhere else)?
Beforehand thank you very much.
DialogFragment class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_captura_dialog_act, container, false);
View v = inflater.inflate(R.layout.frag_capactividades, container, false);
Spinner spinnerA;
spinnerA = (Spinner)v.findViewById(R.id.spinnerConf);
bguardar = (Button) v.findViewById(R.id.bGuaradrPaga);
codigo = (EditText) v.findViewById(R.id.tCodData) ;
precio = (EditText) v.findViewById(R.id.tPrecioData);
preciounidadextra = (EditText) v.findViewById(R.id.preciouextra);
cantidadminima = (EditText) v.findViewById(R.id.tCanMinData);
primadominical = (EditText) v.findViewById(R.id.tPrimaData);
final String tipojornada = spinnerA.getSelectedItem().toString();
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
});
return v;
}
}
Card layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txtcodigoMostrar"
android:layout_width="1dp"
android:layout_height="1dp"
android:visibility="invisible" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="16sp"
android:layout_marginTop="16sp"
android:src="#drawable/ajusted" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="10dp"
android:width="2dp"
android:gravity="right"
android:text="Apuntador"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtNombreMostrar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="4dp"
android:text="Nombre"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="10dp"
android:width="2dp"
android:gravity="right"
android:text="Precio"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtPrecioMostrar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="4dp"
android:text="Precio"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/btnEditar"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_width="100dp"
android:layout_height="30dp"
android:text="Editar"
android:textSize="14dp"
android:visibility="invisible" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Fragment class to cretae recyclerview:
public class empleado extends Fragment implements View.OnClickListener {
FloatingActionButton btndialog;
private SQLiteDatabase db;
RecyclerView idrecyclerview, recyclerView;
static List<ActividadesModel> listCont;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v5 = inflater.inflate(R.layout.activity_empleado, container, false);
RecyclerView recyclerView = v5.findViewById(R.id.idrecyclerviewCa);
//recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(viewAdapter);
return v5;
}
public empleado(String codigo,String precio,String preciounidadextra,String cantidadminima,String primadominical,String tipojornada){
}
public static void guardaempleado(String codigo, String precio, String preciounidadextra, String cantidadminima, String primadominical, String tipojornada){
listCont = new ArrayList<>();
listCont.add(new ActividadesModel("codigo", "precio", "preciounidadextra", "cantidadminima", "primadominical", "tipojornada"));
}
private void ShowMessage() {
final String[] actividades = {"act1", "act2", "act3", "act4", "act5"};
final int itemSelected = 0;
new AlertDialog.Builder(getContext())
.setTitle("Selecciona la actividad")
.setSingleChoiceItems(actividades, itemSelected, new DialogInterface.OnClickListener() {
#Override
// public void onClick(DialogInterface dialogInterface, int selectedIndex) {
public void onClick(DialogInterface dialog, int position) {
// String nombreselect = empleados[position];
Toast.makeText(getContext(), "Position: " + position, Toast.LENGTH_SHORT).show();
String nombreselect = actividades[position];
SharedPreferences sharedPrefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("actividad", nombreselect);
editor.commit();
// empleado.setText(empleadotext);
}
})
// .setNeutralButton("OK", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment dialogs = new CapturaDialogAct(); // creating new object
dialogs.show(fm, "dialog");
}
})
.show();
}
CaptureDialog class:
public class CapturaDialogAct extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
TextView textView;
Button bguardar;
EditText codigo,precio,preciounidadextra, cantidadminima,primadominical;
Adapter rvAdapter;
RecyclerView recyclerView;
private static RecyclerView.Adapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_captura_dialog_act, container, false);
View v = inflater.inflate(R.layout.frag_capactividades, container, false);
Spinner spinnerA;
spinnerA = (Spinner)v.findViewById(R.id.spinnerConf);
bguardar = (Button) v.findViewById(R.id.bGuaradrPaga);
codigo = (EditText) v.findViewById(R.id.tCodData) ;
precio = (EditText) v.findViewById(R.id.tPrecioData);
preciounidadextra = (EditText) v.findViewById(R.id.preciouextra);
cantidadminima = (EditText) v.findViewById(R.id.tCanMinData);
primadominical = (EditText) v.findViewById(R.id.tPrimaData);
final String tipojornada = spinnerA.getSelectedItem().toString();
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
});
return v;
}
}
Model:
public class ActividadesModel implements Serializable {
private String codigo ,precio, preciounidadextra, cantidadminima, primadominical, tipojordana;
public ActividadesModel( String precio, String preciounidadextra, String cantidadminima, String primadominical, String codigo, String tipojordana){
this.codigo = codigo;
}
public String getCodigo()
{
return codigo;
}
public void setCodigo(String codigo){
this.codigo = codigo;
}
public String getPrecio(){
return precio;
}
public void setPrecio(){
this.precio = precio;
}
public String getPreciounidadextra(){
return preciounidadextra;
}
public void setPreciounidadextra(){
this.preciounidadextra = preciounidadextra;
}
public String getCantidadminima(){
return cantidadminima;
}
public void setCantidadminima(){
this.cantidadminima = cantidadminima;
}
public String getPrimadominical(){
return primadominical;
}
public void setPrimadominical(){
this.primadominical = primadominical;
}
public String getTipojordana(){
return tipojordana;
}
public void setTipojordana(){
this.tipojordana = tipojordana;
}
}
Add ADapter:
public class AdapterAct extends RecyclerView.Adapter<AdapterAct.MyViewHolder> implements Filterable {
private List<ActividadesModel> actividadesModelList = new ArrayList<>();
private Context context;
private List<ActividadesModel> actividadesArrayList;
private IAxiliarActividades iAxiliarActividades;
List<ActividadesModel> contactList;
public AdapterAct(Context context, List<ActividadesModel> listCont) {
this.context = context;
this.contactList = contactList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// return null;
View v;
v = LayoutInflater.from(context).inflate(R.layout.card_actividad, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(v);
return myViewHolder;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView precio;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.txtNombreMostrar);
precio = (TextView) itemView.findViewById(R.id.txtPrecioMostrar);
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
//Codigo para crear el listado de acitividades
}
#Override
public int getItemCount() {
return 0;
}
#Override
public Filter getFilter() {
return null;
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView nombre, precio;
public myViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}

Please follow below steps to create interface listener for the the DialogFragment input to be returned to your fragment.
Step 1: Create an interface inside the CapturaDialogAct
DialogFragment, and an instance field of it:
Step 2: Modify the CapturaDialogAct to accept an argument of this
interface
Step 3: Trigger the interface method whenever you click the
DialogFragment button.
class CapturaDialogAct extends DialogFragment {
...
// Step 1
public interface OnSelectionListener {
void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada);
}
private OnSelectionListener mOnSelectionListener;
// Step 2
public CapturaDialogAct(OnSelectionListener listener) {
this.mOnSelectionListener = listener;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_captura_dialog_act, container, false);
View v = inflater.inflate(R.layout.frag_capactividades, container, false);
//..... reset of code
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
// Step 3
if (mOnSelectionListener != null) {
mOnSelectionListener.onConfirmed(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
}
});
}
}
Step 4: at your fragment, change the instantiation of the DialogFragment to implement the interface and handle the returned text with its callback
Replace
DialogFragment dialogs = new CapturaDialogAct(); // creating new object
With
// Step 4
DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
});
UPDATE
It already performs all the steps, it does not mark an error but it does not create the cardview, I will add the adapter to the post
In Step 4 change the list of the RecyclerView adapter, and update the UI.
DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
listCont = new ArrayList<>();
listCont.add(new ActividadesModel(codigo, precio, preciounidadextra, cantidadminima, primadominical, tipojornada));
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
RecyclerView recyclerView = getView().findViewById(R.id.idrecyclerviewCa);
//recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(viewAdapter);
});
Edit
You get an error as you define the RecyclerView as a local variable to onCreateView, so you need to select the class RecyclerView field instead.
So, the change
public class empleado extends Fragment implements View.OnClickListener {
RecyclerView idrecyclerview, recyclerView; // this is the field class variable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v5 = inflater.inflate(R.layout.activity_empleado, container, false);
recyclerView = v5.findViewById(R.id.idrecyclerviewCa); // here is the change
Then, added dismiss() when you hit the dialog hide in order to hide it.
So, in your dialog fragment add dismiss() as below
bguardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Code create recyclerview
empleado.guardaempleado(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
// Step 3
if (mOnSelectionListener != null) {
mOnSelectionListener.onConfirmed(codigo.getText().toString(), precio.getText().toString(), preciounidadextra.getText().toString(), cantidadminima.getText().toString()
, primadominical.getText().toString(), tipojornada);
}
dismiss(); /// <<<<< here is the change
}
});
Also made the adapter as a fragment class field in order to use it when you dismiss the dialog so created AdapterAct mViewAdapter in empleado fragment
Here is the your entire fragment after this modificaiton
public class empleado extends Fragment implements View.OnClickListener {
//private static ArrayList<Object> listCont;
FloatingActionButton btndialog;
// public static TextView empleado;
private SQLiteDatabase db;
RecyclerView idrecyclerview, recyclerView;
static List<ActividadesModel> listCont;
private AdapterAct mViewAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v5 = inflater.inflate(R.layout.activity_empleado, container, false);
recyclerView = v5.findViewById(R.id.idrecyclerviewCa);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
listCont = new ArrayList<>();
mViewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mViewAdapter);
return v5;
}
//public empleado(String codigo,String precio,String preciounidadextra,String cantidadminima,String primadominical,String tipojornada){
public empleado() {
// listCont = new ArrayList<>();
// listCont.add(new ActividadesModel("precio", "preciounidadextra", "cantidadminima", "primadominical", "codigo", "tipojornada"));
}
public static void guardaempleado(String codigo, String precio, String preciounidadextra, String cantidadminima, String primadominical, String tipojornada) {
listCont = new ArrayList<>();
listCont.add(new ActividadesModel(precio, preciounidadextra, cantidadminima, primadominical, codigo, tipojornada));
// new empleado();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//inflate menu
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle menu item clicks
int id = item.getItemId();
if (id == R.id.action_settings) {
//do your function here
Toast.makeText(getActivity(), "Sincronizar", Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_sort) {
//do your function here
Toast.makeText(getActivity(), "Buscar", Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_hoy) {
//do your function here
Toast.makeText(getActivity(), "Hoy", Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_anterior) {
//do your function here
Toast.makeText(getActivity(), "Ayer", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
private static String PREF_NAME = "prefs";
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
private Context mContext;
#Override
public void onViewCreated(View v5, Bundle savedInstanceState) {
//public void onClick(View v5) {
FloatingActionButton btndialog = (FloatingActionButton) v5.findViewById(R.id.floatingActionButton);
final String[] nivelItems = getResources().getStringArray(R.array.nivel);
final int itemSelected = 0;
try {
btndialog.setOnClickListener(new View.OnClickListener() {
// JSONObject js = createJsonObjectInv();
// JSONArray arr = js.getJSONArray("data");
//JSONArray arr3 = js.getJSONArray("data");
//String[] list = new String[arr.length()];
//String[] arr2 = arr.toString().replace("},{", " ,").split(" ");
//#Override
public void onClick(View v) {
try {
JSONObject js = createJsonObjectInv();
JSONArray arr = js.getJSONArray("data");
final String[] list = new String[arr.length()];
for (int i = 0; i <= arr.length() - 1; i++) {
JSONObject element = arr.getJSONObject(i);
String InvernaderoId = "\"invernaderoId\":\"" + element.getString("invernaderoId") + "\", ";
String Name = "\"name\":\"" + element.getString("name") + "\", ";
String Invernarder = "\"Invernarder\":\"" + element.getString("Invernarder") + "\"";
//list[i] = InvernaderoId + Name + Invernarder;
list[i] = Name.substring(8);
}
// final String[] empleados = {"Luis", "Daniel", "Juan", "Jose", "Cesar"};
// final String[] empleados = arr2;
new AlertDialog.Builder(getContext())
.setTitle("Selecciona el Invernadero")
// .setSingleChoiceItems(empleados, itemSelected, new DialogInterface.OnClickListener() {
.setSingleChoiceItems(list, -1, new DialogInterface.OnClickListener() {
#Override
// public void onClick(DialogInterface dialogInterface, int selectedIndex) {
public void onClick(DialogInterface dialog, int position) {
// String nombreselect = empleados[position];
Toast.makeText(getContext(), "Position: " + position, Toast.LENGTH_SHORT).show();
String empleadotext = list[position];
//empleado.setText(empleadotext);
// SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPrefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("inver", empleadotext);
editor.commit();
}
})
//.setPositiveButton("Ok", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ShowMessage();
}
})
.setNegativeButton("Cancel", null)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void ShowMessage() {
final String[] actividades = {"act1", "act2", "act3", "act4", "act5"};
final int itemSelected = 0;
new AlertDialog.Builder(getContext())
.setTitle("Selecciona la actividad")
.setSingleChoiceItems(actividades, itemSelected, new DialogInterface.OnClickListener() {
#Override
// public void onClick(DialogInterface dialogInterface, int selectedIndex) {
public void onClick(DialogInterface dialog, int position) {
// String nombreselect = empleados[position];
Toast.makeText(getContext(), "Position: " + position, Toast.LENGTH_SHORT).show();
String nombreselect = actividades[position];
SharedPreferences sharedPrefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("actividad", nombreselect);
editor.commit();
// empleado.setText(empleadotext);
}
})
// .setNeutralButton("OK", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
/* FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment dialogs = new CapturaDialogAct(); // creating new object
dialogs.show(fm, "dialog");
*/
FragmentManager fm = getActivity().getSupportFragmentManager();
/* DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
}
});*/
DialogFragment dialogs = new CapturaDialogAct(new CapturaDialogAct.OnSelectionListener() {
#Override
public void onConfirmed(String codigo, String precio, String preciounidadextra, String cantidadminima
, String primadominical, String tipojornada) {
// Do whatever you want with the received text from the DialogFragment
/*
AdapterAct viewAdapter = new AdapterAct(getContext(), listCont);
recyclerView.setAdapter(viewAdapter);
*/
// RecyclerView recyclerView = getView().findViewById(R.id.idrecyclerviewCa);
//recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
mViewAdapter.addItem(new ActividadesModel(codigo, precio, preciounidadextra, cantidadminima, primadominical, tipojornada));
}
});
dialogs.show(fm, "dialog");
}
})
.show();
}
public JSONObject createJsonObjectInv() throws JSONException {
Cursor cursor = getAllDataInv();
JSONObject jobj;
JSONArray arr = new JSONArray();
cursor.moveToFirst();
while (cursor.moveToNext()) {
jobj = new JSONObject();
jobj.put("invernaderoId", cursor.getString(0));
jobj.put("name", cursor.getString(1));
jobj.put("Invernarder", cursor.getString(4));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
return jobj;
}
//Syncronizador de datos a servicio
public Cursor getAllDataInv() {
String selectQuery = "Select * from Invernadero";
SQLiteDatabase db = new MyHelper(getActivity()).getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Cursor cursor = db.rawQuery("select * from capturas where syncstatus= ?", new String[] {"0"});
return cursor;
}
#Override
public void onClick(View v) {
}
}
And for your adapter, added a new method called addItem that accepts a new row in the adapter and notifiy change in last item.
public class AdapterAct extends RecyclerView.Adapter<AdapterAct.MyViewHolder> implements Filterable {
private List<ActividadesModel> actividadesModelList;
private Context context;
private List<ActividadesModel> actividadesArrayList;
private IAxiliarActividades iAxiliarActividades;
List<ActividadesModel> contactList;
// Este es nuestro constructor (puede variar según lo que queremos mostrar)
private String[] mDataSet;
private List<ActividadesModel> listCont;
public AdapterAct(Context context, List<ActividadesModel> listCont) {
this.context = context;
this.contactList = listCont;
this.listCont = listCont;
}
public AdapterAct(String[] myDataSet) {
mDataSet = myDataSet;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// return null;
View v;
v = LayoutInflater.from(context).inflate(R.layout.card_actividad, parent, false);
return new MyViewHolder(v);
}
public void addItem(ActividadesModel item) {
this.listCont.add(item);
notifyItemChanged(listCont.size() - 1);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView precio;
public MyViewHolder(View itemView) {
super(itemView);
this.name = (TextView) itemView.findViewById(R.id.txtNombreMostrar);
this.precio = (TextView) itemView.findViewById(R.id.txtPrecioMostrar);
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
ActividadesModel actividadesModel = listCont.get(position);
//Codigo para crear el listado de acitividades
// holder.name.setText("nameprueba");
holder.precio.setText(actividadesModel.getCodigo());
holder.precio.setText(actividadesModel.getPrecio());
// holder.precio.setText("precio23");
}
#Override
public int getItemCount() {
return listCont == null ? 0 : listCont.size();
}
#Override
public Filter getFilter() {
return null;
}
}

Related

RecyclerView, each items has its own activity

I have a RecyclerView, it has items in it. I need each item to have its own Activity, that is, we have item1 by clicking on it, Activity1 opens, there is also item2 about clicking on it, Activity2 is opened. Can this be done somehow? If so, how? I managed to make it so that when I clicked, the same Fragment opened, and the text changes depending on which item was clicked. But it doesn't quite suit me.
Fragment where the RecyclerView is located
public class FragmentAttractionRecyclerView extends Fragment {
private RecyclerView mRec;
private AttractionsAdapter adapter;
private ArrayList<AttractionsItem> exampleList;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
}
#SuppressLint("InflateParams")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
createExampleList();
buildRecyclerView();
}
public void createExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽","Максимальное кол-во детей","10","Возраст","С 1-го до 6 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽","Максимальное кол-во пассажиров","24", "Возраст","От 4-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽","Максимальное кол-во пассажиров","12","Возраст","От 3-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽","Максимальное кол-во пассажиров","","Возраст","С 6 лет"));
}
public void buildRecyclerView() {
mRec = requireView().findViewById(R.id.attraction_recycler);
adapter = new AttractionsAdapter(exampleList);
mLayoutManager = new LinearLayoutManager(getContext());
mRec.setLayoutManager(mLayoutManager);
mRec.setAdapter(adapter);
}
}
Adapter for RecyclerView
public class AttractionsAdapter extends RecyclerView.Adapter<AttractionsAdapter.AttractionsViewHolder> {
public ArrayList<AttractionsItem> mFavList;
public AttractionsAdapter(ArrayList<AttractionsItem> favList) {
mFavList = favList;
}
#NonNull
#Override
public AttractionsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_attraction, parent, false);
AttractionsViewHolder evh = new AttractionsViewHolder(v);
return evh;
}
public static class AttractionsViewHolder extends RecyclerView.ViewHolder {
public ImageView card_image_1, card_image_2;
public TextView card_text_1, card_text_2, card_text_3,attraction_menu_1_1,attraction_menu_1_2;
public CardView Card;
public AttractionsViewHolder(View itemView) {
super(itemView);
card_image_1 = itemView.findViewById(R.id.card_image_1);
card_image_2 = itemView.findViewById(R.id.card_image_2);
card_text_1 = itemView.findViewById(R.id.card_text_1);
card_text_2 = itemView.findViewById(R.id.card_text_2);
card_text_3 = itemView.findViewById(R.id.card_text_3);
attraction_menu_1_1 = itemView.findViewById(R.id.attraction_menu_1_1);
attraction_menu_1_2 = itemView.findViewById(R.id.attraction_menu_1_2);
Card = itemView.findViewById(R.id.Card);
}
}
#Override
public void onBindViewHolder(AttractionsViewHolder holder, int position) {
AttractionsItem currentItem = mFavList.get(position);
holder.card_image_1.setImageResource(currentItem.getImg1());
holder.card_image_2.setImageResource(currentItem.getImg2());
holder.card_text_1.setText(currentItem.get_attraction_name());
holder.card_text_2.setText(currentItem.get_attraction_type());
holder.card_text_3.setText(currentItem.get_attraction_cost());
holder.Card.setOnClickListener(v -> {
FragmentBlancAttraction fragment = new FragmentBlancAttraction(); // you fragment
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
Bundle bundle = new Bundle();
bundle.putString("name", currentItem.get_attraction_name());
bundle.putString("menu_1_1", currentItem.get_attraction_menu_1_1());
bundle.putString("menu_1_2", currentItem.get_attraction_menu_1_2());
bundle.putString("menu_2_1", currentItem.get_attraction_menu_2_1());
bundle.putString("menu_2_2", currentItem.get_attraction_menu_2_2());
fragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.nav_default_enter_anim, R.animator.nav_default_exit_anim,
R.animator.nav_default_pop_enter_anim, R.animator.nav_default_pop_exit_anim);
fragmentTransaction.replace(R.id.fragment, fragment);// your container and your fragment
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
});
}
#Override
public int getItemCount() {
return mFavList.size();
}
}
public class AttractionsItem
{
private int mImg_1,mImg_2;
private final String mText_attraction_name;
private final String mText_attraction_type;
private final String mText_attraction_cost;
private final String mText_attraction_menu_1_1;
private final String mText_attraction_menu_1_2;
private final String mText_attraction_menu_2_1;
private final String mText_attraction_menu_2_2;
public AttractionsItem(int img1,int img2, String text_attraction_name, String text_attraction_type, String text_attraction_cost, String text_attraction_menu_1_1, String text_attraction_menu_1_2, String text_attraction_menu_2_1, String text_attraction_menu_2_2)
{
mImg_1 = img1;
mImg_2 = img2;
mText_attraction_name = text_attraction_name;
mText_attraction_type = text_attraction_type;
mText_attraction_cost = text_attraction_cost;
mText_attraction_menu_1_1 = text_attraction_menu_1_1;
mText_attraction_menu_1_2 = text_attraction_menu_1_2;
mText_attraction_menu_2_1 = text_attraction_menu_2_1;
mText_attraction_menu_2_2 = text_attraction_menu_2_2;
}
public int getImg1()
{
return mImg_1;
}
public int getImg2()
{
return mImg_2;
}
public String get_attraction_name()
{
return mText_attraction_name;
}
public String get_attraction_type()
{
return mText_attraction_type;
}
public String get_attraction_cost()
{
return mText_attraction_cost;
}
public String get_attraction_menu_1_1()
{
return mText_attraction_menu_1_1;
}
public String get_attraction_menu_1_2()
{
return mText_attraction_menu_1_2;
}
public String get_attraction_menu_2_1()
{
return mText_attraction_menu_2_1;
}
public String get_attraction_menu_2_2()
{
return mText_attraction_menu_2_2;
}
}
The positon param inside onBindViewHolder() method tells you which item of your RecyclerView clicked.
Use this to control your program and in out of onBindViewHolder() method you can get your item position by getAdapterPosition().
holder.Card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: {
// Start first activity.
break;
}
case 1: {
// Start Second activity.
break;
}
}
}
});

RecyclerView filled with Objects from SharedPreferences is slow and laggy

I am building an app which has a RecyclerView which holds Objects that are retrieved from SharedPreferences.
Unfortunately the RecyclerView is lagging when it is binded.
This is my Adapter
public class ShiftAdapter extends RecyclerView.Adapter<ShiftAdapter.ViewHolder>{
private List<Shift> mDataSet;
private Context mContext;
private static final String TAG = "ShiftAdapter";
public int previousExpandedPosition = -1;
public int mExpandedPosition = -1;
private static SharedPreferences mPrefs;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Boolean isStart;
private Date shiftIn;
private Date shiftOut;
private Date mDate;
public EditText mshiftInText;
public EditText mshiftOutText;
public Date date;
public ShiftAdapter(Context context, List<Shift> list) {
mDataSet = list;
mContext = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mDate;
public TextView mTime;
public TextView mPay;
public RelativeLayout mRelativeLayout;
public LinearLayout mExepandableLayout;
public Date mshiftIn;
public Date mshiftOut;
public EditText mshiftInText;
public EditText mshiftOutText;
public Button mUpdateButton;
public Button mDeleteButton;
public ViewHolder(View v) {
super(v);
mDate = (TextView) v.findViewById(R.id.date_TV);
mTime = (TextView) v.findViewById(R.id.time_TV);
mPay = (TextView) v.findViewById(R.id.pay_TV);
mRelativeLayout = (RelativeLayout) v.findViewById(R.id.rel_layout);
mExepandableLayout = (LinearLayout) v.findViewById(R.id.expandableLayout);
mshiftInText = (EditText) v.findViewById(R.id.setShiftIn);
mshiftOutText = (EditText) v.findViewById(R.id.setShiftOut);
mUpdateButton = (Button) v.findViewById(R.id.updateButton);
mDeleteButton = (Button) v.findViewById(R.id.deleteButton);
}
}
#Override
public ShiftAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.shift, parent, false);
ViewHolder vh = new ViewHolder(itemView);
return vh;
}
//TODO:Bind all the view elements to Shift Properties
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
// Format double
String hours = new DecimalFormat("##.##").format(mDataSet.get(i).getHours());
String pay = new DecimalFormat("##.##").format(mDataSet.get(i).getPay());
//set the Text
holder.mTime.setText(hours);
holder.mDate.setText(mDataSet.get(i).dateToString());
holder.mPay.setText(pay);
Log.d(TAG, "onBindViewHolder: called");
// new AsyncTask<>().ex
//Expand mExapndableLayout
final int position = i;
final boolean isExpanded = position ==mExpandedPosition;
holder.mExepandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
// //set shift Times
// shiftIn = mDataSet.get(position).getInDate();
// shiftOut = mDataSet.get(position).getInDate();
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
//fill expandable layout
holder.mshiftInText.setText(mDataSet.get(position).fullTimeToString(0));
final EditText in = holder.mshiftInText;
final EditText out = holder.mshiftOutText;
//edit mShiftIn Text
holder.mshiftInText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =true;
timePickerDialog(in,out);
}
});
holder.mshiftOutText.setText(mDataSet.get(position).fullTimeToString(1));
//edit MshiftOut Text
holder.mshiftOutText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =false;
timePickerDialog(in,out);
}
});
//updateButton onClick
holder.mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
shiftIn = mDataSet.get(position).getInDate();
shiftOut = mDataSet.get(position).getOutDate();
if(Validate.getValidate().isDateValid(shiftIn,shiftOut)) {
SharedPrefs.getInstance(mContext).editShift(newShift(shiftIn, shiftOut),Integer.toString(position));
int length = SharedPrefs.getInstance(mContext).getLength() - 1;
if (SharedPrefs.getInstance(mContext).getShift(length) != null) {
Log.d(TAG, "Edit Shift onClick: Success");
SharedPrefs.getInstance(mContext).saveShiftList(SharedPrefs.getInstance(mContext).sortList(SharedPrefs.getInstance(mContext).getShiftList()));
ShiftsFragment.updateUI();
Toast.makeText(mContext, "success", Toast.LENGTH_SHORT).show();
}
} else {
mShiftOut.setBackgroundResource(R.drawable.red_border);
Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show(); }
} catch(Exception e){
Log.d(TAG, "onDateSelected: "+e.toString());
Toast.makeText(mContext,"update FAIL", Toast.LENGTH_SHORT).show();
}
// update the Shift
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
areYouSure(mExpandedPosition);
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public Date timePickerDialog(EditText in,EditText out) {
mshiftInText = in;
mshiftOutText = out;
new SingleDateAndTimePickerDialog.Builder(mContext)
.title(mContext.getResources().getString(R.string.choose_time))
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
#Override
public void onDisplayed(SingleDateAndTimePicker picker) {
if(!isStart) {
date = mDate;
}
}
}).defaultDate(returnDate(date))
.listener(new SingleDateAndTimePickerDialog.Listener() {
#Override
public void onDateSelected(Date date) {
mDate = date;
if (isStart) {
updateShiftIn(mDate);
mshiftInText.setText(dateToString(mDate));
} else {
updateShiftOut(mDate);
mshiftOutText.setText(dateToString(mDate));
}
}
}).display();
return mDate;
}
public String dateToString(Date date)
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String string = df.format(date);
return string;
}
private void updateShiftIn(Date date) {
shiftIn = date;
}
private void updateShiftOut(Date date) {
shiftOut = date;
}
private Date returnDate(Date date)
{
if(date!=null)
{
return date;
}
else return mDate;
}
private void areYouSure(int i)
{
final String position = Integer.toString(i);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Log.d(TAG, "onClick: isSure=true;");
SharedPrefs.getInstance(mContext).removeShift(position);
ShiftsFragment.updateUI();
case DialogInterface.BUTTON_NEGATIVE:
Log.d(TAG, "onClick: isSure= false");
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(mContext.getResources().getString(R.string.are_you_sure)).setPositiveButton(mContext.getResources().getString(R.string.confirm), dialogClickListener)
.setNegativeButton(mContext.getResources().getString(R.string.cancel), dialogClickListener).show();
}
private Shift newShift(Date start,Date stop)
{
int id = SharedPrefs.getInstance(mContext).getLength();
Shift shift = new Shift(dateToCalendar(start),dateToCalendar(stop),id);
return shift;
}
and this is the Fragment that has the RecyclerView
public class ShiftsFragment extends Fragment {
private Toolbar mToolbar;
private TimePicker timePicker1;
private List<Shift> shiftList = new ArrayList<>();
private RecyclerView recyclerView;
private RelativeLayout relativeLayout;
private RecyclerView.LayoutManager layoutManager;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Context mContext;
private ShiftAdapter mAdapter;
private MenuItem mAdd;
private Menu optionsMenu;
private LinearLayout mShiftAddLL;
private SharedPreferences mPrefs;
private static FragmentManager mFragmentManager;
private static final String TAG = "ShiftsFragment";
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG,"Clicked");
final View view = inflater.inflate(R.layout.shifts_layout,container,false);
mToolbar = view.findViewById(R.id.topbar);
mToolbar.inflateMenu(R.menu.toolbarmenu);
mShiftAddLL = view.findViewById(R.id.add_shiftLayout);
mAdd = mToolbar.getMenu().getItem(0);
timePicker1 = (TimePicker) view.findViewById(R.id.timePicker);
mFragmentManager = getFragmentManager();
//TODO:Add a summary bar on the bottom.
//get the context
mContext = getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.shift_list);
// Define a layout for RecyclerView
layoutManager = new GridLayoutManager(mContext,1);
recyclerView.setLayoutManager(layoutManager);
// Initialize a new Shift array
List<Shift> shiftList = initShifts();
Log.d(TAG,"shift array initiated");
// Initialize an array list from array
// Initialize a new instance of RecyclerView Adapter instance
mAdapter = new ShiftAdapter(mContext,shiftList);
// Set the adapter for RecyclerView
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
//Menu add button onClick
//Opens Add_Shift_Fragment
mAdd.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Fragment selectedFragment = new Add_Shift_Fragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return false;
}
});
return view;
}
//Initializes the Shift list from SharedPreferences and returns it.
private List<Shift> initShifts() {
return SharedPrefs.getInstance(mContext).getShiftList();
}
public static void updateUI()
{
Fragment selectedFragment = new ShiftsFragment();
mFragmentManager.beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
}
Everytime i launch the ShiftsFragment there are some frame skips, and the scrolling is choppy and laggy.
Maybe my SharedPreferences handling is what is slowing things down?
public class SharedPrefs {
private static SharedPrefs mSharedPrefs;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
protected Context mContext;
public static final String ID = "shiftList";
private SharedPrefs(Context context) {
mContext = context;
mPrefs = context.getSharedPreferences(ID, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
}
public static SharedPrefs getInstance(Context context) {
if (mSharedPrefs == null) {
mSharedPrefs = new SharedPrefs(context.getApplicationContext());
}
return mSharedPrefs;
}
public void saveShiftList(List<Shift> shiftList) {
Gson gson = new Gson();
String json = gson.toJson(shiftList);
mPrefsEditor.putString(ID, json);
mPrefsEditor.apply();
}
public void addShift (Shift shift)
{
List<Shift> shiftList= getShiftList();
shiftList.add(shift);
saveShiftList(shiftList);
}
//Replaced the shift#id with shift
public void editShift(Shift shift,String id)
{
removeShift(id);
addShift(shift);
}
public void removeShift(String id) {
List<Shift> shiftList = getShiftList();
int pos = Integer.parseInt(id);
shiftList.remove(pos);
saveShiftList(shiftList);
}
public void removeShift(int id) {
List<Shift> shiftList = getShiftList();
shiftList.remove(id);
saveShiftList(shiftList);
}
public Shift getShift(int id) {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
Shift shift = shiftList.get(id);
return shift;
}
public List<Shift> getShiftList() {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
if (shiftList!=null) {
return shiftList;
} else{
shiftList = new ArrayList<>();
return shiftList;
}
}
public List<Shift> sortList(List<Shift> shiftList)
{
Collections.sort(shiftList, new Comparator<Shift>() {
public int compare(Shift shift1, Shift shift2) {
if (shift1.getShiftStart() == null || shift2.getShiftStart() == null)
return 0;
return shift1.getShiftStart().compareTo(shift2.getShiftStart());
}
});
return shiftList;
}
public int getLength()
{
return getShiftList().size();
}
}
I have only found this problem with image loading, not just Strings from Object from SharedPrefs.

RecyclerView notifyDatasetChanged not working

I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.

Change the Icon of a Button in a Recycler View in Adapter Class Based off boolean value

I'm trying to change the icon of a button in my recycler view every time the activity starts based off a boolean value in my custom object. I assume this has to be done within the adapter since not every groups button will have the same background.
Below is the code for my recycler view adapter:
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mRecipeTextSection.setOnClickListener(this);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
Toast.makeText(v.getContext(), recipeToGrocery.getRecipeName() + " added to grocery list.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v){
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}
I know how to change the background of the button when it's clicked with
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
but it's obviously not going to save the state of that button when the activity restarts. I'm just not sure of how to check the boolean value for each group upon activity start up and change the button background accordingly.
I tried using
if(recipe.isInList()){
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
in the onBindViewHolder method but it didn't do anything, and I'm pretty sure that wouldn't be the correct place for it anyways. I know the boolean is working properly since I use it in other places and it works fine.
Here's the relevant XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/android"
android:layout_margin="7dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:id="#+id/recycled_item_section_view"
android:elevation="30dp"
android:background="#drawable/background_border"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Recipe name"
android:textSize="24dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_recipe_name"
android:paddingBottom="3dp"
android:maxWidth="275dip"
android:singleLine="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_below="#id/recipe_list_recycler_view_recipe_name"
android:id="#+id/recipe_list_recycler_view_serving_size"
android:paddingBottom="3dp"/>
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#mipmap/ic_playlist_add_black_24dp"
android:height="36dp"
android:padding="8dp"
android:layout_alignParentRight="true"
android:id="#+id/add_to_grocery_list"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_serving_size"
android:layout_alignParentLeft="true"
android:textSize="18dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_prep_time"
android:paddingBottom="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_prep_time"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:id="#+id/recipe_list_recycler_view_cook_time"/>
</RelativeLayout>
Recipe class:
public class Recipe implements Parcelable {
//These are all of the qualities a recipe contains, we will create an arraylist of this in the activity
private String mRecipeName;
private int mID;
private String mServings;
private String mPrepTime;
private String mCookTime;
private boolean isInList;
private List<String> mIngredients;
private List<String> mDirections;
public Recipe(){
}
public Recipe(int id, String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mID = id;
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public Recipe(String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public String getRecipeName() {
return mRecipeName;
}
public int getID() {
return mID;
}
public void setID(int id){
mID = id;
}
public String getServings() {
return mServings;
}
public String getPrepTime() {
return mPrepTime;
}
public void setRecipeName(String recipeName) {
mRecipeName = recipeName;
}
public void setServingSize(String servings) {
mServings = servings;
}
public void setPrepTime(String prepTime) {
mPrepTime = prepTime;
}
public void setServings(String servings) {
mServings = servings;
}
public List<String> getIngredients() {
return mIngredients;
}
public List<String> getDirections() {
return mDirections;
}
public String getCookTime() {
return mCookTime;
}
public void setCookTime(String cookTime) {
mCookTime = cookTime;
}
public void setIngredients(List<String> ingredients) {
mIngredients = ingredients;
}
public void setDirections(List<String> directions) {
mDirections = directions;
}
public boolean isInList() {
return isInList;
}
public void setInList(boolean inList) {
isInList = inList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mRecipeName);
dest.writeInt(this.mID);
dest.writeString(this.mServings);
dest.writeString(this.mPrepTime);
dest.writeString(this.mCookTime);
dest.writeByte(this.isInList ? (byte) 1 : (byte) 0);
dest.writeStringList(this.mIngredients);
dest.writeStringList(this.mDirections);
}
protected Recipe(Parcel in) {
this.mRecipeName = in.readString();
this.mID = in.readInt();
this.mServings = in.readString();
this.mPrepTime = in.readString();
this.mCookTime = in.readString();
this.isInList = in.readByte() != 0;
this.mIngredients = in.createStringArrayList();
this.mDirections = in.createStringArrayList();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel source) {
return new Recipe(source);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
}
And main activity class that uses the adapter:
public class RecipeList extends AppCompatActivity{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private int REQUEST_CODE=1;
private Button mNavigateGroceryButton;
RecipeDB dbHelper = new RecipeDB(this);
List<Recipe> recipes;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipes = dbHelper.getAllRecipes();
setContentView(R.layout.activity_recipe_list);
mRecyclerView = (RecyclerView) findViewById(R.id.list_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
mNavigateGroceryButton = (Button) findViewById(R.id.navigate_to_groceries_button_list_view);
mNavigateGroceryButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(RecipeList.this, ExpandableListViewActivity.class);
//Log.d("Navigate", "navigate pressed" );
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
}
public boolean onOptionsItemSelected(MenuItem item){
//Handles menu buttons
switch (item.getItemId()){
case R.id.recipe_list_add_recipe_actionbar_button:
//This button creates a new empty Recipe object and passes it to the EditRecipe class
//The Recipe object is passed as a parcelable
Recipe passedRecipe = new Recipe();
Intent i = new Intent(RecipeList.this, EditRecipe.class);
i.putExtra("passed_recipe_key", (Parcelable) passedRecipe);
startActivityForResult(i, REQUEST_CODE);
return true;
default:
Log.d("Name,", "default called");
return super.onOptionsItemSelected(item);
}
}
public void addNewReRecipe(Recipe recipe){
dbHelper.addRecipe(recipe);
recipes = dbHelper.getAllRecipes();
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
}
//Makes the menu bar appear as it is in the action_bar_recipe_list_buttons menu layout file
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_recipe_list_buttons, menu);
return true;
}
//This code is called after creating a new recipe. This is only for creating, and not editing.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE){
if(resultCode == Activity.RESULT_OK) {
Recipe createdRecipe = data.getExtras().getParcelable("recipe_key");
addNewReRecipe(createdRecipe);
}
}
}
}
Looks like you need to declare your button at the top of your ViewHolder with your other views. So move the declaration from the top of your adapter:
private Button mAddToGroceriesButton;
Then in your onBindViewHolder method you can get a reference to your button through the holder and set the background:
if(recipe.isInList()) {
holder.mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
Try this,
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
mRecipeTextSection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
});
Recipe recipeToGrocery = mRecipeSet.get(position);
if(!recipeToGrocery.isInList()) {
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
else{
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_26dp);//set another image
}
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
notifyDataSetChanged();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}

RecyclerView with SearchView will not populate upon initialization

I am currently using searchView to filter results on a RecyclerView. The problem is when the fragment is initialized, the list won't appear not until I click on the search icon on the toolbar and type some texts on it. I've tried modifying the codes. Take a look specifically at the adapter and holder classes, if you'll try to exchange my current codes to these:
public MembershipActivationAdapter(Context context, List<Member> members){
this.context = context;
this.mMembers = members;
}
and
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
,it will show the list upon calling the fragment however if I'll type something on the SearchView, it seems to function only as a one way filter. It will filter names but whenever I'll try to remove a character or a text on the searchview, it won't show the list back. Please help me with this. These are my codes:
Adapter & ViewHolder class:
public class MembershipActivationAdapter extends RecyclerView.Adapter<MembershipActivationAdapter.MembershipActivationViewHolder> {
private final List<Member> mMembers;
private final LayoutInflater inflater;
//private final Context context;
public MembershipActivationAdapter(Context context, List<Member> members){
inflater = LayoutInflater.from(context);
mMembers = new ArrayList<>(members);
//this.context = context;
//this.mMembers = members;
}
#Override
public int getItemCount() {
return mMembers.size();
}
#Override
public void onBindViewHolder(MembershipActivationViewHolder holder, final int position) {
final Member m = mMembers.get(position);
holder.name.setText(m.getName());
holder.email.setText(m.getEmail());
if(m.getStatus().equals("Active")){
holder.status.setText(Html.fromHtml("<font color='#00CD00'>" + m.getStatus() + "</font>"));
}else{
holder.status.setText(Html.fromHtml("<font color='#ff0000'>" + m.getStatus() + "</font>"));
}
}
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = inflater.inflate(R.layout.member_activation_content, viewGroup, false);
return new MembershipActivationViewHolder(itemView);
//final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
public static class MembershipActivationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView name;
public final TextView email;
public final TextView status;
public MembershipActivationViewHolder(View v) {
super(v);
v.setOnClickListener(this);
name = (TextView) v.findViewById(R.id.member_name);
email = (TextView) v.findViewById(R.id.member_email);
status = (TextView) v.findViewById(R.id.member_status);
}
}
public List<Member> getMemberList() {
return mMembers;
}
public void animateTo(List<Member> members) {
applyAndAnimateRemovals(members);
applyAndAnimateAdditions(members);
applyAndAnimateMovedItems(members);
}
private void applyAndAnimateRemovals(List<Member> newMembers) {
for (int i = mMembers.size() - 1; i >= 0; i--) {
final Member member = mMembers.get(i);
if (!newMembers.contains(member)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Member> newMembers) {
for (int i = 0, count = newMembers.size(); i < count; i++) {
final Member member = newMembers.get(i);
if (!mMembers.contains(member)) {
addItem(i, member);
}
}
}
private void applyAndAnimateMovedItems(List<Member> newMembers) {
for (int toPosition = newMembers.size() - 1; toPosition >= 0; toPosition--) {
final Member member = newMembers.get(toPosition);
final int fromPosition = mMembers.indexOf(member);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Member removeItem(int position) {
final Member member = mMembers.remove(position);
notifyItemRemoved(position);
return member;
}
public void addItem(int position, Member member) {
mMembers.add(position, member);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Member member = mMembers.remove(fromPosition);
mMembers.add(toPosition, member);
notifyItemMoved(fromPosition, toPosition);
}
}
Fragment Class:
public class MembershipActivationFragment extends Fragment implements SearchView.OnQueryTextListener{
private static String url = "http://www.xxxxx.org/portal/webservices/get_members.php";
private List<Member> memberList;
private RecyclerView recyclerView;
private MembershipActivationAdapter adapter;
private String pid;
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.member_activation, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.members_recycler_view);
setHasOptionsMenu(true);
memberList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
populate();
return rootView;
}
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
String name, email, status;
Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
member = new Member(name, email, status);
memberList.add(member);
} catch (Exception e) {
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
adapter = new MembershipActivationAdapter(getActivity(), memberList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<Member> filteredMemberList = filter(memberList, query);
adapter.animateTo(filteredMemberList);
recyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Member> filter(List<Member> members, String query) {
query = query.toLowerCase();
final List<Member> filteredModelList = new ArrayList<>();
for (Member member : members) {
final String text = member.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(member);
}
}
return filteredModelList;
}
private void hidePDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
RecyclerView container xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/members_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Content class:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name here"
android:textStyle="bold"
android:id="#+id/member_name"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_email"
android:layout_below="#+id/member_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_status"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
Model Class:
public class Member {
private String name;
private String email;
private String status;
public Member(String name, String email, String status) {
this.name = name;
this.email = email;
this.status = status;
}
public Member(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Atlast! I was able to find the resolution for this. Kudos to the developer himself, Xaver Kapeller!
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
// hidePDialog();
String email, status;
// Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
final String name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
mModels.add(new ExampleModel(name));
// member = new Member(name, email, status);
} catch (Exception e) {
}
}
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
Just tranfer these two lines of code inside onResponse() and everything will work perfectly fine:
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);

Categories

Resources