In my app is Retrofit 1.9 and RecyclerView. On startup HTTP request is sending and I receive data, but not displaying. After SwipeRefresh data are downloaded again, but before that Recycler is displaying previous data.
Fragment:
package com.example.bolek.testy.Fragments;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.widget.Toast;
import com.example.bolek.testy.Adapters.ChaptersAdapter;
import com.example.bolek.testy.Interfaces.WebService;
import com.example.bolek.testy.Pojo.Chapter;
import com.example.bolek.testy.R;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import java.util.ArrayList;
import java.util.List;
public class RetrofitFragment extends Fragment {
private List<Chapter> chapterList = new ArrayList<>();
private RecyclerView recyclerView;
private ChaptersAdapter mAdapter;
RestAdapter retrofit;
WebService webService;
SwipeRefreshLayout refreshLayout;
public RetrofitFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrofit, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeRefreshLayout);
RecyclerView.LayoutManager mLayoutManager;
int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//sprawdzanie rozmiaru ekranu
switch (screenSize) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 1);
break;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
case Configuration.SCREENLAYOUT_SIZE_XLARGE:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 5);
} else {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 4);
}
break;
default:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 4);
} else {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 2);
}
}
mAdapter = new ChaptersAdapter(chapterList, getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
Log.i("aaaaaaaaaaaa", "startup");
prepareData(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("aaaaaaaaaaaa", "onRefresh called from SwipeRefreshLayout");
prepareData(true);
}
});
}
private void prepareData(final boolean refresh) {
retrofit = new RestAdapter.Builder()
.setEndpoint("http://bolex.cba.pl/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
webService = retrofit.create(WebService.class);
try {
webService.getData(new Callback<Chapter[]>() {
#Override
public void success(Chapter[] data, Response response) {
if (refresh) {
chapterList.clear();
}
for (Chapter item : data) {
chapterList.add(item);
}
refreshLayout.setRefreshing(false);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.d("Rest", error.getLocalizedMessage());
}
});
} catch (Exception e) {
Log.d("Rest", e.toString());
}
mAdapter.notifyDataSetChanged();
}
}
Adapter:
package com.example.bolek.testy.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import com.example.bolek.testy.Pojo.Chapter;
import com.example.bolek.testy.R;
public class ChaptersAdapter extends RecyclerView.Adapter<ChaptersAdapter.MyViewHolder> {
private List<Chapter> chapterList;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView date, number, title;
private ImageView cover;
public MyViewHolder(View view) {
super(view);
date = (TextView) view.findViewById(R.id.date);
cover = (ImageView) view.findViewById(R.id.cover);
number = (TextView) view.findViewById(R.id.number);
title = (TextView) view.findViewById(R.id.title);
}
}
public ChaptersAdapter(List<Chapter> chapterList, Context mContext) {
this.chapterList = chapterList;
this.mContext = mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chapter_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Chapter chapter = chapterList.get(position);
holder.title.setText(chapter.getTitle());
if(chapter.getDate() == null){
Log.d("aaaaaaaaaaaaaaaaaaaaa","null");
}
Glide.with(mContext).load("https://novelki.pl/uploads/"+chapter.getImage())
.thumbnail(0.5f)
.error(R.drawable.no_foto)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.cover);
holder.date.setText(chapter.getDate());
holder.number.setText("Tom " + chapter.getTomNumber() + " chapter " + chapter.getChapterNumber());
}
#Override
public int getItemCount() {
return chapterList.size();
}
}
Any idea?
P.S.
Sorry for my bad english.
I think you might not be updating you adapter when the data comes:
private void prepareData(final boolean refresh) {
#Override
public void success(Chapter[] data, Response response) {
retrofit = new RestAdapter.Builder()
.setEndpoint("http://bolex.cba.pl/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
webService = retrofit.create(WebService.class);
try {
webService.getData(new Callback<Chapter[]>() {
#Override
public void success(Chapter[] data, Response response) {
if (refresh) {
chapterList.clear();
}
for (Chapter item : data) {
chapterList.add(item);
}
// I JUST ADDED THIS LINE BELOW
mAdapter.notifyDataSetChanged();
refreshLayout.setRefreshing(false);
}
...
}
Related
i have implemented recyclerview and it works fine , i used a call back in BikeAdapter to be able to click every single row of this recycler view but when, i put these lines in OnCreateView the recycler view recycler throw null callback error , and when i delete mAdapter.setCallback(this); the recyclerview became empty
recyclerView.setAdapter(mAdapter); fillData();
mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
mAdapter.setCallback(this);
and when i put these lines inside the filldata() OnResponse method : mAdapter.setCallback(this) is not recognized
mAdapter.setCallback(this);
if i want to display my recycler view without problems i have to delete mAdapter.setCallback(this);
mAdapter = new BikesAdapter(getActivity(), (ArrayList) bikes);
recyclerView.setAdapter(mAdapter);
inside the fillData to get the response at the right time
//my adapter code
package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {
private final ArrayList<Bike> bikes;
private Context mContext;
private Callback mCallback;
public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
this.mContext = mContext ;
this.bikes = bikes;
}
#NonNull
#Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
return new BikesViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);
holder.BikeName.setText(singleItem.getModel());
holder.BikeImage.setBackgroundResource(singleItem.getImage());
holder.bikeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onItemClicked(singleItem);
}
});
holder.BikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return bikes.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
public final TextView BikeName;
public final ImageView BikeImage;
public final Button bikeView;
final BikesAdapter mAdapter;
public BikesViewHolder(#NonNull View itemView, BikesAdapter mAdapter) {
super(itemView);
this.BikeName = itemView.findViewById(R.id.bikeName);
this.BikeImage = itemView.findViewById(R.id.bikeImage);
this.bikeView = itemView.findViewById(R.id.btn_view);
this.mAdapter = mAdapter;
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public interface Callback {
void onItemClicked(Bike bike);
}
}
//my fragment that contains the recyclerview
package com.example.miniprojetandroid.ui.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentOne extends Fragment implements BikesAdapter.Callback{
private BikeService apiService;
private RecyclerView recyclerView;
private List<Bike> bikes = new ArrayList<Bike>();
private BikesAdapter mAdapter;
List<Bike> result = new ArrayList<Bike>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container,false);
recyclerView = rootView.findViewById(R.id.recycler_bikes);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
apiService = RetrofitClient.getClient().create(BikeService.class);
fillData();
mAdapter.setCallback(this);
return rootView;
}
public void fillData(){
Call<List<Bike>> call = apiService.getBikes();
call.enqueue(new Callback<List<Bike>>() {
#Override
public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
if(response.isSuccessful()){
bikes.addAll(response.body());
for(Bike bike: bikes){
bike.setImage(R.drawable.ruebike);
}
Log.e("Bike LIST", bikes.toString());
mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
recyclerView.setAdapter(mAdapter);
//listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
}
}
#Override
public void onFailure(Call<List<Bike>> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
/*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
bikes.add(new Bike(2,"AAA", "RTT" , "33", R.drawable.ruebike ));
bikes.add(new Bike(3,"BBB", "RUE" , "11", R.drawable.ruebike ));
bikes.add(new Bike(4,"EEE", "SPORT" , "25", R.drawable.ruebike ));
bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
Log.e("USERS LIST", bikes.toString());*/
}
#Override
public void onItemClicked(Bike bike) {
Bundle bundle = new Bundle();
bundle.putInt("bike_id",bike.getId());
bundle.putString("model", bike.getModel());
bundle.putString("type", bike.getType());
bundle.putString("price", bike.getPrice());
bundle.putInt("image", bike.getImage());
DetailsFragment f = new DetailsFragment();
f.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentsContainer, f )
.commit();
}
}
What i am trying to do is two things:
1/ make my fragment recyclerview works with filldata with the call back method(for idea Log.e show that this method works fine)
2/ to make sure that when i click an item of the recycler view , i pass the selected bike to a thired fragmend (DetailsFragment)
Errors: the recycler view is empty when i delete the callback and it throw null exception when i use it
help me pls
the method fillData is not executing immediately because it contain network operation so it work on background thread , so when you call setCallback , the mAdapter will not be initialized yet , so i suggest to initialize mAdapter and call setAdapter inside onCreate instead of onResponse method, and you can pass the array to the constructor as null ,and inside onResponse you can pass the bikes arrayList by setter method and inside this method (the setter method) after assigning the list add "notifyDataSetChanged();"
so your adapter will look like :
package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {
private final ArrayList<Bike> bikes;
private Context mContext;
private Callback mCallback;
public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
this.mContext = mContext ;
this.bikes = bikes;
}
public setBikesList(ArrayList<Bike> bikes){
this.bikes=bikes;
notifyDataSetChanged();
}
#NonNull
#Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
return new BikesViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);
holder.BikeName.setText(singleItem.getModel());
holder.BikeImage.setBackgroundResource(singleItem.getImage());
holder.bikeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onItemClicked(singleItem);
}
});
holder.BikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return bikes.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
public final TextView BikeName;
public final ImageView BikeImage;
public final Button bikeView;
final BikesAdapter mAdapter;
public BikesViewHolder(#NonNull View itemView, BikesAdapter mAdapter) {
super(itemView);
this.BikeName = itemView.findViewById(R.id.bikeName);
this.BikeImage = itemView.findViewById(R.id.bikeImage);
this.bikeView = itemView.findViewById(R.id.btn_view);
this.mAdapter = mAdapter;
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public interface Callback {
void onItemClicked(Bike bike);
}
}
and your fragment :
package com.example.miniprojetandroid.ui.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentOne extends Fragment implements BikesAdapter.Callback{
private BikeService apiService;
private RecyclerView recyclerView;
private List<Bike> bikes = new ArrayList<Bike>();
private BikesAdapter mAdapter;
List<Bike> result = new ArrayList<Bike>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container,false);
recyclerView = rootView.findViewById(R.id.recycler_bikes);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
apiService = RetrofitClient.getClient().create(BikeService.class);
fillData();
mAdapter = new BikesAdapter(getActivity(),null);
mAdapter.setCallback(this);
recyclerView.setAdapter(mAdapter);
return rootView;
}
public void fillData(){
Call<List<Bike>> call = apiService.getBikes();
call.enqueue(new Callback<List<Bike>>() {
#Override
public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
if(response.isSuccessful()){
bikes.addAll(response.body());
for(Bike bike: bikes){
bike.setImage(R.drawable.ruebike);
}
Log.e("Bike LIST", bikes.toString());
mAdapter.setBikesList(bikes);
//listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
}
}
#Override
public void onFailure(Call<List<Bike>> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
/*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
bikes.add(new Bike(2,"AAA", "RTT" , "33", R.drawable.ruebike ));
bikes.add(new Bike(3,"BBB", "RUE" , "11", R.drawable.ruebike ));
bikes.add(new Bike(4,"EEE", "SPORT" , "25", R.drawable.ruebike ));
bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
Log.e("USERS LIST", bikes.toString());*/
}
#Override
public void onItemClicked(Bike bike) {
Bundle bundle = new Bundle();
bundle.putInt("bike_id",bike.getId());
bundle.putString("model", bike.getModel());
bundle.putString("type", bike.getType());
bundle.putString("price", bike.getPrice());
bundle.putInt("image", bike.getImage());
DetailsFragment f = new DetailsFragment();
f.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentsContainer, f )
.commit();
}
}
I have a class that extends from a RecyclerView.Adapter, in that class I have two buttons, one to update and one to delete, the problem is that I want to use those buttons to call a method that is in another class that extends Fragments but not I know how to make the instance to my method, I also want to pass a parameter.
This is my class that extends from a RecyclerView.Adapter:
package com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.R;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.tareasFragmento;
import java.util.ArrayList;
/**
* Created Enrique Espinosa.
*/
public class TareasAdapter extends RecyclerView.Adapter<TareasAdapter.UsuarioHolder>{
private Activity activity;
private ArrayList<Tareas> tareas;
public TareasAdapter(Activity activity, ArrayList<Tareas> tareas) {
this.activity = activity;
this.tareas = tareas;
}
public class UsuarioHolder extends RecyclerView.ViewHolder {
public TextView txtId;
public TextView txtNombreUsuario;
public TextView txtNota;
public TextView txtEstudiante;
public int pasId;
Button btnEliminar = (Button)itemView.findViewById(R.id.btnEliminar);
Button btnActualizar = (Button)itemView.findViewById(R.id.btnActualizar);
public UsuarioHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.txt_id);
txtNombreUsuario = (TextView) itemView.findViewById(R.id.txt_nombre_usuario);
txtNota = (TextView) itemView.findViewById(R.id.txt_nota);
txtEstudiante = (TextView) itemView.findViewById(R.id.txtEstudiante);
}
}
#Override
public UsuarioHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = activity.getLayoutInflater().inflate(R.layout.plantilla_usuariosegundo, parent, false);
UsuarioHolder holder = new UsuarioHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final UsuarioHolder holder, int position) {
holder.txtId.setText(tareas.get(position).getId());
holder.txtNombreUsuario.setText("Tarea: "+ tareas.get(position).getNombreTarea());
holder.txtNota.setText("Nota: "+ tareas.get(position).getNota());
holder.txtEstudiante.setText("Estudiante: "+ tareas.get(position).getEstudiante());
}
#Override
public int getItemCount() {
return tareas.size();
}
}
And this is my class that extends form a Fragment:
package com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter.Tareas;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter.TareasAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Enriq on 26/04/2018.
*/
public class tareasFragmento extends Fragment {
private String url = "http://192.168.1.128:8080/WebServiceExamenFinal/webapi/tareas";
private ArrayList<Tareas> estudiantes = new ArrayList<>();
//Si no funciona esto se puede borrar
AlertDialog alertDialog;
private List<Tareas> tareasList;
private TareasAdapter tareasAdapter;
private int assiId;
public tareasFragmento() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tareas, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2,
GridLayoutManager.VERTICAL, false));
final TareasAdapter adapter = new TareasAdapter(getActivity(), estudiantes);
recyclerView.setAdapter(adapter);
RequestQueue queue = Volley.newRequestQueue(getContext());
final ProgressDialog dialog = new ProgressDialog(getContext());
dialog.setMessage("Por favor espere...");
dialog.show();
try {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
deserializarJSONArray(response);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"Error al realizar la peticiĆ³n\n" + error.getMessage(),
Toast.LENGTH_LONG).show();
if (dialog.isShowing()) dialog.dismiss();
}
});
queue.add(jsonArrayRequest);
}catch (Exception e) {
Toast.makeText(getActivity(),"El error es: "+e,Toast.LENGTH_LONG).show();
}
return view;
}
public void deserializarJSONArray(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject item = jsonArray.getJSONObject(i);
Tareas tareas = new Tareas();
tareas.setId(item.getString("id"));
tareas.setNombreTarea(item.getString("nombreUsuario"));
tareas.setEstudiante(item.getString("estudiante"));
tareas.setNota(item.getString("nota"));
estudiantes.add(tareas);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error al procesar la respuesta de la peticiĆ³n: " + e,
Toast.LENGTH_SHORT).show();
}
}
}
public void delete(int id){
Toast.makeText(getActivity(),"Este es el id recibido: "+id,Toast.LENGTH_LONG).show();
}
public int getAssiId(){
Toast.makeText(getActivity(),"Estas en el get de tareas fragmento",Toast.LENGTH_LONG).show();
return assiId;
}
}
I tried doing something similar to this:
tareasFragmento tarea = new tareasFragmento();
tarea.eliminar(id);
But it returns this error:
Attemp to invoque a virtual method 'android.content.res.Resources
android.content.Context.getResources()' a null object refrences
I've updated your adapter.
public class TareasAdapter extends RecyclerView.Adapter<TareasAdapter.UsuarioHolder> {
private Activity activity;
private ArrayList<Tareas> tareas;
private OnClickButton callback;
public TareasAdapter(Activity activity, ArrayList<Tareas> tareas) {
this.activity = activity;
this.tareas = tareas;
}
public void setCallback(OnClickButton callback) {
this.callback = callback;
}
public class UsuarioHolder extends RecyclerView.ViewHolder {
public TextView txtId;
public TextView txtNombreUsuario;
public TextView txtNota;
public TextView txtEstudiante;
public int pasId;
Button btnEliminar;
Button btnActualizar;
public UsuarioHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.txt_id);
txtNombreUsuario = (TextView) itemView.findViewById(R.id.txt_nombre_usuario);
txtNota = (TextView) itemView.findViewById(R.id.txt_nota);
txtEstudiante = (TextView) itemView.findViewById(R.id.txtEstudiante);
btnEliminar = (Button) itemView.findViewById(R.id.btnEliminar);
btnActualizar = (Button) itemView.findViewById(R.id.btnActualizar);
}
}
#Override
public UsuarioHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = activity.getLayoutInflater().inflate(R.layout.plantilla_usuariosegundo, parent, false);
UsuarioHolder holder = new UsuarioHolder(view);
holder.btnActualizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onClickUpdate();
}
});
holder.btnEliminar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onClickDelete();
}
});
return holder;
}
#Override
public void onBindViewHolder(final UsuarioHolder holder, int position) {
holder.txtId.setText(tareas.get(position).getId());
holder.txtNombreUsuario.setText("Tarea: " + tareas.get(position).getNombreTarea());
holder.txtNota.setText("Nota: " + tareas.get(position).getNota());
holder.txtEstudiante.setText("Estudiante: " + tareas.get(position).getEstudiante());
}
#Override
public int getItemCount() {
return tareas.size();
}
public interface OnClickButton {
void onClickUpdate();
void onClickDelete();
}
}
EDIT:
Now make the fragment that uses this adapter implement the interface OnClickButton. you'll then be able to manipulate the click events in the activity which is the right place to manipulate/communicate with fragments.
Finally after initializing the adapter call:
adapter.setCallback(this);
I try to add a swipe left or right to my RecyclerView List, but I don't know what I'm doing wrong. I've tried a lot of working solutions but they don't work for me.
This is my Fragment:
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import de.christian_heinisch.studenttodo.adapters.ToDoListRecyclerViewAdapter;
import de.christian_heinisch.studenttodo.database.ToDo;
import de.christian_heinisch.studenttodo.database.ToDoDataSource;
/**
* A simple {#link Fragment} subclass.
*/
public class ToDoFragment_RV extends Fragment {
View rootview;
private ToDoDataSource dataSource_todo;
private RecyclerView mRecyclerView;
private RecyclerView new_mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.LayoutManager new_mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
public ToDoFragment_RV() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.fragment_to_do_rv, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.rv);
mRecyclerView.setHasFixedSize(true);
LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(mRecyclerView);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ToDoListRecyclerViewAdapter(getContext(), getDataSet());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnFlingListener(snapHelper);
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
new_mRecyclerView = (RecyclerView) rootview.findViewById(R.id.rv_checked);
new_mRecyclerView.setHasFixedSize(true);
new_mLayoutManager = new LinearLayoutManager(getContext());
new_mRecyclerView.setLayoutManager(new_mLayoutManager);
mAdapter = new ToDoListRecyclerViewAdapter(getContext(), getDataSet_checked());
new_mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration newitemDecoration =
new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
new_mRecyclerView.addItemDecoration(newitemDecoration);
// setHasOptionsMenu(true);
FloatingActionButton fab = (FloatingActionButton) rootview.findViewById(R.id.fbToDoAdd);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((StartActivity)getContext()).DialogAddToDO();
}
});
return rootview;
}
private ArrayList<ToDo> getDataSet() {
dataSource_todo = new ToDoDataSource(getContext());
dataSource_todo.open();
ArrayList<ToDo> arrayOfToDo = null;
arrayOfToDo = dataSource_todo.getToDoForList("false");
dataSource_todo.close();
return arrayOfToDo;
}
private ArrayList<ToDo> getDataSet_checked() {
dataSource_todo = new ToDoDataSource(getContext());
dataSource_todo.open();
ArrayList<ToDo> arrayOfToDo = null;
arrayOfToDo = dataSource_todo.getToDoForList("true");
dataSource_todo.close();
return arrayOfToDo;
}
}
This is my RecyclerView Adapter
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import de.christian_heinisch.studenttodo.R;
import de.christian_heinisch.studenttodo.StartActivity;
import de.christian_heinisch.studenttodo.ToDoFragment_RV;
import de.christian_heinisch.studenttodo.database.ToDo;
import de.christian_heinisch.studenttodo.database.ToDoDataSource;
/**
* Created by chris on 16.06.2017.
*/
public class ToDoListRecyclerViewAdapter extends RecyclerView
.Adapter<ToDoListRecyclerViewAdapter
.DataObjectHolder> {
private ArrayList<ToDo> mDataset;
private static MyClickListener myClickListener;
private Context mContext;
ToDoDataSource dataSource = new ToDoDataSource(mContext);
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
TextView dateTime;
CheckBox checked;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView_item_todolist_content);
dateTime = (TextView) itemView.findViewById(R.id.textView_item_todolist_Date);
checked = (CheckBox) itemView.findViewById(R.id.cbToDo);
//itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ToDoListRecyclerViewAdapter(Context context, ArrayList<ToDo> myDataset) {
mDataset = myDataset;
mContext = context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_todolist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
holder.label.setText(mDataset.get(position).getToDo());
holder.dateTime.setText(getDate(mDataset.get(position).isDate()));
if(mDataset.get(position).isChecked().equalsIgnoreCase("true")){
holder.checked.toggle();
}
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
float _xSwipe1;
float _xSwipe2;
#Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
_xSwipe1 = event.getX();
break;
case MotionEvent.ACTION_UP:
_xSwipe2 = event.getX();
float deltaX = _xSwipe2 - _xSwipe1;
if (deltaX < 0)
{
Log.e("SWIPE", "Right to Left swipe");
}
else if (deltaX >0)
{
Log.e("SWIPE", "Left to right swipe");
}
break;
}
return false;
}
});
// Set onClicklistener
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
System.out.println("Position " + position);
edit(mDataset.get(position).getId());
//notifyDataSetChanged();
return false;
}
});
holder.dateTime.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
edit(mDataset.get(position).getId());
return false;
}
});
holder.checked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource = new ToDoDataSource(mContext);
dataSource.open();
// TODO Auto-generated method stub
if(holder.checked.isChecked()){
System.out.println("Checked");
dataSource.updateToDo(mDataset.get(position).getId(), mDataset.get(position).getToDo(), "true", mDataset.get(position).isDate());
}else{
System.out.println("un-Checked");
dataSource.updateToDo(mDataset.get(position).getId(), mDataset.get(position).getToDo(), "false", mDataset.get(position).isDate());
}
dataSource.close();
}
});
}
public void addItem(ToDo dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.GERMAN);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd.MM.yyyy", cal).toString();
return date;
}
private void edit(long l){
((StartActivity)mContext).DialogEditToDO(l);
}
}
Return true on case MotionEvent.ACTION_DOWN may resolve your issue.
Hi,Im trying to copy code from Activity to Fragment but it gives me error when i try to compile "cannot override onCreate(Bundle)". Here is my Activity code:
package com.candyshop.www.candyshop;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private GridLayoutManager gridLayoutManager;
private CustomAdapter adapter;
private List<MyData> data_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
data_list = new ArrayList<>();
load_data_from_server(0);
gridLayoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter = new CustomAdapter(this,data_list);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(gridLayoutManager.findLastCompletelyVisibleItemPosition() == data_list.size()-1){
load_data_from_server(data_list.get(data_list.size()-1).getId());
}
}
});
}
private void load_data_from_server(int id) {
AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.178.26/test/script.php?id="+integers[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
MyData data = new MyData(object.getInt("id"),object.getString("description"),
object.getString("image"));
data_list.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of content");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
}
And the code from my Fragment is
package com.candyshop.www.candyshop;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Reinhard Bonnke on 5/14/2017.
*/
public class females extends Fragment {
public females() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.tab1, container, false);
}
}
Can you please help me know how i can avoid this error or how i can copy the code to the fragment
This may help :https://developer.android.com/guide/components/fragments.html
Try this in your fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.tab1, container, false);
recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
data_list = new ArrayList<>();
load_data_from_server(0);
// more UI from your activity ....
return root;
}
I have a recyclerview with a couple of items. When someone clicks on an item in the Main Fragment, it is stored on sharedpreferences and then all clicked items are supposed to be displayed on another fragment. My issue is when someone clicks on an item, only the first clicked item is displayed on the other fragment(Details Fragment) instead of a list of items.
These are the methods of saving, retrieving and removing items on my SessionManager.class
public void saveitems(Context context,List<SingleItem> items){
Gson gson = new Gson();
String cartitems = gson.toJson(items);
editor.putString(KEY_ITEMS,cartitems);
editor.commit();
}
public void grandtotal (String total){
editor.putString(KEY_TOTAL,total);
editor.commit();
}
public void savetocart(Context context, SingleItem singleitems){
List<SingleItem> itemList = getItems(context);
if (itemList == null) {
itemList = new ArrayList<>();
itemList.add(singleitems);
saveitems(context, itemList);
}
}
public ArrayList<SingleItem> getItems(Context context){
List<SingleItem> items;
if (pref.contains(KEY_ITEMS)){
String cartitems = pref.getString(KEY_ITEMS,null);
Gson gson = new Gson();
SingleItem[] singleItems = gson.fromJson(cartitems,SingleItem[].class);
items = Arrays.asList(singleItems);
items = new ArrayList<>(items);
}
else
return null;
return (ArrayList<SingleItem>) items;
}
public void removeitem(Context context, SingleItem singleItem){
ArrayList<SingleItem> items = getItems(context);
if (items != null){
items.remove(singleItem);
saveitems(context,items);
}
}
This is how i am storing the items that have been clicked. Take a look at (RecyclerItems):
package com.carlton.shop;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ss.com.bannerslider.banners.RemoteBanner;
import ss.com.bannerslider.views.BannerSlider;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private BannerSlider bannerSlider;
private RecyclerView Categories;
public RecyclerView RecyclerItems;
private ShopItemAdapter adapter;
private List<ShopItem> item;
SessionManager sessionManager;
private List<SingleItem> items;
private SingleItemAdapter adapters;
private LinearLayout Layoutcategories, Layoutitems;
private TextView CatName;
private Button Up;
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
bannerSlider = (BannerSlider) view.findViewById(R.id.banner_slider1);
Categories = (RecyclerView) view.findViewById(R.id.recyclercategories);
Layoutcategories = (LinearLayout) view.findViewById(R.id.LayoutCategories);
Layoutitems = (LinearLayout) view.findViewById(R.id.LayoutItems);
RecyclerItems = (RecyclerView) view.findViewById(R.id.recycleritems);
CatName = (TextView) view.findViewById(R.id.tvcategoryname);
Up = (Button) view.findViewById(R.id.btnup);
sessionManager = new SessionManager(getContext());
Categories.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
Categories.setLayoutManager(layoutManager);
RecyclerItems.setHasFixedSize(true);
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
RecyclerItems.setLayoutManager(layoutmanager);
Categories.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Layoutcategories.setVisibility(View.GONE);
Layoutitems.setVisibility(View.VISIBLE);
sessionManager.createcategorysession(item.get(position).getCategory());
HashMap<String, String> cat = sessionManager.getcategoryitems();
CatName.setText(cat.get(SessionManager.KEY_CATEGORY));
Up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Layoutitems.setVisibility(View.GONE);
Layoutcategories.setVisibility(View.VISIBLE);
}
});
items = new ArrayList<>(item.get(position).getItems());
adapters = new SingleItemAdapter(getContext(),items);
RecyclerItems.setAdapter(adapters);
RecyclerItems.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sessionManager.savetocart(getContext(), items.get(position));
Toasty.success(getContext(),"Added to cart",Toast.LENGTH_SHORT,true).show();
}
}));
}
}));
Banner();
getdata();
return view;
}
private void Banner() {
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
}
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading Items...");
progressDialog.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfaceRequest request = retrofit.create(InterfaceRequest.class);
Call<JSONResponse> call =request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
if (response.isSuccessful()){
JSONResponse jsonResponse = response.body();
item = new ArrayList<>(jsonResponse.getItem());
adapter = new ShopItemAdapter(getContext(),item);
Categories.setAdapter(adapter);
} else {
Toasty.warning(getContext(),"Oops! Items could not be loaded",Toast.LENGTH_SHORT,true).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Toasty.error(getContext(),t.getLocalizedMessage(),Toast.LENGTH_SHORT,true).show();
Log.d(Constants.TAG,t.getMessage());
progressDialog.dismiss();
}
});
}
}
This is how i'm retrieving the items on DetailsFragment;
package com.carlton.shop;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import es.dmoral.toasty.Toasty;
import static com.helpshift.util.HelpshiftContext.getApplicationContext;
/**
* A simple {#link Fragment} subclass.
*/
public class Details extends Fragment {
private RecyclerView RecyclerDetails;
private TextView CartPrice;
private CheckBox CheckCart;
private List<SingleItem> list;
private CartAdapter adapter;
private boolean add = false;
private Paint p = new Paint();
private SessionManager sessionManager;
public Details() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_details, container, false);
RecyclerDetails = (RecyclerView) view.findViewById(R.id.recyclercart);
CartPrice = (TextView) view.findViewById(R.id.tvcart);
CheckCart = (CheckBox) view.findViewById(R.id.chkcart);
sessionManager = new SessionManager(getContext());
RecyclerDetails.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
RecyclerDetails.setLayoutManager(layoutManager);
list = sessionManager.getItems(getContext());
RecyclerDetails.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}));
if(list != null){
Toasty.info(getContext(),"Swipe to go to Next", Toast.LENGTH_LONG,true).show();
adapter = new CartAdapter(getContext(),list);
RecyclerDetails.setAdapter(adapter);
}
//initswipe();
return view;
}
}
In your session manager something's not right with the savetocart() method.
The first time it called, getItems() will return null as expected, therefore the if statement in the next line will resolve to true and an item will be added. But after that itemList will not be null, therefore the if statement will always resolve to false and no items are added to the list.
That method should look like this
public void savetocart(Context context, SingleItem singleitems){
List<SingleItem> itemList = getItems(context);
if (itemList == null) {
itemList = new ArrayList<>();
}
itemList.add(singleitems);
saveitems(context, itemList);
}