Related
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;
}
}
I have a gallery of images that shows the images in a recyclerviewusing glide and by clicking on each image in the recyclerview that image open in a view pager. every thing is ok in the beginning the recyclerview is fine, the images open in a viewpager and sliding in viewpager are all fine. but when i press back to close the viewpager and goback to recyclerview suddenly the allocated memory raises to about 400 MB!!!
there are 8 images that are about 490*420 pixel and 72 KB size.
MainGallery.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recView_Gallery1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
>
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_retry_Gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="تلاش مجدد"
android:textSize="16sp"
android:visibility="gone"
android:layout_gravity="center"
android:gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
GalleryEnter.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="wrap_content"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/iv_photoGallety"
android:adjustViewBounds="true"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:layout_margin="2dp"
android:layout_width="match_parent"
android:background="#android:color/white"/>
</LinearLayout>
ImageDetail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.parsroyan.restaurant.imageDetailActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
MainGalleryActivity.java
public class GalleryMain_Activity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public static RecyclerView recListMenuTypes;
public static ImageAdapter mta;
ArrayList<ImageGallery> data = new ArrayList<>();
Button btn_retry;
TextView tv_message;
ImageView imv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_main_);
btn_retry = (Button) findViewById(R.id.btn_retry_Gallery);
recListMenuTypes = (RecyclerView) findViewById(R.id.recView_Gallery1)
;
recListMenuTypes.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new
GridLayoutManager(GalleryMain_Activity.this, 2);
recListMenuTypes.setLayoutManager(mLayoutManager);
//LinearLayoutManager llm = new
LinearLayoutManager(GalleryMain_Activity.this);
//llm.setOrientation(LinearLayoutManager.VERTICAL);
//recListMenuTypes.setLayoutManager(llm);
recListMenuTypes.setItemAnimator(new DefaultItemAnimator());
mta = new ImageAdapter(GalleryMain_Activity.this, data);
recListMenuTypes.setAdapter(mta);
Check_Connection_Retrive();
btn_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Check_Connection_Retrive();
}
});
}
private void alertView1(String message,boolean success) {
final TypedArray styledAttributes =
GalleryMain_Activity.this.getTheme().obtainStyledAttributes(new int[] {
android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.custom_toast_layout));
tv_message = (TextView)
toastLayout.findViewById(R.id.custom_toast_message);
tv_message.setText(message);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP | Gravity.START |
Gravity.FILL_HORIZONTAL,0,Y);
toast.setView(toastLayout);
imv_message = (ImageView)
toastLayout.findViewById(R.id.custom_toast_image);
if(!success){
toastLayout.setBackgroundColor(Color.parseColor("#cc0000"));
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_alert);
}
else {
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_info);
}
toastLayout.setAlpha(.8f);
toast.show();
}
public void Check_Connection_Retrive()
{
if(InternetConnection.checkConnection(getApplicationContext(),this))
{
btn_retry.setVisibility(View.GONE);
new FetchGallery().execute();
}
else
{
btn_retry.setVisibility(View.VISIBLE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private class FetchGallery extends AsyncTask<String, String, String> {
TransparentProgressDialog pdLoading = new
TransparentProgressDialog
(GalleryMain_Activity.this,R.drawable.progress_circle);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {`enter code here`
super.onPreExecute();
//pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
//pdLoading.setProgress(10);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("My_URL");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "1";
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "2";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return "3";
}
} catch (IOException e) {
return "4";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
switch(result) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
try {
btn_retry.setVisibility(View.GONE);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
//JSONObject json_data = jArray.getJSONObject(i);
ImageGallery image = new ImageGallery();
//image.name = json_data.getString("name");
image.title = jArray.get(i).toString();
image.url = "MY_URL" + image.title;
data.add(image);
}
// Setup and Handover data to recyclerview
mta.notifyDataSetChanged();
recListMenuTypes.addOnItemTouchListener(new
RecyclerViewTouchListener(getApplicationContext(), recListMenuTypes, new
RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GalleryMain_Activity.this,
imageDetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position){
}
}));
} catch (JSONException e) {
Toast.makeText(GalleryMain_Activity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
ImageAdapter.java
public class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.MenuViewHolder> {
private List<ImageGallery> imageGalleryList;
private Context context;
protected int lastPosition = -1;
public ImageAdapter(Context Context,List<ImageGallery> contactList)
{
this.imageGalleryList = contactList;
this.context = Context;
}
#Override
public int getItemCount() {
return imageGalleryList.size();
}
#Override
public void onBindViewHolder(ImageAdapter.MenuViewHolder menuViewHolder,
int i) {
final ImageGallery m = imageGalleryList.get(i);
Glide.with(context).load("MyURL"+m.title)
.thumbnail(.1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.logoback)
.into(menuViewHolder.vImage);
setFadeAnimation(menuViewHolder,i);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public ImageAdapter.MenuViewHolder onCreateViewHolder(ViewGroup
viewGroup, int i) {
final View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_gallery_enter, viewGroup, false);
return new ImageAdapter.MenuViewHolder(itemView);
}
#Override
public void onViewDetachedFromWindow(ImageAdapter.MenuViewHolder holder)
{
((ImageAdapter.MenuViewHolder)holder).itemView.clearAnimation();
}
public class MenuViewHolder extends RecyclerView.ViewHolder{
protected ImageView vImage;
public MenuViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.iv_photoGallety);
}
}
private void setFadeAnimation(ImageAdapter.MenuViewHolder view, int
position) {
if (position > lastPosition) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
anim.setDuration(1000);
view.itemView.startAnimation(anim);
lastPosition = position;
}
}
}
ImageDetailActivity.java
public class imageDetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageGallery> data = new ArrayList<>();
int pos;
Toolbar aboveToolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
//aboveToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.detail_toolbar);
//setSupportActionBar(aboveToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
setTitle(data.get(pos).getName());
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageGallery> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageGallery> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUrl());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
// #Override
//public CharSequence getPageTitle(int position) {
//return data.get(position).getName();
// }
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
ImageView ImageView;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
//private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
//this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
//args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
this.ImageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.tiara3)
.into(this.ImageView);
return rootView;
}
}
}
error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at com.bumptech.glide.request.GenericRequest.getPlaceholderDrawable(GenericRequest.java:416)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.request.ThumbnailRequestCoordinator.clear(ThumbnailRequestCoordinator.java:106)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2322)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2186)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:271)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:388)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:5273)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3438)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
at android.app.ActivityThread.access$1200(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
real device result:
enter image description here
smulator result:
enter image description here
Add below line in Application tag in Menifest file:
android:largeHeap="true"
I know that this question was asked many times before, but i'm confused why sometimes the data is loaded and sometimes data isn't loaded once i get to the end of list. Also when i go fast scrolling through the list, and the new data has been loaded, but immediately it returns me to the first item in list and remove all new loaded items from the next page from server. So that is the second problem and the third problem is that when i load items using SwipeRefreshLayout, i'm also not getting new items when i reach the end of the list.
I have implemented this in my project: https://gist.github.com/ssinss/e06f12ef66c51252563e
list.setLayoutManager(manager);
list.setEmptyView(emptyView);
list.setItemAnimator(new DefaultItemAnimator());
list.setAdapter(mAdapter);
loadJokes(1);
list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
#Override
public void onLoadMore(final int current_page) {
loadMoreJokes(current_page);
}
});
Here is the method where i'm loading more items from server:
private void loadMoreJokes(int current_page) {
StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + current_page,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
JSONArray jokes = object.getJSONArray("jokes");
if (!error) {
for (int i = 0; i < jokes.length(); i++) {
JSONObject object1 = jokes.getJSONObject(i);
Joke joke = new Joke();
joke.setId(object1.optInt("id"));
joke.setLikes(object1.optInt("likes"));
joke.setComments(object1.optInt("comments"));
joke.setJoke(object1.optString("joke"));
joke.setCreatedAt(object1.optString("created_at"));
joke.setName(object1.optString("user_name"));
joke.setImagePath(object1.optString("image_path"));
joke.setFacebookUserId(object1.optString("facebook_user_id"));
joke.setCategory(object1.optString("category"));
mJokes.add(joke);
}
menu.showMenu(true);
}
// Notify adapter that data has changed
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request);
}
And here is the method where i'm loading first visible items when someone launch the app:
private void loadJokes(int page) {
pDialog.setMessage("Loading..");
showDialog();
StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + page,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mJokes.clear();
hideDialog();
try {
JSONObject object = new JSONObject(response);
boolean error = object.getBoolean("error");
JSONArray jokes = object.getJSONArray("jokes");
if (!error) {
for (int i = 0; i < jokes.length(); i++) {
JSONObject object1 = jokes.getJSONObject(i);
Joke joke = new Joke();
joke.setId(object1.optInt("id"));
joke.setLikes(object1.optInt("likes"));
joke.setComments(object1.optInt("comments"));
joke.setJoke(object1.optString("joke"));
joke.setCreatedAt(object1.optString("created_at"));
joke.setName(object1.optString("user_name"));
joke.setImagePath(object1.optString("image_path"));
joke.setFacebookUserId(object1.optString("facebook_user_id"));
joke.setCategory(object1.optString("category"));
mJokes.add(joke);
}
menu.showMenu(true);
}
// Notify adapter that data has changed
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
menu.showMenu(true);
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request);
}
And this is onRefresh() method:
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
refreshItems();
}
}, 5000);
}
private void refreshItems() {
loadJokes(1);
mSwipeRefreshLayout.setRefreshing(false);
}
If i need to post more code, let me know. I really need to solve this problem as soon as i can. So again, the problems are the following:
When fast scrolling through the list, new items are being loaded, but immediately after that it returns me to the beginning of the list and when i go to the end of list again, load more doesn't respond.
After refreshing the list with SwipRefreshLayout, also scrolling doesn't respond at the end.
Note: The scrolling and loading new items is working only if i go slowly through the list and if i didn't swipe to refresh list.
EDIT:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_jokes, container, false);
mContext = getActivity();
mView = (CoordinatorLayout) view.findViewById(R.id.coordinatorLayout);
TextView tvEmptyText = (TextView) view.findViewById(R.id.tv_empty);
ImageView ivSignal = (ImageView) view.findViewById(R.id.iv_signal);
if (!ConnectionDetector.getInstance(getActivity()).isOnline() && mAdapter == null) {
tvEmptyText.setVisibility(View.VISIBLE);
ivSignal.setVisibility(View.VISIBLE);
showNoInternetSnackbar();
}
// INITIALIZE RECYCLER VIEW
EmptyRecyclerView list = (EmptyRecyclerView) view.findViewById(R.id.list);
mJokes = new ArrayList<>();
mAdapter = new RecyclerJokesAdapter(getActivity(), mJokes, JokesFragment.this, null);
// Progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
showDialog();
View emptyView = inflater.inflate(R.layout.layout_empty_view, container, false);
FloatingActionButton fab1 = (FloatingActionButton) view.findViewById(R.id.fab_funny);
FloatingActionButton fab2 = (FloatingActionButton) view.findViewById(R.id.fab_good_morning);
FloatingActionButton fab3 = (FloatingActionButton) view.findViewById(R.id.fab_good_night);
FloatingActionButton fab4 = (FloatingActionButton) view.findViewById(R.id.fab_all);
menu = (FloatingActionMenu) view.findViewById(R.id.menu_sort_jokes);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
fab3.setOnClickListener(this);
fab4.setOnClickListener(this);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(
R.color.refresh_progress_1,
R.color.refresh_progress_2,
R.color.refresh_progress_3);
LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
list.setLayoutManager(manager);
list.setEmptyView(emptyView);
list.setItemAnimator(new DefaultItemAnimator());
list.setAdapter(mAdapter);
if (ConnectionDetector.getInstance(mContext).isOnline()) {
loadJokes(1);
} else {
showNoInternetSnackbar();
hideDialog();
}
list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
#Override
public void onLoadMore(final int current_page) {
loadMoreJokes(current_page);
}
});
return view;
}
In onCreate method initialize your adapter, recyclerView and List
List<MyObject> myList = new ArrayList<>();
recyclerViewAdapter = new RecyclerViewAdapter(context, myList)
myRecyclerView.setAdapter(recyclerViewAdapter);
Now, whenever you load data. add the data to your myList and call notifyDataSetChange on your adpater
myList.add(data);
recyclerViewAdapter.notifyDataSetChange();
Use this wrapper class
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import java.util.List;
public abstract class RecyclerWrapperAdapter<E> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected Context context;
protected List<E> objects;
public void setContext(Context context) {
this.context = context;
}
public void setObjects(List<E> objects) {
this.objects = objects;
notifyDataSetChanged();
}
public void add(#NonNull E object) {
objects.add(object);
notifyDataSetChanged();
}
public void add(int position, #NonNull E object) {
if (position < objects.size() && position >= 0) {
objects.add(position, object);
notifyItemChanged(position);
notifyDataSetChanged();
} else if (position >= objects.size()) {
objects.add(object);
notifyDataSetChanged();
}
}
public void set(int position, #NonNull E object) {
if (position < objects.size() && position >= 0) {
objects.set(position, object);
notifyItemChanged(position);
} else if (position >= objects.size()) {
objects.add(object);
notifyDataSetChanged();
}
}
public void remove(#NonNull E object) {
objects.remove(object);
notifyDataSetChanged();
}
public void remove(int position) {
if (position >=0 && position < objects.size()) {
objects.remove(position);
notifyDataSetChanged();
}
}
public void removeAll() {
objects.clear();
notifyDataSetChanged();
}
public E getItem(int position) {
return objects.get(position);
}
#Override
public int getItemCount() {
return objects.size();
}
}
Well I have done this way:
MainActivity .java
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, onRecyclerViewListener {
private RecyclerView mRecyclerView;
private TextView tvEmptyView;
private LinearLayoutManager mLayoutManager;
private List<Object> studentList;
protected Handler handler;
private int count = 0;
private SwipeRefreshLayout swipeRefreshLayout;
private MyRecycleAdapter myRecycleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.purple, R.color.green, R.color.orange);
tvEmptyView = (TextView) findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
studentList = new ArrayList<Object>();
handler = new Handler();
loadData();
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
myRecycleAdapter = new MyRecycleAdapter(mRecyclerView, studentList, R.layout.list_row, R.layout.progressbar_item, this);
myRecycleAdapter.setLoadMoreEnable(true);
myRecycleAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
count++;
if (count == 4) {
count = 0;
myRecycleAdapter.setLoadMoreEnable(false);
} else {
myRecycleAdapter.setLoadMoreEnable(true);
}
//add null , so the adapter will check view_type and show progress bar at bottom
studentList.add(null);
myRecycleAdapter.notifyItemInserted(studentList.size() - 1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
studentList.remove(studentList.size() - 1);
myRecycleAdapter.notifyItemRemoved(studentList.size());
//add items one by one
int start = studentList.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
studentList.add(new Student("Student " + i, "AndroidStudent" + i + "#gmail.com"));
myRecycleAdapter.notifyItemInserted(studentList.size());
}
myRecycleAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 1000);
}
});
ItemViewHolderNew.setRecyclerListener(this);
mRecyclerView.setAdapter(myRecycleAdapter);
if (studentList.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
}
private void loadData() {
for (int i = 1; i <= 20; i++) {
studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
},5000);
}
#Override
public void onBindView(View view, final ItemViewHolderNew itemViewHolder) {
itemViewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
itemViewHolder.tvEmailId = (TextView) view.findViewById(R.id.tvEmailId);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, Object object, ItemViewHolderNew itemViewHolder) {
Student studentObj = (Student)object;
itemViewHolder.tvName.setText(studentObj.getName());
itemViewHolder.tvEmailId.setText(studentObj.getEmailId());
itemViewHolder.student= studentObj;
}
#Override
public void setClickListener(View view, ItemViewHolderNew itemViewHolder) {
Toast.makeText(view.getContext(), "OnClick :" + itemViewHolder.student.getName() + " \n " + itemViewHolder.student.getEmailId(), Toast.LENGTH_SHORT).show();
}
public static class ItemViewHolderNew extends RecyclerView.ViewHolder{
public TextView tvName, tvEmailId;
public Student student;
private static onRecyclerViewListener mListener;
public static void setRecyclerListener(onRecyclerViewListener listener){
mListener = listener;
}
public ItemViewHolderNew(View itemView) {
super(itemView);
mListener.onBindView(itemView, this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setClick(v);
}
});
}
private void setClick(View v) {
mListener.setClickListener(v, this);
}
}
}
Add OnLoadMoreListener.java interface
public interface OnLoadMoreListener {
void onLoadMore();
}
Add Student.java as Model class
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String emailId;
public Student(String name, String emailId) {
this.name = name;
this.emailId = emailId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
<TextView
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="No Records Here !"
android:visibility="gone" />
</RelativeLayout>
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:padding="5dp"
android:background="?android:selectableItemBackground">
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<TextView
android:id="#+id/tvEmailId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="#android:color/black"
android:textSize="12sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvName"
android:layout_margin="5dp"
android:text="Email Id"
android:textColor="#android:color/black"
android:textSize="12sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
progressbar_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" />
</LinearLayout>
Working fine with Endless, swipe to refresh, load more RecyclerView.
Hope this would help you.
Volley RequestQueue uses a thread pool for network requests.
/** Number of network request dispatcher threads to start. */
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
Obviously, when you do fast scrolling through the list multiple requests are generated in quick succession.
There is a possibility that the responses are received asynchronously / out of sequence. Also, its possible that the "No more data" responses / error responses etc arrive before the responses with next page of data, which may lead to unexpected behaviour by your app.
Specially watch out for how this would effect your mJokes ArrayList member variable.
I am building a order receiving app for waiter in which half page is activity layout which contains listview and half is viewpager which contains json arraylist in fragment. I want to add the menu data from fragment when clicked on + button with number of quantity to be add on root activity's listview
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="140dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
app:layout_collapseMode="parallax"
android:background="#mipmap/bgactionbar">
<ImageView
android:id="#+id/logo"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginLeft="30dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:background="#mipmap/logoapp"
/>
<ImageView
android:id="#+id/triangle"
android:layout_width="280dp"
android:layout_height="100dp"
android:layout_toRightOf="#+id/logo"
android:background="#mipmap/caley"
/>
<RelativeLayout
android:id="#+id/searchLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/triangle"
android:background="#F3EEE8"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_menu_search"
android:layout_toRightOf="#+id/search_menu"
/>
<EditText
android:id="#+id/search_menu"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Search Menu..."
android:textColorHint="#color/tab_text"
android:textColor="#color/tab_text"
android:background="#android:color/transparent"
android:layout_alignParentLeft="true"
android:inputType="textVisiblePassword"/>
</RelativeLayout>
<ImageView
android:id="#+id/coffee"
android:layout_width="110dp"
android:layout_height="140dp"
android:layout_toRightOf="#+id/searchLayout"
android:background="#mipmap/coffee"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
android:background="#mipmap/background"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:background="#mipmap/background"
android:layout_below="#id/My_Container_1_ID">
<TextView
android:id="#+id/txtorder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Order"
android:textStyle="bold"
android:textColor="#color/tab_text"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/orderlist"
android:layout_width="340dp"
android:layout_height="match_parent"
android:layout_above="#+id/submit_order"
android:layout_below="#+id/txtorder"
android:background="#mipmap/background"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<Button
android:id="#+id/submit_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/orderlist"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/orderlist"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#EE6426"
android:textColor="#android:color/white"
android:text="Submit" />
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_below="#+id/My_Container_1_ID"
android:layout_toRightOf="#+id/content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
public class Menu extends AppCompatActivity implements Coffee.OnMenuInteractionListener {
// private ArrayList<MenuDataModel> allOrders;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ListView listView;
RecyclerView recyclerView;
RecyclerAdapter adapter;
// MenuTabAdapter adapter;
// ArrayList<MenuDataModel> allOrders;
private List<MenuDataModel> allOrders = new ArrayList<MenuDataModel>();
// private List<String> orderList = new ArrayList<>();
private String Quantity, Name;
EditText count, inputSearch;
TextView order;
String searchValue;
private ArrayList<String> stringArrayList;
CollapsingToolbarLayout collapsingToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbar= (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// collapsingToolbar.setTitle(getString(R.string.app_name));
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// listView = (ListView) findViewById(R.id.orderlist);
// adapter = new MenuTabAdapter(this, allOrders);
// listView.setAdapter(adapter);
TextView orddd = (TextView) findViewById(R.id.txtorder);
inputSearch = (EditText) findViewById(R.id.search_menu);
// inputSearch.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// collapsingToolbar.setVisibility(View.GONE);
//
// }
// });
// recyclerView = (RecyclerView) findViewById(R.id.orderlist);
// recyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(layoutManager);
//
// adapter = new RecyclerAdapter(this, allOrders);
// recyclerView.setAdapter(adapter);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Coffee(), "Coffee");
adapter.addFragment(new Coffee(), "BreakFast");
adapter.addFragment(new Coffee(), "Beverage");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList) {
allOrders = menuList;
}
#Override
public void onMenuListItemClick(int position) {
//musicService.setSong(position);
MenuDataModel menuorder = allOrders.get(position);
// menuorder.setName(menuorder.getName());
// menuorder.setName(allOrders);
allOrders.add(menuorder);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class Coffee extends Fragment {
ListView listView;
MenusAdapter adapter;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<MenuDataModel> menuList = new ArrayList<MenuDataModel>();
OnMenuInteractionListener menuItemClick;
private String searchData;
private EditText inputSearch;
// Activity activity;
//OnMenuInteractionListener mCallback;
public Coffee() {
// Required empty public constructor
}
public interface OnMenuInteractionListener {
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList);
public void onMenuListItemClick(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
menuItemClick = (OnMenuInteractionListener) getActivity();
}
#Override
public void onDetach() {
super.onDetach();
menuItemClick = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// searchData = getArguments().getString("search");
inputSearch = (EditText) getActivity().findViewById(R.id.search_menu);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user changed the Text
//adapter.getFilter().filter(cs.toString());
if (count < before) {
// We're deleting char so we need to reset the adapter data
adapter.resetData();
}
Coffee.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
View view = inflater.inflate(R.layout.fragment_coffee, container, false);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MenusAdapter(getActivity(), menuList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showpDialog();
// Creating volley request obj
JsonObjectRequest bookingReq = new JsonObjectRequest(Request.Method.GET, "" + url + "?", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("bsd", response.toString());
// Parsing json
try {
JSONArray menu = response.getJSONArray("menus");
int length = menu.length();
for (int i = 0; i < menu.length(); i++) {
JSONObject obj = menu.getJSONObject(i);
MenuDataModel dm = new MenuDataModel();
// Log.d("vdata", String.valueOf(menu.length()));
dm.setID(obj.getString("id"));
dm.setName(obj.getString("name"));
dm.setThumbnailUrl(obj.getString("photo"));
Log.d("image", String.valueOf(obj.getString("photo")));
dm.setDescription(obj.getString("description"));
dm.setRate(obj.getString("price"));
dm.setStatus(obj.getString("status"));
// adding movie to movies array
menuList.add(dm);
// Log.d("nth", String.valueOf(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#SuppressWarnings("deprecation")
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("b", "Error: " + error.getMessage());
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookingReq);
return view;
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.setMessage("Please wait...");
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
public class MenusAdapter extends BaseAdapter implements Filterable {
private static final String TAG = MenusAdapter.class.getSimpleName();
List<MenuDataModel> MenuItems;
List<MenuDataModel> mSearchValues;
private android.widget.Filter menufilter;
Coffee.OnMenuInteractionListener mCallback;
//private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MenusAdapter(Activity activity, List<MenuDataModel> MenuItems) {
//this.activity = activity;
this.MenuItems = MenuItems;
this.mSearchValues = MenuItems;
}
#Override
public int getCount() {
return MenuItems.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return MenuItems.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.menu_item, parent, false);
}
// if (imageLoader == null)
// imageLoader = AppController.getInstance().getImageLoader();
final ImageView increase = (ImageView) view.findViewById(R.id.icon_increase);
ImageView decrease = (ImageView) view.findViewById(R.id.icon_decrease);
final EditText count = (EditText) view.findViewById(R.id.count_menu);
NetworkImageView thumbnailUrl = (NetworkImageView) view.findViewById(R.id.menu_image);
TextView name = (TextView) view.findViewById(R.id.menu_items);
// TextView description = (TextView) view.findViewById(R.id.description);
// TextView rate = (TextView) view.findViewById(R.id.price);
final MenuDataModel data = MenuItems.get(index);
name.setText(String.valueOf(data.getName()));
thumbnailUrl.setImageUrl(data.getThumbnailUrl(), imageLoader);
thumbnailUrl.setDefaultImageResId(R.mipmap.logoapp);
thumbnailUrl.setErrorImageResId(R.mipmap.logoapp);
// description.setText(String.valueOf(data.getDescription()));
// title.setText(data.getTitle());
// rate.setText(String.valueOf(data.getRate()));
// final double dis = Double.valueOf(data.getRate());
final int[] quantity = {MenuItems.get(index).getAnInt()};
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
quantity[0]++;
count.setText(quantity[0] + "");
count.setTag(quantity[0] + "");
// mCallback.onFragmentSetOrders(all);
mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
// Coffee.OnMenuInteractionListener listener = (Coffee.OnMenuInteractionListener) activit;
// mCallback.onFragmentSetOrders(menu);
// Bundle bundle = new Bundle();
// bundle.putString("quantity", quantity[0] + "");
// bundle.putString("name", String.valueOf(data.getName()));
// q.putExtra("bookingid", dataModel.getbkid());
// parent.getContext().startActivity(q);
}
});
decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count.getTag();
count.setTag(quantity[0] + "");
quantity[0]--;
count.setText(quantity[0] + "");
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return view;
}
#Override
public Filter getFilter() {
if (menufilter == null)
menufilter = new MenuFilter();
return menufilter;
}
public void resetData() {
MenuItems = mSearchValues;
}
private class MenuFilter extends android.widget.Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = mSearchValues;
results.count = mSearchValues.size();
} else {
// We perform filtering operation
List<MenuDataModel> nDriverList = new ArrayList<MenuDataModel>();
for (MenuDataModel p : MenuItems) {
if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nDriverList.add(p);
}
results.values = nDriverList;
results.count = nDriverList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
MenuItems = (List<MenuDataModel>) results.values;
notifyDataSetChanged();
}
}
}
;
}
i am getting null pointer exception on mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
Step 1: Create Interface
public interface ActivityCommunicator{
public void passDataToActivity(ArrayList<string> arrayList);
}
Step 2:Initialize interface object in fragment class
private ActivityCommunicator activityCommunicator;;
public void onAttach(Activity activity)
{
super.onAttach(activity);
context = getActivity();
activityCommunicator =(ActivityCommunicator)context;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
activityButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
activityCommunicator.passDataToActivity("Your Array List");
}
});
}
step 3: Access Your arraylist from fragment in your activity class.
public class MainActivity extends FragmentActivity implements ActivityCommunicator{
public static ArrayList<String> aList;
#Override
public void passDataToActivity(ArrayList<String> arrayList){
aList = arrayList;
}
}
I'm trying to understand AsyncTask in Android. I can't understand how do we pass parameters. In this code :
protected class AsyncLogin extends AsyncTask<String, JSONObject, Boolean> {
String userName = null;
#Override
protected Boolean doInBackground(String... params)
{
RestAPI api = new RestAPI();
boolean userAuth = false;
try
{
JSONObject jsonObj = api.UserAuthentication(params[0], params[1]);
JSONParser parser = new JSONParser();
userAuth = parser.parseUserAuth(jsonObj);
userName = params[0];
}
catch (Exception e)
{
Log.d("AsyncLogin", e.getMessage());
}
return userAuth;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
Toast.makeText(context, "Please wait...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Boolean result)
{
if(result) {
Intent i = new Intent(LoginActivity.this, UserDetailsActivity.class);
i.putExtra("username", userName);
startActivity(i);
}
else
{
Toast.makeText(context, "Not valid username/password", Toast.LENGTH_SHORT).show();
}
}
}
I can't understand why do we use <String, JSONObject, Boolean> in
protected class AsyncLogin extends AsyncTask<String, JSONObject, Boolean>
What do String, JSONObject and Boolean refer to? Can you explain it to me? Thanks.
AsyncTask (Type1, Type2, Type3) uses argument types:
Type1 is the type of argument you pass when you call execute (received in doInBackground)
Type2 is the type of the argument you pass to onProgressUpdate when you call publishProgress.
Type3 is the type of argument you pass to onPostExecute, which is what you return from doInBackground.
Asynch Task implementation allows you one type parameter as argument. But you can pass it more type parameters, by declaring one parameterized constructor to it.
e.g.
class YourAsynchTask extends AsyncTask<ArgumentObject, ProgressObject, ResultObject> {
......
ObjectType1 argument1;
ObjectType2 argument2;
ObjectType3 argument3;
YourAsynchTask(ObjectType1 arg1, ObjectType2 arg2, ObjectType3 arg3) {
argument1 = arg1;
argument2 = arg2;
argument3 = arg3;
}
// rest of the method of your asynch task like doInBackground, etc.
}
You can call this type of asynch task like this :
new YourAsynchTask(arg1, arg2, arg3).execute(argumentObjet);
public class Child
{
String child_title;
public String getChild_title() {
return child_title;
}
public void setChild_title(String child_title) {
this.child_title = child_title;
}
}
public class Parent
{
String header_title;
ArrayList<Child>childArrayList;
public ArrayList<Child> getChildArrayList() {
return childArrayList;
}
public void setChildArrayList(ArrayList<Child> childArrayList) {
this.childArrayList = childArrayList;
}
public String getHeader_title() {
return header_title;
}
public void setHeader_title(String header_title) {
this.header_title = header_title;
}
}
public class ExpandAdapter extends BaseExpandableListAdapter
{
Context context;
ArrayList<Parent>parentArrayList;
LayoutInflater li;
public ExpandAdapter(Context context, ArrayList<Parent> parentArrayList)
{
this.context=context;
this.parentArrayList=parentArrayList;
li= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getGroupCount() {
return parentArrayList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return parentArrayList.get(groupPosition).getChildArrayList().size();
}
#Override
public Object getGroup(int groupPosition) {
return parentArrayList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return parentArrayList.get(groupPosition).getChildArrayList().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
convertView=li.inflate(R.layout.customheader,null);
TextView tv= (TextView) convertView.findViewById(R.id.tv);
tv.setText(parentArrayList.get(groupPosition).getHeader_title());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
convertView=li.inflate(R.layout.customchild,null);
TextView tv1= (TextView) convertView.findViewById(R.id.tv1);
tv1.setText(parentArrayList.get(groupPosition).childArrayList.get(childPosition).getChild_title());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
ExpandableListView expandlv;
ArrayList<Parent>parentArrayList;
ArrayList<Child>childArrayList;
Parent parent;
Child child;
String header_title[]={"No","Alpha","Funcation"};
String child_notitle[]={"1","2","3"};
String child_alphatitle[]={"A","B","C"};
String child_functiontitle[]={"F1","F2","F3"};
Context context=this;
ExpandAdapter expandadapter;
expandlv= (ExpandableListView) findViewById(R.id.expandlv);
parentArrayList =new ArrayList<>();
for(int i=0;i<header_title.length;i++)
{
parent =new Parent();
parent.setHeader_title(header_title[i]);
childArrayList =new ArrayList<>();
if(i==0)
{
for(int j=0;j<child_notitle.length;j++)
{
child =new Child();
child.setChild_title(child_notitle[j]);
childArrayList.add(child);
parent.setChildArrayList(childArrayList);
}
}
if(i==1)
{
for(int j=0;j<child_alphatitle.length;j++)
{
child=new Child();
child.setChild_title(child_alphatitle[j]);
childArrayList.add(child);
parent.setChildArrayList(childArrayList);
}
}
if(i==2)
{
for(int j=0;j<child_functiontitle.length;j++)
{
child=new Child();
child.setChild_title(child_functiontitle[j]);
childArrayList.add(child);
parent.setChildArrayList(childArrayList);
}
}
parentArrayList.add(parent);
}
expandadapter=new ExpandAdapter(context,parentArrayList);
expandlv.setAdapter((ExpandableListAdapter) expandadapter);
customheader
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header Title"
android:textColor="#android:color/darker_gray"
android:textSize="30dp"
android:layout_centerHorizontal="true"
android:id
enter code here
customchild
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv1"
android:layout_centerHorizontal="true"
android:text="Child Title"
android:textColor="#android:color/holo_green_dark"
android:textSize="20dp"/>
</RelativeLayout>
<ExpandableListView
android:layout_width="wrap_content"
android:layout_margin="20dp"
android:layout_height="wrap_content"
android:id="#+id/expandlv"/>
View Pager With Slide
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="#dimen/_10sdp" />
TabLayout tabLayout;
ViewPager viewPager;
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText(""));
tabLayout.addTab(tabLayout.newTab().setText(""));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final MyAdapter adapter = new MyAdapter(MainActivity.this,getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public class MyAdapter extends FragmentPagerAdapter {
private Context myContext;
int totalTabs;
public MyAdapter(Context context, FragmentManager fm, int totalTabs) {
super(fm);
myContext = context;
this.totalTabs = totalTabs;
}
// this is for fragment tabs
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment0 zero = new Fragment0();
return zero;
case 1:
Fragment1 one = new Fragment1();
return one;
default:
return null;
}
}
// this counts total number of tabs
#Override
public int getCount() {
return totalTabs;
}
}