Retrofit 2 in a CustomView - android

In my code I am using an internet example that work fine using Retrofit2 and custom recyclerview but I decide to use this application in android starting at version 4.1.2 so the recyclerview doesn't work there. So, there is a possibility to change the custom recyclerview to a custom listview?
Lista_productos.java
public class Lista_productos extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<Elementos_fila_productos> elementos;
private RecyclerviewAdapter adapter;
private ApiInterface apiInterface;
static LayoutInflater layoutInflater;
static PopupWindow popupWindow;
static TextView nombre_seleccionado;
static FrameLayout frameLayout;
static String cantidad_deseada;
static char hola;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_productos);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview_tablillas);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
if(getIntent().getExtras() != null){
String type = getIntent().getExtras().getString("type");
buscarInformacion(type);
}
}
public void buscarInformacion(String type){
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<Elementos_fila_productos>> call = apiInterface.getElementosInfo(type);
call.enqueue(new Callback<List<Elementos_fila_productos>>() {
#Override
public void onResponse(Call<List<Elementos_fila_productos>> call, Response<List<Elementos_fila_productos>> response) {
elementos = response.body();
adapter = new RecyclerviewAdapter(elementos, Lista_productos.this);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<List<Elementos_fila_productos>> call, Throwable t) {
final AlertDialog.Builder builder = new AlertDialog.Builder(Lista_productos.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
builder.setCancelable(true);
builder.setTitle("Error!");
builder.setMessage("mensaje");
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
ListaComprasAdapter.java
public class ListaComprasAdapter extends BaseAdapter {
ArrayList<String> nombre;
ArrayList<String> cantidad;
ArrayList<String> precio;
ArrayList<String> total;
Context mContext;
//constructor
public ListaComprasAdapter(Context mContext, ArrayList<String> nombre, ArrayList<String> cantidad, ArrayList<String> precio, ArrayList<String> total) {
this.mContext = mContext;
this.nombre = nombre;
this.cantidad = cantidad;
this.precio = precio;
this.total = total;
}
public int getCount() {
return nombre.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View arg1, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.custom_lista_de_compras, viewGroup, false);
TextView Nombre = (TextView) row.findViewById(R.id.nombre_del_producto);
TextView Cantidad = (TextView) row.findViewById(R.id.cantidad);
TextView Precio = (TextView) row.findViewById(R.id.precio);
TextView Total = (TextView) row.findViewById(R.id.precio_total_producto);
Nombre.setText(nombre.get(position));
Cantidad.setText(cantidad.get(position));
Precio.setText(precio.get(position));
Total.setText(total.get(position));
return row;
}
}
Elementos_fila_productos.java : the elements of each row
public class Elementos_fila_productos {
#SerializedName("ID")
private String ID;
#SerializedName("Caracteristicas")
private String Caracteristicas;
#SerializedName("Precio")
private int Precio;
#SerializedName("Grosor")
private String Grosor;
#SerializedName("Disponibles")
private int Disponible;
#SerializedName("Imagen")
private String Imagen;
public String getGrosor() {
return Grosor;
}
public String getID() {
return ID;
}
public String getCaracteristicas() {
return Caracteristicas;
}
public int getPrecio() {
return Precio;
}
public int getDisponible() {
return Disponible;
}
public String getImagen() {
return Imagen;
}
}
ApiInterface.java
public interface ApiInterface {
#GET("tablillas2.php")
//revisar en el caso de que no funcione
Call<List<Elementos_fila_productos>> getElementosInfo(#Query("item_type") String item_type);
}
ApiClient.java
public class ApiClient {
public static final String Base_Url = "http://creadorjuancarloscfapptablilla.esy.es/appTablillas/";
public static Retrofit retrofit;
public static Retrofit getApiClient(){
if (retrofit==null){
retrofit = new Retrofit.Builder().baseUrl(Base_Url).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}

It looks like RecyclerView does work for Android 4.1.2. See the accepted answer for this question: Would recyclerview work on an android device with Jellybean?

Related

how to remove item from Recyclerview

friends...
In my project, I am creating a list of images from the server and showing in Recyclerview.
now I want to remove a particular item from the list when I click on the verify button.
I tried to hide holder.itemview but its see again when I scroll.
I just want to remove or hide that item which is verified once.
here is my code :
1) Main activity
public class MainActivity extends AppCompatActivity {
private static final String url = "www.mysite.com/api/api-id-list.php?action=imgs";
private ProgressDialog mDetailProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main_activity);
LoadRecyclerView();
}
private void LoadRecyclerView() {
mDetailProgress = new ProgressDialog(this);
mDetailProgress.setTitle("Loading images");
mDetailProgress.setMessage("Please Wait...");
mDetailProgress.setCanceledOnTouchOutside(false);
mDetailProgress.show();
final RecyclerView imgList = (RecyclerView) findViewById(R.id.imgList);
imgList.setLayoutManager(new LinearLayoutManager(this));
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Image[] images = gson.fromJson(response, Image[].class);
imgList.setAdapter(new ImageAdapter(MainActivity.this, images));
mDetailProgress.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Something went wrong..!", Toast.LENGTH_LONG);
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}}
2) ImageAdapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private ProgressDialog mDetailProgress;
private Context context;
private Image[] data;
Button btn_ban, btn_verify;
private View view;
public ImageAdapter (Context context, Image[] data) {
this.context = context;
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.single_item, parent, false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
final Image imagelist = data[position];
holder.userCode.setText(imagelist.getCode());
Glide.with(holder.userImage.getContext()).load(imagelist.getIdPhoto()).into(holder.userImage);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.itemView.setVisibility(View.GONE);
}
});
}
#Override
public int getItemCount() { return data.length; }
public class ImageViewHolder extends RecyclerView.ViewHolder {
TextView userCode;
ImageView userImage;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
userImage = (ImageView) itemView.findViewById(R.id.card_iv_img);
userCode = (TextView) itemView.findViewById(R.id.card_tv_code);
btn_ban = (Button) itemView.findViewById(R.id.btn_ban);
btn_verify = (Button) itemView.findViewById(R.id.btn_verify);
}
}}
3) Image.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Image {
#SerializedName("per_ID")
#Expose
private String perID;
#SerializedName("code")
#Expose
private String code;
#SerializedName("first_nm")
#Expose
private String firstNm;
#SerializedName("last_nm")
#Expose
private String lastNm;
#SerializedName("photo_ID")
#Expose
private String photoID;
#SerializedName("id_photo")
#Expose
private String idPhoto;
public String getPerID() {
return perID;
}
public void setPerID(String perID) {
this.perID = perID;
}
public Image withPerID(String perID) {
this.perID = perID;
return this;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Image withCode(String code) {
this.code = code;
return this;
}
public String getFirstNm() {
return firstNm;
}
public void setFirstNm(String firstNm) {
this.firstNm = firstNm;
}
public Image withFirstNm(String firstNm) {
this.firstNm = firstNm;
return this;
}
public String getLastNm() {
return lastNm;
}
public void setLastNm(String lastNm) {
this.lastNm = lastNm;
}
public Image withLastNm(String lastNm) {
this.lastNm = lastNm;
return this;
}
public String getPhotoID() {
return photoID;
}
public void setPhotoID(String photoID) {
this.photoID = photoID;
}
public Image withPhotoID(String photoID) {
this.photoID = photoID;
return this;
}
public String getIdPhoto() {
return idPhoto;
}
public void setIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
}
public Image withIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
return this;
}}
First make data not array, but List, so it's easy to remove item;
Secondly set listener for verify button inside ViewHolder and inside OnClick remove item and notify adapter.
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
data.remove(position);
notifyItemRemoved(position);
}
});
Note: Setting OnClickListener inside ViewHolder makes sure that only correct item is removed by using getAdapterPosition() to get correct position.
Position provided by onBindViewHolder might be invalid after new items are inserted.

views not populating in gridlayout recyclerview

I am trying to load data from an api online but am having an issue with the views loading. When I try to run the emulator, a blank screen shows up. Any idea why? I am guessing my issue is somewhere within how I am loading the gridview but I have not been able to figure it out.
MainActivity
public class MainActivity extends AppCompatActivity {
String SEARCH_TERM = "popular";
private RecyclerView mRecyclerView;
private MovieAdapter mMovieAdapter;
private GridLayoutManager gridLayoutManager;
private List<Movie> movieData;
/*
API KEY
https://api.themoviedb.org/3/movie/550?api_key=1f5029b7d824dee72f4d4a156dac90ed
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
movieData = new ArrayList<>();
loadMovieData();
}
private void loadMovieData() {
new FetchMovieTask().execute(SEARCH_TERM);
}
public class FetchMovieTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String MOVIES_RESULTS = "results";
final String MOVIES_POSTER_IMAGE = "poster_path";
final String MOVIES_TITLE = "title";
final String RELEASE_DATE = "release_date";
URL moviesUrl = NetworkUtils.buildUrl(SEARCH_TERM);
try {
String jsonMoviesResponse = NetworkUtils.getReponseFromHttpUrl(moviesUrl);
JSONObject moviesJson = new JSONObject(jsonMoviesResponse);
JSONArray moviesArray = moviesJson.getJSONArray(MOVIES_RESULTS);
for (int i = 0; i < moviesArray.length(); i++) {
String moviePoster;
String movieTitle;
String movieReleaseDate;
JSONObject movie = moviesArray.getJSONObject(i);
moviePoster = ("http://image.tmdb.org/t/p/w185/" + movie.getString(MOVIES_POSTER_IMAGE));
movieTitle = movie.getString(MOVIES_TITLE);
movieReleaseDate = movie.getString(RELEASE_DATE);
Log.i("MoviteTitle", movieTitle);
Log.i("ReleaseDate", movieReleaseDate);
Log.i("Image", moviePoster);
Movie data = new Movie(movieTitle, movieReleaseDate, moviePoster);
movieData.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mMovieAdapter.notifyDataSetChanged();
}
}
}
Adapter Class
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieAdapterViewHolder>{
private List<Movie> mMovieData;
private Context context;
public MovieAdapter(Context context, List<Movie> movieData) {
this.context = context;
this.mMovieData = movieData;
}
#Override
public void onBindViewHolder(#NonNull MovieAdapterViewHolder holder, int position) {
holder.mTitleTextView.setText(mMovieData.get(position).getTitle());
holder.mReleaseDateTextView.setText(mMovieData.get(position).getDate());
Picasso.with(context).load(mMovieData.get(position).getMoviePoster()).into(holder.mImageView);
}
#NonNull
#Override
public MovieAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.cardview_item, parent, false);
return new MovieAdapterViewHolder(view);
}
#Override
public int getItemCount() {
if (null == mMovieData)
return 0;
return mMovieData.size();
}
public class MovieAdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mTitleTextView;
public final TextView mReleaseDateTextView;
public final ImageView mImageView;
public MovieAdapterViewHolder(View itemView) {
super(itemView);
mTitleTextView = itemView.findViewById(R.id.title_text_view);
mReleaseDateTextView = itemView.findViewById(R.id.release_date_text_view);
mImageView = itemView.findViewById(R.id.image_data);
}
}
}
Movie Class
public class Movie {
private String Title;
private String Date;
private String MoviePoster;
public Movie(String title, String date, String moviePoster) {
Title = title;
Date = date;
MoviePoster = moviePoster;
}
public Movie() {
}
public String getTitle() {
return Title;
}
public String getDate() {
return Date;
}
public String getMoviePoster() {
return MoviePoster;
}
public void setTitle(String title) {
Title = title;
}
public void setDate(String date) {
Date = date;
}
public void setMoviePoster(String moviePoster) {
MoviePoster = moviePoster;
}
}
Info : Java is all pass by value.
Issue : you are passing empty list reference to adapter and later initialising the list but in adapter it is still null so adapter will never receive the added value in list so do
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
movieData = new ArrayList<>();
//^^^^^^^^^^^^^^^^^^^^^^^^^ do it before
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
loadMovieData();

Android Retrofit 2.1.0 Response.body() is null, status code is 404

I am trying to make a call to this api and am having difficulty as the response.body() is returning null.
http://demo.museum.vebrary.vn/api/stuff/getall
I want to get stuff name of list and show to my recyclerview.
My model:
public class SOAnswersResponse {
#SerializedName("StuffModels")
#Expose
private List<StuffModel> stuffModels = null;
public List<StuffModel> getStuffModels() {
return stuffModels;
}
public void setStuffModels(List<StuffModel> stuffModels) {
this.stuffModels = stuffModels;
}
and
public class StuffModel {
#SerializedName("STUFFID")
#Expose
private Integer sTUFFID;
#SerializedName("STUFFCODE")
#Expose
private String sTUFFCODE;
#SerializedName("STUFFNAME")
#Expose
private String sTUFFNAME;
#SerializedName("STUFFNOTE")
#Expose
private String sTUFFNOTE;
#SerializedName("STUFFORDER")
#Expose
private Integer sTUFFORDER;
#SerializedName("CUSTOMERID")
#Expose
private String cUSTOMERID;
#SerializedName("EXHIBITS")
#Expose
private List<Object> eXHIBITS = null;
Json response
{
"StuffModels":[
{
"STUFFID":2,
"STUFFCODE":"Gi",
"STUFFNAME":"Giấy",
"STUFFNOTE":"",
"STUFFORDER":2,
"CUSTOMERID":"CAMAU",
"EXHIBITS":[
]
},
ApiUtils Class
public class ApiUtils {
private ApiUtils() {
}
public static final String BASE_URL = "http://demo.museum.vebrary.vn/api/";
public static SOService getSOService() {
return RetrofitClient.getClient(BASE_URL).create(SOService.class);
}
}
Service interface
public interface SOService {
#GET("/stuff/getall")
Call<SOAnswersResponse> getAnswers();
}
RetrofitClient Class
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
My RecyclerView adapter
public class CategogyNameRecyclerViewAdapter extends RecyclerView.Adapter<CategogyNameRecyclerViewAdapter.ViewHolder> {
private List<StuffModel> mItems;
private Context mContext;
private PostItemListener mItemListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView titleTv;
PostItemListener mItemListener;
public ViewHolder(View itemView, PostItemListener postItemListener) {
super(itemView);
titleTv = itemView.findViewById(R.id.tvListMenuCategogy);
this.mItemListener = postItemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
StuffModel item = getItem(getAdapterPosition());
this.mItemListener.onPostClick(item.getSTUFFID());
notifyDataSetChanged();
}
}
public CategogyNameRecyclerViewAdapter(Context context, List<StuffModel> posts, PostItemListener itemListener) {
mItems = posts;
mContext = context;
mItemListener = itemListener;
}
#Override
public CategogyNameRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View postView = inflater.inflate(R.layout.item_list_text, parent, false);
ViewHolder viewHolder = new ViewHolder(postView, this.mItemListener);
return viewHolder;
}
#Override
public void onBindViewHolder(CategogyNameRecyclerViewAdapter.ViewHolder holder, int position) {
StuffModel item = mItems.get(position);
TextView textView = holder.titleTv;
textView.setText(item.getSTUFFNAME());
}
#Override
public int getItemCount() {
return mItems.size();
}
public void updateAnswers(List<StuffModel> items) {
mItems = items;
notifyDataSetChanged();
}
private StuffModel getItem(int adapterPosition) {
return mItems.get(adapterPosition);
}
public interface PostItemListener {
void onPostClick(long id);
}
}
And my main activity
public class Testttt extends AppCompatActivity {
private CategogyNameRecyclerViewAdapter mAdapter;
private RecyclerView mRecyclerView;
private SOService mService;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.test );
mService = ApiUtils.getSOService();
mRecyclerView = (RecyclerView) findViewById(R.id.rcvCategogyNameMenuTest);
mAdapter = new CategogyNameRecyclerViewAdapter(this, new ArrayList<StuffModel>(0), new CategogyNameRecyclerViewAdapter.PostItemListener() {
#Override
public void onPostClick(long id) {
Toast.makeText(Testttt.this, "Post id is" + id, Toast.LENGTH_SHORT).show();
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
mRecyclerView.addItemDecoration(itemDecoration);
loadAnswers();
}
public void loadAnswers() {
mService.getAnswers().enqueue(new Callback<SOAnswersResponse>() {
#Override
public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) {
Toast.makeText(Testttt.this, "333333333333333333"+response.body(), Toast.LENGTH_SHORT).show();
if(response.isSuccessful()) {
mAdapter.updateAnswers(response.body().getStuffModels());
Log.d("AnswersPresenter", "posts loaded from API");
}else {
int statusCode = response.code();
}
}
#Override
public void onFailure(Call<SOAnswersResponse> call, Throwable t) {
showErrorMessage();
Log.d("AnswersPresenter", "error loading from API");
}
});
}
public void showErrorMessage() {
Toast.makeText(this, "Error loading posts", Toast.LENGTH_SHORT).show();
}
}
The first thing that came in my mind:
Your
public static final String BASE_URL = "http://demo.museum.vebrary.vn/api/";
has a "/" at the the end and your
#GET("/stuff/getall")
Call<SOAnswersResponse> getAnswers();
starts with a "/". So there is a double backslash in the url that might leads to the 404 code. Does this solve the problem?
When i call your URL i receive XML. Maybe the API is not configured correctly?
Change your Service interface
public interface SOService {
#GET("stuff/getall")
Call<SOAnswersResponse> getAnswers();
}
it occurred because you have use start with backslash it already added in your base url

Picasso only loading single image but the size is 20

I am trying to make a service call with Retrofit and RxJava. I am using Picasso 2.5.2 to upload image from the API call. I am getting the image displayed, but i am getting single image only. When I debug, I get size as 20 but the displayed is single. Any help on that would be great.
The Adapter class:
public class PopularMoviesAdapter extends RecyclerView.Adapter<PopularMoviesAdapter.MoviesViewHolder> {
private final String TAG = PopularMoviesAdapter.class.getSimpleName();
private Context context;
private List<MoviesResponse> movieItems = new ArrayList<>();
public PopularMoviesAdapter(Context context, List<MoviesResponse> movieItems) {
this.context = context;
this.movieItems = movieItems;
}
#Override
public MoviesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movies_grid_item, parent, false);
return new MoviesViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
List<Movies> movies = movieItems.get(position).getResults();
String imageUrl = IntentKeys.MOVIES_POSTER_ENDPOINT + movies.get(position).getPosterPath();
Log.d(TAG, "Poster URL from the API call: " + imageUrl);
Picasso.with(context).load(imageUrl).into(holder.imageView);
Glide.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return movieItems.size();
}
class MoviesViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public MoviesViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.movies_grid_item_image);
}
}}
The fragment class:
public class PopularMoviesFragment extends Fragment {
private static final int COLUMN_COUNT = 2;
private List<MoviesResponse> responses;
private RecyclerView recyclerView;
private PopularMoviesAdapter popularMoviesAdapter;
private Subscription subscription;
private MoviesService service = RetrofitManager.getMoviesClient().create(MoviesService.class);
public PopularMoviesFragment() {
responses = new ArrayList<>();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular_movies, container, false);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(
getActivity(),
COLUMN_COUNT,
LinearLayoutManager.VERTICAL,
false);
recyclerView = (RecyclerView) view.findViewById(R.id.popular_movies_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(COLUMN_COUNT, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
return view;
}
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart() {
super.onStart();
getMoviesSubscription();
}
private void getMoviesSubscription() {
subscription = service.getPopularMovies(IntentKeys.POPULAR_MOVIES_API_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
new Action1<MoviesResponse>() {
#Override
public void call(MoviesResponse movies) {
responses.add(movies);
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
}
}, new Action0() {
#Override
public void call() {
displayPosters();
}
}
);
}
private void displayPosters() {
popularMoviesAdapter = new PopularMoviesAdapter(getContext(), responses);
recyclerView.setAdapter(popularMoviesAdapter);
recyclerView.invalidate();
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (subscription != null && subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
}
Finally the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/movies_grid_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/movies_grid_item_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
</LinearLayout>
POJO:
public class Movies implements Serializable {
private String posterPath;
private Boolean adult;
private String overview;
private String releaseDate;
private List<Integer> genreIds = new ArrayList<Integer>();
private Integer id;
private String originalTitle;
private String originalLanguage;
private String title;
private String backdropPath;
private Float popularity;
private Integer voteCount;
private Boolean video;
private Float voteAverage;
// getters and setters ommitted and constructor
}
public class MoviesResponse implements Serializable {
private Integer page;
private List<Movies> results = new ArrayList<Movies>();
private Integer totalResults;
private Integer totalPages;
// getters and setters ommitted and constructor
}
Thanks!
Try
Context context = holder.itemView.getContext();
in your onBindViewHolder, so that you don't pass context around.
Also try adding popularMoviesAdapter.notifyDataSetChanged() in your fragment. Do you mind uploading your POJO?
in your adapter
public PopularMoviesAdapter(List<Movie> movies) {
this.movies = movies;
}
in your fragment
.subscribe(
new Action1<MoviesResponse>() {
#Override
public void call(MoviesResponse movies) {
responses.add(movies.getResults());
popularMoviesAdapter.notifyDataSetChanged()
}
}
Change
#Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
List<Movies> movies = movieItems.get(position);
String imageUrl = IntentKeys.MOVIES_POSTER_ENDPOINT + movies.get(position).getPosterPath();
Log.d(TAG, "Poster URL from the API call: " + imageUrl);
Picasso.with(context).load(imageUrl).into(holder.imageView);
Glide.with(context).load(imageUrl).into(holder.imageView);
}
This is your code to set adapter
popularMoviesAdapter = new PopularMoviesAdapter(getContext(), responses); recyclerView.setAdapter(popularMoviesAdapter);
your ArrayList responses = new ArrayList() // this is your arraylist which you are providing to adapter
debug and check size of responses that how many records will return i think it has on one object
i think your array is somewhat like this
responses [{
0,{
}
}];
so passs
popularMoviesAdapter = new PopularMoviesAdapter(getContext(), responses.get(0).getResults
); recyclerView.setAdapter(popularMoviesAdapter);

Endless pagination listview Android with database

I need to implement an endless pagination listview in my code, I've searched online and I saw a lot of examples, but none of them is using database, my app does the following:
it connects to an API and retrieves the data with json and show it in a listview, ok that works fine, but I want that listview to have an infinite scroll, like the facebook one.
I don't want anyone to write the code for me, I'm asking to someone guide me on wich is the better way to achieve that, I'll share some of my code, so you can understand:
try {
//Repositorio is my database
Repositorio mRepositorio = new Repositorio(getActivity());
List listaDeClientes = mRepositorio.getClientes();
System.out.println(listaDeClientes);
TextView total = (TextView) rootView.findViewById(R.id.totalClientes);
total.setText(getTotalClientes(mRepositorio.getTotalRegistros("clientes")));
final ArrayAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item, listaDeClientes);
ListView lv = (ListView) rootView.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClienteModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(Context context, int resource, List<ClienteModel> objects) {
super(context, resource, objects);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClienteModel mClienteModel = getItem(position);
view = inflater.inflate(resourceId, parent, false);
TextView tvId = (TextView) view.findViewById(R.id.clienteId);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
tvId.setText(String.valueOf(mClienteModel.getClientes_id()));
tvNome.setText(mClienteModel.getNome());
tvTipo.setText(mClienteModel.getTipo());
return view;
}
}
Model:
public class ClienteModel implements Serializable {
private static final long serialVersionUID = 1L;
private Integer clientes_id;
private Integer id_rm;
private Integer credencial_id;
private String nome;
private String tipo;
private String informacao_adicional;
private String _criado;
private String _modificado;
private String _status;
public Integer getClientes_id() {
return clientes_id;
}
public void setClientes_id(Integer clientes_id) {
this.clientes_id = clientes_id;
}
public Integer getId_rm() {
return id_rm;
}
public void setId_rm(Integer id_rm) {
this.id_rm = id_rm;
}
public Integer getCredencial_id() {
return credencial_id;
}
public void setCredencial_id(Integer credencial_id) {
this.credencial_id = credencial_id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getInformacao_adicional() {
return informacao_adicional;
}
public void setInformacao_adicional(String informacao_adicional) {
this.informacao_adicional = informacao_adicional;
}
public String get_criado() {
return _criado;
}
public void set_criado(String _criado) {
this._criado = _criado;
}
public String get_modificado() {
return _modificado;
}
public void set_modificado(String _modificado) {
this._modificado = _modificado;
}
public String get_status() {
return _status;
}
public void set_status(String _status) {
this._status = _status;
}
public static String[] getColunas() {
return Colunas;
}
public static void setColunas(String[] colunas) {
Colunas = colunas;
}
public static String[] Colunas = new String[]{
Coluna.CLIENTES_ID,
Coluna.ID_RM,
Coluna.CREDENCIAL_ID,
Coluna.NOME,
Coluna.TIPO,
Coluna.INFORMACAO_ADICIONAL,
Coluna._CRIADO,
Coluna._MODIFICADO,
Coluna._STATUS
};

Categories

Resources