How to display json data in Recyclerview? - android

I want to display data from Mysql database in Recyclerview i use this codes but i get white page nothing show i don't know where error please help me to find error please explain your answer because i'm new in android this my codes
Mainactivity.java
RequestQueue requestQueue;
ArrayList<listitem_gib> rewayaList = new ArrayList<>();
private RecyclerView recyclerView;
ProgressBar progressBar;
LinearLayout progress_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardview);
TextView progress_txt = (TextView) findViewById(R.id.progress_txt);
progress_layout = (LinearLayout) findViewById(R.id.progress_layout);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
String url = "http://grassyhat.com/android/arabic.php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
progress_layout.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
String size = respons.getString("size");
rewayaList.add(new listitem_gib(id, name, img, url, num, size));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
//Just your list of objects, in your case the list that comes from the db
CardAdapter adapter = new CardAdapter(rewayaList, this);
//RecyclerView needs a layout manager in order to display data so here we create one
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//Here we set the layout manager and the adapter to the listview
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private List<listitem_gib> rewayaList;
Context context;
public CardAdapter(List<listitem_gib> rewayaList, Context context) {
super();
this.rewayaList = rewayaList;
this.context = context;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
CardViewHolder viewHolder = new CardViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewHolder holder, int position) {
//Here you bind your views with the data from each object from the list
listitem_gib rewaya = rewayaList.get(position);
holder.rewaya_name.setText(rewaya.name);
holder.writer_name.setText(rewaya.num);
}
#Override
public int getItemCount() {
return rewayaList.size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
public ImageView Image;
public TextView rewaya_name, writer_name;
public CardViewHolder(View itemView) {
super(itemView);
Image = (ImageView) itemView.findViewById(R.id.image);
rewaya_name = (TextView) itemView.findViewById(R.id.Main_Text);
writer_name = (TextView) itemView.findViewById(R.id.Second_Text);
}
}}
ListItem
public class listitem_gib {
public String id;
public String name;
public String img;
public String url;
public String num;
public String size;
public listitem_gib(String id, String name, String img, String url, String num, String size) {
this.id = id;
this.name = name;
this.img = img;
this.url = url;
this.num = num;
this.size = size;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}}

it is hard to look to your code in figure out the error
in this cases you have to break down you code and test every part alone
first check that the response is coming form the server properly by print the response via LOG or toast then check the parsing part when you have arrayLst
then populate the data to the recycler view

After
rewayaList.add(new listitem_gib(id, name, img, url, num, size));
Add
adapter.notifyDataSetChanged();
For detailed explanation visit Official Documentation for the function notifyDataSetChanged. It's just a few sentences so don't be scared that it might be a lengthy documentation.

Related

how to fetch a images from database using retrofit 2

Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database
Code is Here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
Intent intent = getIntent();
parent = intent.getStringExtra("Parent");
child = intent.getStringExtra("Child");
Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
//init firebase
//load menu
recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
apiInterface =
ApiClient.getRetrofit().create(ApiInterface.class);
recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
recycler_menu.setHasFixedSize(true);
mUploads = new ArrayList<>();
loadMenu();
}
private void loadMenu(){
Toast.makeText(Product.this, "Hello",
Toast.LENGTH_SHORT).show();
Call<Upload> call = apiInterface.performProduct(parent,child);
call.enqueue(new Callback<Upload>() {
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<Upload> call, Throwable t) {
}
});
}}
ImageAdapter.java .
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getImgName());
holder.textViewPrice.setText(uploadCurrent.getPrice());
Picasso.get()
.load(uploadCurrent.getImgUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
//holder.collection.setText(uploadCurrent.getmRadioGroup());
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener {
public TextView textViewName;
public TextView textViewPrice;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.menu_name);
textViewPrice = itemView.findViewById(R.id.menu_price);
imageView = itemView.findViewById(R.id.menu_price);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Upload.class
public class Upload {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#SerializedName("id")
private String id;
#SerializedName("image")
private String imgName;
#SerializedName("imgUrl")
private String imgUrl;
#SerializedName("price")
private String price;
#SerializedName("description")
private String Description;
#SerializedName("response")
private String Response;
public String getResponse(){
return Response;
}
public Upload() {
}
public Upload(String id,String imgName, String imgUrl, String price, String Description) {
this.id = id;
this.imgName = imgName;
this.imgUrl = imgUrl;
this.price = price;
this.Description = Description;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
PHP File:
<?php include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
$name = $data['name'];
$id = $data['id'];
$des = $data['description'];
$price = $data['price'];
$image = $data['image'];
$status = "ok";
echo
json_encode(array("response"=>$status,
"img"=>$image,"name"=>$name,
"id"=>$id,"description"=>$des,"price"=>$price));
}?>
this code does nothing a blank screen appers
You are sending blank ArrayList to Adapter
look here In onCreate() you assign mUploads = new ArrayList<>();
then you just pass mUploads to mAdapter = new ImageAdapter(Product.this, mUploads);
chnage code from
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
to ,
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mUploads=responese.body(); //# add this line
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
From your endpoint I got the following response
{"response":"ok","img":"greypant.jpg","name":"GreyPant","id":"1","description":"A very fine pant with great finishing.","price":"1500"}
you can try making the following edits to your PHP file to get the full path to the image file(s).
<?php
include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
$name = $data['name'];
$id = $data['id'];
$des = $data['description'];
$price = $data['price'];
$image = $data['image'];
$status = "ok";
echo json_encode(array("response"=>$status,
"img"=> "http://yourdomain.com/{$image}",
"name"=>$name,
"id"=>$id,
"description"=>$des,
"price"=>$price));
}
?>
replace http://yourdomain.com/ with the full path to the directory where your image is saved. Good luck!

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.

Order App - Android post array of values to database

I am creating an order app for part of a project I am working on. Basically, on one activity the user can view a list of all the items pulled from a database as a ListView. They also have a EditText field where they can enter the quantity they would like to order below each item.
I would like to have a submit button at the bottom of the screen which will then post the details of all the items ordered (i.e their item id) and the quantity being ordered however I am unsure how to do this.
Here is my current code:
public class OrderItems extends AppCompatActivity {
String menuID;
private TextView menuTitle;
ListView listView;
List<OrderItemList> listOrderItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_items);
menuTitle = findViewById(R.id.tvOrderMenuTitle);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
menuID = intent.getStringExtra("id");
menuTitle.setText(title);
listView = findViewById(R.id.list_order_items);
listOrderItems = new ArrayList<>();
displayItems();
}
private void displayItems(){
String url = "hidden";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("menuitems");
for (int i = 0; i < array.length(); i++) {
final JSONObject menuObj = array.getJSONObject(i);
OrderItemList o = new OrderItemList(menuObj.getString("menu_item_name"),
menuObj.getString("item_type"), menuObj.getInt("menu_item_price"), menuObj.getInt("menu_item_qty"));
listOrderItems.add(o);
}
OrderItemAdapter adapter = new OrderItemAdapter(listOrderItems, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OrderItems.this, "Oops! " +error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("menuid", menuID);
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
Displaying the items works fine although I am unable to type into the EditText box the quantity of the items to order, once I type it and then go to the next box, the previous value disappears.
The model class looks like this:
public class OrderItemList {
String Name, Type;
int Price, Qty;
public OrderItemList(String name, String type, int price, int qty) {
Name = name;
Type = type;
Price = price;
Qty = qty;
}
public String getName() {
return Name;
}
public int getQty() {
return Qty;
}
public String getType() {
return Type;
}
public int getPrice() {
return Price;
}
}
and the adapter:
public class OrderItemAdapter extends ArrayAdapter <OrderItemList>{
private List<OrderItemList> orderItemList1;
private Context context;
public OrderItemAdapter(List<OrderItemList> M, Context C){
super(C, R.layout.listorder, M);
this.orderItemList1 = M;
this.context = C;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.listorder,null,true);
TextView menuItemName = view.findViewById(R.id.tvItemName);
TextView menuItemPrice = view.findViewById(R.id.tvItemPrice);
TextView menuItemType = view.findViewById(R.id.tvItemType);
TextView menuItemQty = view.findViewById(R.id.tvItemQty);
OrderItemList orderItemList = orderItemList1.get(position);
menuItemName.setText(orderItemList.getName());
menuItemQty.setText("Available quantity: " +orderItemList.getQty());
menuItemPrice.setText("£" +orderItemList.getPrice());
if(position>0){
OrderItemList prevOrderItemList = orderItemList1.get(position-1);
if(!orderItemList.getType().equals(prevOrderItemList.getType())){
menuItemType.setText(orderItemList.getType());
}
} else {
menuItemType.setText(orderItemList.getType());
}
return view;
}
}
Any help/adivce would be greatly appreciated!

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 -how to bind the image loaded from picasso to recycler view

I have list of data in MenuItemsModel(model) class along with image url and two strings fetching from the API. How can I load the image url with Picasso and how to bind the loaded image to recyclerview?
Here is my code
Code for model class
public class MenuItemsModel {
public int image;
public String itemName;
public String itemCost;
public MenuItemsModel(int image, String itemName, String itemCost) {
this.image = image;
this.itemName = itemName;
this.itemCost = itemCost;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCost() {
return itemCost;
}
public void setItemCost(String itemCost) {
this.itemCost = itemCost;
}
}
Here is my RecyclerAdapter class
public class MenusRecyclearView extends
RecyclerView.Adapter<MenusRecyclearView.RecyclerViewHolder> {
Context context;
List<MenuItemsModel> menuItemsModel;
public MenusRecyclearView(Context context, List<MenuItemsModel> menuItemsModel) {
this.context = context;
this.menuItemsModel = menuItemsModel;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_items_list, parent, false);
return new RecyclerViewHolder(view, context, menuItemsModel);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.imageView.setImageResource(menuItemsModel.get(position).getImage());
holder.ItemName.setText(menuItemsModel.get(position).getItemName());
holder.ItemCost.setText(menuItemsModel.get(position).getItemCost());
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return menuItemsModel.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView imageView;
public TextView ItemName, ItemCost;
Context ctx;
List<MenuItemsModel> menuItemsModels;
public RecyclerViewHolder(View view, Context ctx, List<MenuItemsModel> menuItemsModels) {
super(view);
this.ctx = ctx;
this.menuItemsModels = menuItemsModels;
view.setOnClickListener(this);
imageView = view.findViewById(R.id.biriyani_menu_item);
ItemName = view.findViewById(R.id.item_name);
ItemCost = view.findViewById(R.id.item_cost);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
MenuItemsModel model = this.menuItemsModels.get(position);
Intent i = new Intent(this.ctx, CategoryDescription.class);
i.putExtra("ImageId", model.getImage());
i.putExtra("ItemName", model.getItemName());
i.putExtra("ItemCost", model.getItemCost());
this.ctx.startActivity(i);
}
}
}
** Here is my MainActivity class **
public class BiryanisActivity extends AppCompatActivity implements
View.OnClickListener, NetworkOperationListener{
RecyclerView recyclerView;
MenusRecyclearView menusRecyclearView;
RecyclerView.LayoutManager layoutManager;
List<MenuItemsModel> menuItemsModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.biriyanis_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
menuItemsModel = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclearview_menu);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
menusRecyclearView = new MenusRecyclearView(this, menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
HttpAdapter.getMenuItemsList(this,"MenuItemsList");
//prepareData();
}
/* public void prepareData() {
MenuItemsModel data = new MenuItemsModel(R.drawable.item5, "Chicken Dhum
Biriyani", "Rs.240");
menuItemsModel.add(data);
MenuItemsModel data1 = new MenuItemsModel(R.drawable.item2, "Chicken
Chilli Biriyani", "Rs.260");
menuItemsModel.add(data1);
MenuItemsModel data2 = new MenuItemsModel(R.drawable.item3, "Chicken
Tandhuri Biriyani", "Rs.280");
menuItemsModel.add(data2);
MenuItemsModel data3 = new MenuItemsModel(R.drawable.item4, "Chicken
Moghulai Biriyani", "Rs.230");
menuItemsModel.add(data3);
MenuItemsModel data4 = new MenuItemsModel(R.drawable.item1, "Chicken
Special Biriyani", "Rs.220");
menuItemsModel.add(data4);
MenuItemsModel data5 = new MenuItemsModel(R.drawable.item1, "Chicken
Mandi Biriyani", "Rs.210");
menuItemsModel.add(data5);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onClick(View view) {
}
#Override
public void operationCompleted(NetworkResponse response) {
if (response.getStatusCode() == 200) {
if (response.getTag().equals("MenuItemsList")) {
try {
JSONObject jsonObjects = new JSONObject(response.getResponseString());
if (jsonObjects.getString("Data").equals("null")) {
Toast.makeText(this, "No Data Found", Toast.LENGTH_SHORT).show();
return;
}
JSONArray jsonArray = jsonObjects.getJSONArray("Data");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
MenuItemsModel data = new Gson().fromJson(jsonObject.toString(),MenuItemsModel.class);
//Picasso.with(this).load(data.getImage()).into();
Picasso.with(this).load(data.getImage()).into(holder.imageView);
/* int image = data.getImage();
String name = data.getItemName();
String cost = data.getItemCost();
//picaso(image, imageView);*/
menuItemsModel.add(data);
}
MenusRecyclearView menusRecyclearView = new MenusRecyclearView(this,menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Failed to Connect Server, Please try again later", Toast.LENGTH_SHORT).show();
}
}
public void picaso(String path, ImageView imageView) {
if (!path.equals("")) {
Picasso.with(this).load(path).into(imageView);
}
}
}
Well, you are on the right track. You need to uncomment this line:
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
And, the .getImage() needs to become your URL. That means, you should store the image url inside MenuItemsModel. Now your image is an int, and should be of a type of String so you can pass the URL to it.
Also see this answer here:
https://stackoverflow.com/a/41157030/5457878

Categories

Resources