At the moment i am using custom adapter/recycle view to build a simple image and a small galery under the image, every time when i click on one of the images below it loads the image in the main imageView above.
My problem at the moment is, that everytime i click on the images on the galery i do a request for the image, i get the id of the clicked image and load again the image to display it above.
I don't like very well my solution, i want to get the bitmap of the clicked image and display it in the imageView above.
So in my main activity i do a simple request to get the main image, the rest of the images are loading in another reques of my activity that loads a recycle view with all images.
here is the activity:
public class PhotosForPlant extends AppCompatActivity implements IResult,PhotosForPlantsAdapter.OnItemClickListener {
RecyclerView recyclerView;
ArrayList<Photo> photos = new ArrayList<Photo>();
VolleyService mVolleyService;
IResult mResultCallback = null;
IResult mResultCallback2 = null;
final String GETREQUEST = "GETCALL";
PhotosForPlantsAdapter adapter;
String token;
TextView familyTxt;
TextView genreTxt;
TextView specieTxt;
TextView specieDescription;
ImageView plantImg;
int familyId;
int genreId;
String familyName;
String genreName;
Double lat = null;
Double lon = null;
Double alt = null;
String time = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
setContentView(R.layout.photos_for_plant);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);;
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
findViewById(R.id.user_ic2).setVisibility(View.GONE);
TextView toolbarText = (TextView) myToolbar.findViewById(R.id.toolbar_title);
toolbarText.setText("Dados planta");;
familyTxt = (TextView)findViewById(R.id.FamilyName);
genreTxt = (TextView)findViewById(R.id.GenreName);
specieTxt = (TextView)findViewById(R.id.SpecieName);
specieDescription = (TextView)findViewById(R.id.specieDescription);
plantImg = (ImageView)findViewById(R.id.plantImage);
token = checkForToken();
getAllPhotos();
getSpecificPlant();
}
private void getSpecificPlant() {
String id = getIntent().getExtras().getString("plantId");
final String URL = "http://109d0157.ngrok.io/plants/" + id;
getSpecificVolleyCallback();
mVolleyService = new VolleyService(mResultCallback2,this);
mVolleyService.getDataObjectVolley(GETREQUEST,URL,token);
}
private void getAllPhotos() {
String id = getIntent().getExtras().getString("plantId");
final String URL = "http://109d0157.ngrok.io/fotos/" + id + "/plants";
getFotosForPlantVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL,token);
recyclerView = (RecyclerView)findViewById(R.id.gallery);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5,GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
adapter = new PhotosForPlantsAdapter(getApplicationContext(), photos,this);
recyclerView.setAdapter(adapter);
}
private void getSpecificVolleyCallback() {
mResultCallback2 = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
try {
Log.d("ENTREIAQUI","ENTREI");
String specie = response.getString("specie");
loadImage(specie);
familyName = response.getJSONObject("genre").getJSONObject("family").getString("name");
genreName = response.getJSONObject("genre").getString("name");
genreId = response.getJSONObject("genre").getInt("id");
genreTxt.setText(genreName);
specieTxt.setText(specie);
familyTxt.setText(familyName);
specieDescription.setText(response.getString("description"));
familyId = response.getJSONObject("genre").getJSONObject("family").getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Log.d("ENTREIAQUI","ENTREI");
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("erro!",error.toString());
Log.d("ENTREIAQUI","ENTREI");
}
};
}
void getFotosForPlantVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Photo photo;
// iterate over the JSONArray response
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i); // get the individual object from JSONArray
Log.d("objeto",object.toString());
int id = Integer.parseInt(object.getString("id")); // get the unique identifier from the object
if(lat != null && lon != null && alt != null){
lat = Double.parseDouble(object.getString("lat"));
lon = Double.parseDouble(object.getString("lon"));
alt = Double.parseDouble(object.getString("altitude"));
}
time = object.getString("date");
String path = object.getString("image");
photo = new Photo(path,id,lat,lon,alt,time); // construct the object
photos.add(photo); // add the object to the arraylist so it can be used on the cardLayout
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("resposta",error.toString());
}
};
}
public void genrePressed(View view){
Intent i = new Intent(this,SpecieLibrary.class);
i.putExtra("id",String.valueOf(genreId));
i.putExtra("name",String.valueOf(genreName));
startActivity(i);
}
public void familyPressed(View view){
Intent i = new Intent(this,GenreLibrary.class);
i.putExtra("id",String.valueOf(familyId));
i.putExtra("name",String.valueOf(familyName));
startActivity(i);
}
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
}
#Override
public void notifyError(String requestType, VolleyError error) {
}
public String checkForToken() {
SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
String tokenKey = getResources().getString(R.string.token);
String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
return token;
}
public void loadImage(String specie){
String url = "http://109d0157.ngrok.io/images/" + specie + "/Thumbnail.jpg";
Picasso.with(PhotosForPlant.this)
.load(url)
.into(plantImg);
}
#Override
public void onRowClick(int position, int id,String path, View view) {
String url = "http://109d0157.ngrok.io/" + path;
Picasso.with(PhotosForPlant.this)
.load(url)
.into(plantImg);
}
}
the loadImage, is where i load the main image and then i have the onRowClick that comes from my custom adapter, i get the path of the clicked row there and so i load it again, but what i need is to get somehow the bitmap there and setImageResource on the plantImg.
Here is my adapter:
public class PhotosForPlantsAdapter extends RecyclerView.Adapter<PhotosForPlantsAdapter.ViewHolder> {
private ArrayList<Photo> photos;
private Context context;
private OnItemClickListener listener;
public interface OnItemClickListener {
void onRowClick(int position,int id,String path, View view);
}
public PhotosForPlantsAdapter(Context context, ArrayList<Photo> photos,OnItemClickListener listener) {
this.photos = photos;
this.context = context;
this.listener = listener;
}
#Override
public PhotosForPlantsAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.photos_for_plant_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final PhotosForPlantsAdapter.ViewHolder viewHolder, final int i) {
String urlFoto = photos.get(i).getPath();
String url = "http://109d0157.ngrok.io/" + urlFoto;
viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.with(context)
.load(url)
.resize(240, 120)
.centerInside()
.into(viewHolder.img);
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onRowClick(viewHolder.getAdapterPosition(),photos.get(i).getId(),photos.get(i).getPath(), view);
}
}
});
}
#Override
public int getItemCount() {
return photos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
public ViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
try to set Image in this way as bitmap
URL newurl = new URL("http://109d0157.ngrok.io/" + urlFoto);
mIcon_val=BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
viewHolder.img.setImageBitmap(mIcon_val);
and get Image in this way
Bitmap imgBitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
Related
I am developing an android app which shows a list of countries affected by Coronavirus , the total number of confirmed cases and total Deaths. I am using a JSON API to get the data and displaying it using a RecyclerView . The app works fine , and i get a list of all the countries with their respective case counts. I want to add a search option so that the users can filter the list and find a specific country. How do i do that? I am new to programming , if someone could help with this that would be awesome.
Here is the code snippet
MainActivity.java
private RecyclerView mRecyclerView;
private Corona_Stats_Adapter mCorona_Stats_Adapter;
private TextView mErrorDisplay;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.corona_stats);
mRecyclerView = (RecyclerView)findViewById(R.id.Corona_stats_recycler);
mErrorDisplay = (TextView) findViewById(R.id.tv_error_message_display);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mCorona_Stats_Adapter = new Corona_Stats_Adapter();
mRecyclerView.setAdapter(mCorona_Stats_Adapter);
mProgressBar = (ProgressBar)findViewById(R.id.pb_loading_indicator) ;
loadCoronaData();
}
private void loadCoronaData(){
showCoronaDataView();
//String Country = String.valueOf(mSearchQuery.getText());
new Fetch_data().execute();
}
private void showCoronaDataView(){
mErrorDisplay.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
private void showErrorMessage(){
mRecyclerView.setVisibility(View.INVISIBLE);
mErrorDisplay.setVisibility(View.VISIBLE);
}
public class Fetch_data extends AsyncTask<Void,Void,String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected String[] doInBackground(Void... voids) {
URL covidRequestURL = NetworkUtils.buildUrl();
try {
String JSONCovidResponse = NetworkUtils.getResponseFromHttpUrl(covidRequestURL);
String[] simpleJsonCovidData = CovidJSON_Utils.getSimpleStringFromJson(MainActivity.this, JSONCovidResponse);
return simpleJsonCovidData;
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String[] coronaData) {
mProgressBar.setVisibility(View.INVISIBLE);
if(coronaData !=null){
showCoronaDataView();
mCorona_Stats_Adapter.setCoronaData(coronaData);
} else{
showErrorMessage();
}
}
}
}
RecyclerView Adapter class Corona_stats_Adapter.java
public class Corona_Stats_Adapter extends RecyclerView.Adapter<Corona_Stats_Adapter.Corona_Stats_AdapterViewHolder>
{
private Context context;
// private List<Country> countryList;
// private List<Country> countryListFiltered;
private String[] mCoronaData;
public Corona_Stats_Adapter(){
}
#NonNull
#Override
public Corona_Stats_AdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int LayoutIdForListItem =R.layout.corona_stats_list_item;
LayoutInflater inflater =LayoutInflater.from(context);
boolean ShouldAttachToParentImmediately = false;
View view = inflater.inflate(LayoutIdForListItem,viewGroup,ShouldAttachToParentImmediately);
return new Corona_Stats_AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Corona_Stats_AdapterViewHolder corona_stats_adapterViewHolder, int position) {
String coronaStats = mCoronaData[position];
corona_stats_adapterViewHolder.mCoronaTextView.setText(coronaStats);
}
#Override
public int getItemCount() {
if(null == mCoronaData) return 0;
return mCoronaData.length;
// return countryListFiltered.size();
}
public class Corona_Stats_AdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mCoronaTextView;
public Corona_Stats_AdapterViewHolder(#NonNull View view) {
super(view);
mCoronaTextView = (TextView) view.findViewById(R.id.tv_corona_data);
}
}
public void setCoronaData(String[] coronaData){
mCoronaData = coronaData;
notifyDataSetChanged();
}
}
Parsing the JSON data in CovidJSON_Utils.java
public final class CovidJSON_Utils {
public static String[] getSimpleStringFromJson(Context context, String codivJsonString)
throws JSONException {
final String COV_COUNTRY = "Countries";
final String COV_CONFIRMED = "confirmed";
final String COV_DEATHS = "deaths";
final String COV_MESSAGE_CODE = "code";
String[] parsedCovidData = null;
JSONObject covidJsonObject = new JSONObject(codivJsonString);
if (covidJsonObject.has(COV_MESSAGE_CODE)) {
int errorCode = covidJsonObject.getInt(COV_MESSAGE_CODE);
switch (errorCode) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_NOT_FOUND:
return null;
default:
return null;
}
}
JSONArray countryCovidArray = covidJsonObject.getJSONArray(COV_COUNTRY);
parsedCovidData = new String[countryCovidArray.length()];
for (int i = 0; i < countryCovidArray.length(); i++) {
JSONObject countryJSONObject = countryCovidArray.getJSONObject(i);
String Country = countryJSONObject.getString("Country");
String Confirmed = String.valueOf(countryJSONObject.getInt("TotalConfirmed"));
String Deaths = String.valueOf(countryJSONObject.getInt("TotalDeaths"));
parsedCovidData[i] = Country + "- Cases " + Confirmed + "- Deaths " + Deaths;
}
return parsedCovidData;
}
}
The problem is with below initialization in the MainActivity.Oncreate method
mCorona_Stats_Adapter = new Corona_Stats_Adapter(this,countries);
Initialize the adapter in onPostExecute method with updated countries data.
Hope this will help you.
You have to set arraylist to update country data in adapter after getting data from the server.
Public void setCoronaData (Arraylist coronaData) {
countryList = coronaData;
notifyDataSetChanged ();
}
I am developing an app in android studio in which contents are coming form an Api in a recyclerview. In the api there is an element "content" that sends all html tags with images like a full page. I have to display that page in textview. I have tried Htm.fromHtml method but it is not displaying the images. I have searched all answers and got the solution of ImageGetter method, but I am not able to display dynamic content in the recycleradapter from ImageGetter. I have to keep the images in the drawable of my app and match the source URL that is being parsed. Please help. Below is my code.
PageActivity.java
public class PageActivity extends AppCompatActivity {
RequestQueue queue;
String menuidpage;
RecyclerView recyclerView;
List<MenuFeeds> feedsList = new ArrayList<MenuFeeds>();
String newimage = "http://www.groveus.com/micro/assets/uploads/page/";
PageRecyclerAdapter adapter;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle bundle=getIntent().getExtras();
menuidpage=bundle.getString("page_id");
recyclerView = (RecyclerView) findViewById(R.id.recyclerviewpage);
pDialog = new ProgressDialog(this);
adapter = new PageRecyclerAdapter(this, feedsList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
//Getting Instance of Volley Request Queue
queue = NetworkController.getInstance(this).getRequestQueue();
//Volley's inbuilt class to make Json array request
pDialog.setMessage("Loding...");
pDialog.show();
String url = "http://www.groveus.com/micro/api/index.php/pages/view?
id="+menuidpage;
JsonArrayRequest menuReq = new JsonArrayRequest(url, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pDialog.dismiss();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MenuFeeds feeds = new MenuFeeds(obj.getInt("page_id"),
obj.getString("status"), obj.getString("title"),
newimage+obj.getString("image"),obj.getString("content"));
// adding movie to movies array
feedsList.add(feeds);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
//Notify adapter about data changes
adapter.notifyItemChanged(i);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
pDialog.dismiss();
}
});
//Adding JsonArrayRequest to Request Queue
queue.add(menuReq);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
PageRecyclerAdapter.java
public class PageRecyclerAdapter extends
RecyclerView.Adapter<PageRecyclerAdapter.MyViewHolder> implements
View.OnTouchListener
{
private List<MenuFeeds> feedsList;
private Context context;
private LayoutInflater inflater;
public PageRecyclerAdapter(Context context, List<MenuFeeds> feedsList) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.list_layout5, parent, false);
return new MyViewHolder(rootView);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final MenuFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
//holder.idmenu.setText(feeds.getMenuId());
//holder.title.setText(feeds.getFeedName());
/* holder.description.setText(Html.fromHtml(feeds.getDescription(), 0,
new Html.ImageGetter() {
#Override
public Drawable getDrawable(String s) {
int id;
if
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT
INFECTION 1.png")) {
id = R.drawable.urin1;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT
INFECTION 2.png")) {
id = R.drawable.urin2;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE
INFECTION 1.png")) {
id = R.drawable.skinsoft1;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE
INFECTION 2.png")) {
id = R.drawable.skinsoft2;
}
else if
(s.equals("http://groveus.com/micro/assets/images/RESPIRATORY TRACT
INFECTION.png")) {
id = R.drawable.respo;
}
else if (s.equals("http://groveus.com/micro/assets/images/LOCAL
BACTERIAL INFECTIONS.png")) {
id = R.drawable.local;
}
else if
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION
2nd 1.png")) {
id = R.drawable.urine2nd1;
}
else if
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION
2nd 2.png")) {
id = R.drawable.urine2nd2;
}
else if
(s.equals("http://groveus.com/micro/assets/images/table.png")) {
id = R.drawable.table;
}
else if
(s.equals("http://www.groveus.com/micro/assets/images/table 2.png")) {
id = R.drawable.table2;
}
else {
return null;
}
Drawable d = context.getResources().getDrawable(id);
d.setBounds(0,0,1020,600);
return d;
}
}, null));*/
holder.description.setText(Html.fromHtml(feeds.getDescription()));
holder.description.setOnTouchListener(this);
holder.description.setMovementMethod(new ScrollingMovementMethod());
holder.imageview.setImageUrl(feeds.getImgURL(),
NetworkController.getInstance(context).getImageLoader());
// holder.ratingbar.setProgress(feeds.getRating());
}
#Override
public int getItemCount() {
return feedsList.size();
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title,description;
private NetworkImageView imageview;
//private ProgressBar ratingbar;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.ImageNameTextView);
description = (TextView) itemView.findViewById(R.id.desc);
//idmenu = (TextView) itemView.findViewById(R.id.ImageNameTextView2);
UrlImageParser p=new UrlImageParser(description,context);
// Volley's NetworkImageView which will load Image from URL
imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
MenuFeeds.java
public class MenuFeeds
{
private String imgURL, feedName, description,page;
//private String id;
private int id;
public MenuFeeds(int menuid, String page, String name, String imgurl,String
desc) {
this.id=menuid;
this.page=page;
this.feedName = name;
this.imgURL = imgurl;
this.description = desc;
//this.rating = rating;
}
public int getMenuId() {
return id;
}
public String getPageID()
{
return page;
}
public String getDescription() {
return description;
}
public String getImgURL() {
return imgURL;
}
public String getFeedName() {
return feedName;
}
}
I also faced a similar problem month ago and used this and it works fine :
String htmlData = listData.get(position).getValue();
String showData = htmlData.replace("\n", "");
URLImageParser p = new URLImageParser(holder.textt, context);
Spanned htmlAsSpanned = Html.fromHtml(showData,p,null);
holder.yourTextView.setText(htmlAsSpanned);
Now copy and paste these 2 methods :
First method :
public class URLDrawable extends BitmapDrawable {
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
if(drawable != null) {
drawable.draw(canvas);
}
}
}
///Second Method :
public class URLImageParser implements Html.ImageGetter {
Context c;
TextView container;
/***
* Construct the URLImageParser which will execute AsyncTask and refresh the container
* #param t
* #param c
*/
public URLImageParser(TextView t, Context c) {
this.c = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
#Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
#Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.container.invalidate();
URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
+ result.getIntrinsicHeight()));
}
/***
* Get the Drawable from URL
* #param urlString
* #return
*/
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} `enter code here`catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
}
try this
load your image using piccaso
add below library in your build.gradle
implementation 'com.squareup.picasso:picasso:2.71828'
when you need to set image use piccaso this way
Picasso.get()
.load(your_image)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.your_error_image_or_blank)
.into(your_imageView);
This is Fist time i'm asking question!! so bear with me.
The application is project(popular movie stage 2) from udacity where i need to fetch info of movies like tilte or poster_path or backdrop_path.
so when i fetch data from json it works perfectly fine but when i add another argument String backdrop in my Movies.java class.then getmBackdrop() shows empty and i couldn't get the data of backdrop overview and vote.but if i delete backdrop from constructor than it works fine. i dont know what is happening please help me.
this is Movies.javaclass
public class Movies implements Parcelable {
//Movies Data
public long mID;
private String mPosterPath;
private String mReleaseDate;
private String mTitle;
private String mVote;
private String mOverview;
private String mBackdrop;
private ArrayList<Trailers> trailers;
private ArrayList<Reviews> reviews;
public Movies() {
}
public Movies(String title, String releaseDate, String posterPath,
String backdrop,String vote, String overview) {
// this.mID=id;
this.mTitle = title;
this.mReleaseDate = releaseDate;
this.mPosterPath = posterPath;
this.mBackdrop = backdrop;
this.mVote = vote;
this.mOverview = overview;
this.trailers = new ArrayList<>();
this.reviews = new ArrayList<>();
}
public long getID(){ return mID ;}
public String getmBackdrop() { return mBackdrop; }
public String getPosterPath() {
return mPosterPath;
}
public String getTitle() {
return mTitle;
}
public String getReleaseDate() {
return mReleaseDate;
}
public String getOverview() {
return mOverview;
}
public String getVote() {
return mVote +"/10";
}
public void setTrailers(ArrayList<Trailers> trailers) {
this.trailers = trailers;
}
public void setReviews(ArrayList<Reviews> reviews) {
this.reviews = reviews;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(mID);
dest.writeString(mTitle);
dest.writeString(mReleaseDate);
dest.writeString(mPosterPath);
dest.writeValue(mBackdrop);
dest.writeString(mVote);
dest.writeString(mOverview);
}
protected Movies(Parcel in) {
mID = in.readLong();
mTitle = in.readString();
mReleaseDate = in.readString();
mPosterPath = in.readString();
mBackdrop = in.readString();
mVote = in.readString();
mOverview = in.readString();
}
public static final Creator<Movies> CREATOR = new Creator<Movies>() {
public Movies createFromParcel(Parcel source) {
return new Movies(source);
}
public Movies[] newArray(int size) {
return new Movies[size];
}
};
}
MoviepediaJsonUtils.java where i'm parsing data
public class MoviepediaJsonUtils {
public static ArrayList<Movies> getParseMovieJson(String jsonMovies) throws JSONException {
final String IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
final String BACKDROP_URL= "https://image.tmdb.org/t/p/w1280/";
JSONObject movieJson = new JSONObject(jsonMovies);
JSONArray movieArray = movieJson.getJSONArray("results");
ArrayList<Movies> movieArrayList = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movieObject = movieArray.getJSONObject(i);
long id = movieObject.getLong("id");
String title = movieObject.getString("title");
String release_date = movieObject.getString("release_date");
String poster_path = movieObject.getString("poster_path");
String backdrop = movieObject.getString("backdrop_path");
String vote_average = movieObject.getString("vote_average");
String overview = movieObject.getString("overview");
Movies movies = new Movies(title, release_date,
IMAGE_BASE_URL + poster_path, BACKDROP_URL+backdrop,vote_average, overview);
movieArrayList.add(movies);
}
return movieArrayList;
}
public static String getResponseFromHttpUrl(InputStream stream) throws IOException {
Scanner scanner = new Scanner(stream);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
}
}
MainActivityFragments.java
public class MainActivityFragments extends Fragment {
private static final int COLUMN = 2;
private RecyclerView mRecyclerView;
SharedPreferences mSettings;
GridLayoutManager mGridLayoutManager;
private SharedPreferences.Editor mEditor;
private static final String SHARED_KEY_SORT = "sort";
private static final String POPULARITY = "popular";
private static final String RATINGS = "top_rated";
public static String[] backdrop;
public static final String SAVE_LAST_UPDATE_ORDER = "save_last_update_order";
private String mLastUpdateOrder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.poster_fragment, container, false);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mGridLayoutManager = new GridLayoutManager(getActivity(),2, LinearLayoutManager.VERTICAL,false);
}else{
mGridLayoutManager = new GridLayoutManager(getActivity(), 4,LinearLayoutManager.VERTICAL,false);
}
mRecyclerView = view.findViewById(R.id.rv_movies);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSettings.edit();
mEditor.apply();
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), new ArrayList<Movies>()));
return view;
}
#Override
public void onStart() {
super.onStart();
if (needToUpdateUi()) {
updateUi();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVE_LAST_UPDATE_ORDER, mLastUpdateOrder);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mLastUpdateOrder = savedInstanceState.getString(SAVE_LAST_UPDATE_ORDER);
}
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
updateUi();
}
// OnCreateOptionMenues will be here
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.poster_fragment, menu);
Drawable drawable = menu.findItem(R.id.icon).getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}
}
// OnOptionitemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.poularity:
mEditor.putString(SHARED_KEY_SORT, POPULARITY);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
case R.id.top_rated:
mEditor.putString(SHARED_KEY_SORT, RATINGS);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
if (sortBy.equals(POPULARITY)) {
menu.findItem(R.id.poularity).setChecked(true);
} else {
menu.findItem(R.id.top_rated).setChecked(true);
}
}
private void updateUi() {
if (isNetworkAvailable()) {
OnTaskCompleted taskCompleted = new OnTaskCompleted() {
#Override
public void onFetchMoviesTaskCompleted(ArrayList<Movies> movies) {
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), movies));
}
};
MoviesAsyncTask moviesAsyncTask = new MoviesAsyncTask(taskCompleted);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
mLastUpdateOrder = sortBy;
moviesAsyncTask.execute(sortBy);
} else {
Toast.makeText(this.getActivity().getApplicationContext(), "Need Internet Connection", Toast.LENGTH_LONG).show();
}
}
private boolean needToUpdateUi() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (!mLastUpdateOrder.equals(prefs.getString(SHARED_KEY_SORT, POPULARITY))) {
return true;
} else {
return false;
}
}
//Based on a stackoverflow snippet
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) this.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
DeatailActivityFragment
public class DetailActivityFragments extends Fragment {
private final String TAG = this.getClass().getSimpleName();
private static final String PARCEL_KEY = "movie_parcel";
Movies mMovie;
OnTaskCompleted mlistener;
ArrayList<Trailers> mTrailers;
ArrayList<Reviews> mReviews;
ImageView poster;
ImageView backdrop;
public DetailActivityFragments() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_detail_fragment,
container, false);
Movies parceableExtra = getActivity().getIntent().getParcelableExtra(PARCEL_KEY);
poster = view.findViewById(R.id.poster_IV);
TextView title = view.findViewById(R.id.title_TV);
TextView releaseDate = view.findViewById(R.id.relaesedate_TV);
TextView vote = view.findViewById(R.id.vote_TV);
TextView overView = view.findViewById(R.id.overview_TV);
backdrop = view.findViewById(R.id.image_id);
final FloatingActionButton fab1 = view.findViewById(R.id.fab);
//String gotPosition = getStringExtra("position");
//intGotPosition=Integer.parseInt(gotPosition);
// String url = "https://image.tmdb.org/t/p/w1280"+DetailActivityFragments.backdrop[intGotPosition];
title.setText(parceableExtra.getTitle());
releaseDate.setText(parceableExtra.getReleaseDate());
vote.setText(parceableExtra.getVote());
overView.setText(parceableExtra.getOverview());
Picasso.with(view.getContext()).load(parceableExtra.getPosterPath())
.into(poster);
Picasso.with(this.getActivity()).load( parceableExtra.getmBackdrop())
.error(R.drawable.sam).into(backdrop);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent i=new Intent(context , TrailerActivity.class);
startActivity(i);
}
});
return view;
}
}
MoviesAsyncTask.java
public class MoviesAsyncTask extends AsyncTask<String, Void, ArrayList<Movies>> {
private final String LOG_TAG = MoviesAsyncTask.class.getSimpleName();
final String MY_API_KEY = "removed deliberately";
ArrayList<Movies> mMovies;
private OnTaskCompleted mListener;
public MoviesAsyncTask(OnTaskCompleted listener) {
mListener = listener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Movies> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
final String MOVIEDB_BASE_URL =
"https://api.themoviedb.org/3/movie/";
final String APIKEY = "api_key";
Uri builtUri = Uri.parse(MOVIEDB_BASE_URL).buildUpon()
.appendPath(params[0])
.appendQueryParameter(APIKEY, MY_API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String response = null;
try {
response = MoviepediaJsonUtils.getResponseFromHttpUrl(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
return MoviepediaJsonUtils.getParseMovieJson(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Movies> movies) {
super.onPostExecute(movies);
mListener.onFetchMoviesTaskCompleted(movies);
mMovies = movies;
}
}
Try to add your string at the end of your class or remove all the parcelable generated code, add your string, then apply again the parcelable implementation.
This happens because you're not updating the parcel methods.
I'm using Volley to fetch data from a json array and I'm facing some real problems on loading more data! I've set OFFSET in my SQL Query to send 10 item, each time Android send a page number to get more data! It works perfectly and I've already tested my php codes with Postman application and there is no problem with that! I guess something is wrong about my recyclerview or the way I'm fetching data from server that cause out of memory issue! so please if you take a look at my code probably you could find the problem!
here is my code:
My Adapter:
public class ReviewsAdapter extends RecyclerView.Adapter<ReviewsAdapter.ReviewsHolder> {
private Context context;
private ArrayList<ReviewsList> reviewsList;
public ReviewsAdapter(ArrayList<ReviewsList> reviewsList, Context context) {
this.reviewsList = reviewsList;
this.context = context;
}
#Override
public ReviewsAdapter.ReviewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ReviewsAdapter.ReviewsHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_reviews, parent, false));
}
private float f;
#Override
public void onBindViewHolder(ReviewsAdapter.ReviewsHolder holder, int position) {
holder.userName.setText(reviewsList.get(position).getSentBy());
for (f = 0.0f; f <= 5.0f; f += 0.5f) {
if (f == Float.valueOf(reviewsList.get(position).getRate())) {
holder.ratingBar.setRating(f);
}
}
holder.date.setText(reviewsList.get(position).getDate());
holder.Ctext.setText(reviewsList.get(position).getCText());
}
#Override
public int getItemCount() {
return reviewsList.size();
}
class ReviewsHolder extends RecyclerView.ViewHolder {
TextView userName, date;
JustifiedTextView Ctext;
RatingBar ratingBar;
ReviewsHolder(View view) {
super(view);
userName = view.findViewById(R.id.userName);
ratingBar = view.findViewById(R.id.commentRate);
date = view.findViewById(R.id.commentDate);
Ctext = view.findViewById(R.id.commentText);
}
}
}
List.java:
public class ReviewsList {
private int Cid;
private String sentBy, rate, date, Ctext;
public ReviewsList(int Cid, String sentBy, String rate, String date, String Ctext) {
this.sentBy = sentBy;
this.rate = rate;
this.date = date;
this.Ctext = Ctext;
this.Cid = Cid;
}
public String getSentBy() {
return sentBy;
}
public String getRate() {
return rate;
}
public String getDate() {
return date;
}
public String getCText() {
return Ctext;
}
}
My Activity:
public class ReviewsActivity extends AppCompatActivity {
private int page = 0;
private boolean itShouldLoadMore = true;
private RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
private ArrayList<ReviewsList> reviewsLists;
private ReviewsAdapter reviewsAdapter;
TextView noMoreData;
NestedScrollView nestedScrollView;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviews);
noMoreData = findViewById(R.id.NoMoreDataTxt);
reviewsLists = new ArrayList<>();
reviewsAdapter = new ReviewsAdapter(reviewsLists, getApplicationContext());
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView = findViewById(R.id.RecyclerView);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(reviewsAdapter);
firstLoadData();
recyclerView.setNestedScrollingEnabled(false);
nestedScrollView = findViewById(R.id.nestedScrollView);
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
int totalItemCount = linearLayoutManager.getItemCount();
int lastVisible = linearLayoutManager.findLastVisibleItemPosition();
boolean endHasBeenReached = lastVisible + 5 >= totalItemCount;
if (totalItemCount > 0 && endHasBeenReached) {
loadMore();
}
}
});
recyclerView.setNestedScrollingEnabled(false);
}
public void firstLoadData() {
String url = "https://oh-music.ir/parastar/get_reviews.php?page=1" + "&nurseId=" + theId;
itShouldLoadMore = false;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
itShouldLoadMore = true;
if (response.length() <= 0) {
noMoreData.setVisibility(View.VISIBLE);
return;
}
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
int id = jsonObject.getInt("id");
String sent_by = jsonObject.getString("sent_by");
String rate = jsonObject.getString("rate");
String date = jsonObject.getString("date");
String text = jsonObject.getString("text");
reviewsLists.add(new ReviewsList(id, sent_by, rate, date, text));
reviewsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
itShouldLoadMore = true;
String message = "";
new VolleyErrorHandler(getApplicationContext(), error, message);
}
});
//Pay Attention to this line is this causing the crashing?
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void loadMore() {
String url = "https://oh-music.ir/parastar/get_reviews.php?action=loadmore&page=" + String.valueOf(page++) + "&nurseId=" + theId;
itShouldLoadMore = false;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
itShouldLoadMore = true;
if (response.length() <= 0) {
noMoreData.setVisibility(View.VISIBLE);
return;
}
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
int id = jsonObject.getInt("id");
String sent_by = jsonObject.getString("sent_by");
String rate = jsonObject.getString("rate");
String date = jsonObject.getString("date");
String text = jsonObject.getString("text");
reviewsLists.add(new ReviewsList(id, sent_by, rate, date, text));
reviewsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
itShouldLoadMore = true;
String message = "";
new VolleyErrorHandler(getApplicationContext(), error, message);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen()) {
drawer.closeDrawer();
} else {
super.onBackPressed();
}
}
}
As you may ask for logcat errors, I've to say that there are lots of errors but not with red color! Here is some of them:
It starts like this:
Continues like this for about 100 lines of code:
And ends with these:
I will really appreciate your help ♥ Thanks for your time...
EDIT: I've to say that when recyclerview reaches the end and tries to load more data, it reproduce the previous items again! for example if there are 7 items it load 7 more items (the same items). and after some scroll up and down the app crashes.
I would say that this happens because you're disabling nested scrolling of the RecyclerView and also putting the RecyclerView inside the NestedScrollView resulting in the RecyclerView to load all the items at once and not to recycle any views which result in OOM and performance issues.
Solution:
Remove the NestedScrollView and set the ScrollListener on the RecyclerView directly.
Delete recyclerView.setNestedScrollingEnabled(false);
I am getting json values from volley post request. I am adding those values to list using setter method. When i am retrieving values in adapter onBindViewholder() method and displaying it in a recyclerview result is not getting displayed as expected:
Below code refers to adding values to list from volley request and response in MainActivity.java:
private ProductsPojo pojo;
public static ProductsAdapter productsAdapter;
private List<ProductsPojo> pojoList;
pojo = new ProductsPojo();
pojoList = new ArrayList<>();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Appet8","Products response:"+response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray products = jsonObject.getJSONArray("products");
for (int i=0;i<products.length();i++) {
JSONObject product_object = products.getJSONObject(i);
String name = product_object.getString("name");
String price = product_object.getString("price");
String product_id = product_object.getString("id");
String sessionname = product_object.getString("sessionname");
String image = product_object.getString("image");
String categoryname = product_object.getString("categoryname");
pojo.setName(product_object.getString("name"));
pojo.setImage(product_object.getString("image"));
pojoList.add(pojo);
}
productsAdapter = new ProductsAdapter(pojoList,getApplicationContext());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("customer_id", customer_id);
return params;
}
};
AppController.getInstance().addToRequestQueue(request,tag_request);
Below code refers to setting adapter to recyclerview in a ProductFragment.java:
private GridLayoutManager layoutManager;
private RecyclerView recyclerView;
recyclerView = (RecyclerView) view.findViewById(R.id.productList);
recyclerView.setHasFixedSize(true);
layoutManager = new GridLayoutManager(getActivity().getApplicationContext(),3);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(MainActivity.productsAdapter);
Below code refers to adapter class which displays values, ProductsAdapter.java:
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductsViewHolder> {
private List<ProductsPojo> productList;
private Context context;
public ProductsAdapter(List<ProductsPojo> productList,Context context) {
this.productList=productList;
this.context = context;
}
#Override
public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.products_list, parent, false);
ProductsViewHolder holder = new ProductsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductsViewHolder holder,final int position) {
final ProductsPojo pojo = productList.get(position);
Log.d("Appet8","Name:"+pojo.getName());
holder.vTitle.setText(pojo.getName());
holder.vTitle.setTypeface(MainActivity.font);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pojo.setSelected(!pojo.isSelected());
holder.itemView.setBackgroundColor(pojo.isSelected() ? Color.parseColor("#4D79CF08") : Color.parseColor("#2D6F6F6F"));
if(pojo.isSelected()) {
holder.selected.setVisibility(View.VISIBLE);
} else if(!pojo.isSelected()) {
holder.selected.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public static class ProductsViewHolder extends RecyclerView.ViewHolder {
protected TextView vTitle;
protected ImageView image,selected;
protected CardView product_card;
public ProductsViewHolder(View v) {
super(v);
vTitle = (TextView) v.findViewById(R.id.title);
image = (ImageView) v.findViewById(R.id.product);
product_card = (CardView) v.findViewById(R.id.product_card);
selected = (ImageView) v.findViewById(R.id.selected);
}
}
}
This is the response that i get from volley request:
{
"products":[
{
"name":"Idli",
"price":"120",
"id":"Fi2mYuQA",
"sessionname":"Breakfast",
"image":"VCYwmSae2BShoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
},
{
"name":"Meals123",
"price":"200",
"id":"bmF8Is1Y",
"sessionname":"Dinner",
"image":"sIe8JBFzaRstock-photo-115193575.jpg",
"categoryname":"Non Veg"
},
{
"name":"Dosa",
"price":"100",
"id":"e9sWHV4A",
"sessionname":"Breakfast",
"image":"j8nu4GpVa7Shoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
},
{
"name":"Coca",
"price":"40",
"id":"0oJDfdCz",
"sessionname":"Cold Drinks",
"image":"LrkS8QpAs7Shoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
},
{
"name":"ICe",
"price":"100",
"id":"2ykEgtSs",
"sessionname":null,
"image":"KtPX9C26oRShoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
}
]
}
This is the output i am getting. Item names are repeated.
Below code Refers to ProductsPojo.java:
public class ProductsPojo {
public String name;
public String image;
private boolean isSelected = false;
public void setName(String name) {
this.name = name;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
Looks to me like you only ever create one ProductsPojo instance, here:
pojo = new ProductsPojo();
And then in your loop you keep modifying this one instance, and then adding it to the list again and again. This way you'd end up with the same item (the last one) in your list as many times as the number of objects you got in the response.
What you wanted to do was probably to create a new ProductsPojo at the beginning of the for loop every time instead, like this:
for (int i=0;i<products.length();i++) {
ProductsPojo pojo = new ProductsPojo();
JSONObject product_object = products.getJSONObject(i);
String name = product_object.getString("name");
String price = product_object.getString("price");
String product_id = product_object.getString("id");
String sessionname = product_object.getString("sessionname");
String image = product_object.getString("image");
String categoryname = product_object.getString("categoryname");
pojo.setName(product_object.getString("name"));
pojo.setImage(product_object.getString("image"));
pojoList.add(pojo);
}