android -how to bind the image loaded from picasso to recycler view - android

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

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.

add integer values selected by checkbox

TestListModel.class
public class TestListModel {
private String testlist_id;
private String test_price;
private String test_name;
private boolean isSelected;
public TestListModel(String testlist_id, String test_price, String test_name,boolean isSelected) {
this.testlist_id = testlist_id;
this.test_price = test_price;
this.test_name = test_name;
this.isSelected = isSelected;
}
public String getTestlist_id() {
return testlist_id;
}
public void setTestlist_id(String testlist_id) {
this.testlist_id = testlist_id;
}
public String getTest_price() {
return test_price;
}
public void setTest_price(String test_price) {
this.test_price = test_price;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
JsonResponse.java
public class JSONResponse {
private TestListModel[] result;
public TestListModel[] getResult() {
return result;
}
public void setResult(TestListModel[] result) {
this.result = result;
}
}
HealthActivity.java
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> data;
private RecyclerAdapter madapter;
private Button submitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
submitButton=(Button) findViewById(R.id.submit_button);
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
initViews();
submitButton.setOnClickListener(this);
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
int count = 0;
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
//AmountCartModel serialNumber = stList.get(i);
if (singleStudent.isSelected() == true) {
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
count++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}
Toast.makeText(HealthServicesActivity.this,
"Selected Lists: \n" + testName+ "" + testPrice, Toast.LENGTH_LONG)
.show();
Intent in= new Intent(HealthServicesActivity.this, AmountCartActivity.class);
in.putExtra("test_name", testName);
in.putExtra("test_price", testPrice);
//in.putExtra("total_price",totalPrice);
in.putExtra("total_price", totalPrice);
in.putExtra("serialNumber", count);
startActivity(in);
finish();
break;
/** back Button Click
* */
case R.id.back_to_add_patient:
startActivity(new Intent(getApplicationContext(), PatientActivity.class));
finish();
break;
default:
break;
}
}
/** show center Id in action bar
* */
#Override
protected void onResume() {
super.onResume();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
}
private void showcenterid(LoginModel userLoginData) {
centerId.setText(userLoginData.getResult().getGenCenterId());
centerId.setText(userLoginData.getResult().getGenCenterId().toUpperCase());
deviceModeName.setText(userLoginData.getResult().getDeviceModeName());
}
private void initViews() {
recyclerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" http://192.168.1.80/aoplnew/api/")
//
.baseUrl("https://earthquake.usgs.gov/fdsnws/event/1/query?")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface request = retrofit.create(ApiInterface.class);
Call<JSONResponse> call = request.getTestLists();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
HealthRecyclerAdapter.java
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<TestListModel> android;
public RecyclerAdapter(ArrayList<TestListModel> android) {
this.android = android;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_list_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, final int position) {
holder.test_name.setText(android.get(position).getTest_name());
holder.test_price.setText(android.get(position).getTest_price());
holder.chkSelected.setChecked(android.get(position).isSelected());
holder.chkSelected.setTag(android.get(position));
holder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
TestListModel contact = (TestListModel) cb.getTag();
contact.setSelected(cb.isChecked());
android.get(position).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView test_name;
private TextView test_price;
public CheckBox chkSelected;
public TestListModel testLists;
public ViewHolder(View itemView) {
super(itemView);
test_name = (TextView)itemView.findViewById(R.id.test_name);
test_price = (TextView)itemView.findViewById(R.id.price_name);
chkSelected = (CheckBox) itemView.findViewById(R.id.check_box);
}
}
// method to access in activity after updating selection
public List<TestListModel> getTestList() {
return android;
}
AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private Integer serialNumber;
private Integer totalPrice;
public AmountCartModel() {
this.testName = testName;
this.testPrice = testPrice;
this.serialNumber = serialNumber;
this.totalPrice = totalPrice;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPrice() {
return testPrice;
}
public void setTestPrice(String testPrice) {
this.testPrice = testPrice;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}
AmountCartActivity.java
public class AmountCartActivity extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.total_price)
TextView totalPriceDisplay;
SharePreferenceManager<LoginModel> sharePreferenceManager;
private RecyclerView recyclerView;
List<AmountCartModel> mydataList ;
private MyAdapter madapter;
Bundle extras ;
String testName="";
String testPrice="";
String totalPrice= "";
int counting = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amount_cart);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
mydataList = new ArrayList<>();
/*
* Getting Values From BUNDLE
* */
extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("test_name");
testPrice = extras.getString("test_price");
totalPrice = String.valueOf(extras.getInt("total_price"));
counting = extras.getInt("serialNumber");
//Just add your data in list
AmountCartModel mydata = new AmountCartModel(); // object of Model Class
mydata.setTestName(testName );
mydata.setTestPrice(testPrice);
mydata.setTotalPrice(Integer.valueOf(totalPrice));
mydata.setSerialNumber(counting);
mydataList.add(mydata);
//totalPriceDisplay.setText(totalPrice);
}
madapter=new MyAdapter(mydataList);
madapter.setMyDataList(mydataList);
recyclerView = (RecyclerView)findViewById(R.id.recyler_amount_cart);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(madapter);
RecyclerAdapter.java //RecyclerAdapter for AmountCart
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private List<AmountCartModel> context;
private List<AmountCartModel> myDataList;
public MyAdapter(List<AmountCartModel> context) {
this.context = context;
myDataList = new ArrayList<>();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
// Replace with your layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amount_cart_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Set Your Data here to yout Layout Components..
// to get Amount
/* myDataList.get(position).getTestName();
myDataList.get(position).getTestPrice();*/
holder.testName.setText(myDataList.get(position).getTestName());
holder.testPrice.setText(myDataList.get(position).getTestPrice());
holder.textView2.setText(myDataList.get(position).getSerialNumber());
}
#Override
public int getItemCount() {
/*if (myDataList.size() != 0) {
// return Size of List if not empty!
return myDataList.size();
}
return 0;*/
return myDataList.size();
}
public void setMyDataList(List<AmountCartModel> myDataList) {
// getting list from Fragment.
this.myDataList = myDataList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView testName,testPrice,textView2;
public ViewHolder(View itemView) {
super(itemView);
// itemView.findViewById
testName=itemView.findViewById(R.id.test_name_one);
testPrice=itemView.findViewById(R.id.test_price);
textView2=itemView.findViewById(R.id.textView2);
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class));
finish();
}
}
This is my code.
Here I am taking HealthActivity and in this class by using recycler view I have displayed testList in recycler view. I am passing testList whichever I am selecting through checkbox to AmountCartActivity of recycler View, And, I am calculating total amount of the selected testList and I am getting the result and that result I am passing to the AmountCart Activity through bundle and I am getting correct result in bundle, but, when I am trying to display total amount in a textView its showing me nothing.
And, my second problem is,
I am trying to display serial number to to my AmountCartActivity of recycler view whichever I am selecting from previous HealthCartActivity using checkbox. And, I have implemented some code but I am not getting how to solve it. please help me.
For Issue#1
Data should be passed onto the Adapter through constructor. The issue could simply be adding another parameter to the constructor:
public MyAdapter(List<AmountCartModel> context, List<AmountCartModel> myDataList) {
this.context = context;
myDataList = this.myDataList;
}
Or,
To add selection support to a RecyclerView instance:
Determine which selection key type to use, then build a ItemKeyProvider.
Implement ItemDetailsLookup: it enables the selection library to access information about RecyclerView items given a MotionEvent.
Update item Views in RecyclerView to reflect that the user has selected or unselected it.
The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder() like,
In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
Update the styling of the view to represent the activated status.
For Issue #2
Try using passing data through intents.
The easiest way to do this would be to pass the serial num to the activity in the Intent you're using to start the activity:
Intent intent = new Intent(getBaseContext(), HealthServicesActivity.class);
intent.putExtra("EXTRA_SERIAL_NUM", serialNum);
startActivity(intent);
Access that intent on next activity
String sessionId= getIntent().getStringExtra("EXTRA_SERIAL_NUM");

search is not Working in section RecyclerView

i am trying implement search function in my section recyclerview
its not working but also not showing error...
i try with edittext addTextChangedListener method.
then in adapter add notifydatachanged method.
try with normal recyclerview its working fine but when use with section recyclerview its not working
sorry for bad english
here is mainActivty
here i get data from server and pass to the adapter in this class i am add the method for filter recyclerview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section_rv_search_prac);
init();
initView();
setUpRecyclerView();
tempModels = new ArrayList<TempModel>();
serviceRequest();
searchItem();
}
private void init() {
mAdapter = new ItemRecyclerViewAdapter(SectionRvSearchPrac.this);
}
private void initView() {
mEt_search = findViewById(R.id.et_search_main);
}
///////////////////////////////
private void searchItem() {
mEt_search.addTextChangedListener(
new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
}
//method for filter list is here..
private void filter(String text) {
ArrayList<TempModel> mFilter_list = new ArrayList<>();
for (TempModel tempModel : tempModels) {
if (tempModel.getName().toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(tempModel);
}
}
Log.d(TAG, "filter: " + mFilter_list);
mAdapter.filterList(mFilter_list);
}
//////////////////
private void setUpRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.sectioned_recycler_view);
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void serviceRequest() {
StringRequest stringRequest =
new StringRequest(
Request.Method.GET,
JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
parseJason(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT)
.show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void parseJason(String response) {
{
Log.d(TAG, "onResponse: " + response);
String[] first;
ArrayList<String> sewction_list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
String data = jsonArray.getString(0);
first = data.split(Pattern.quote("***^^^***"));
myList_sec = new ArrayList<>(Arrays.asList(first));
for (int j = 0; j < myList_sec.size(); j++) {
myList_first =
new ArrayList<>(Arrays.asList(myList_sec.get(j).split(Pattern.quote("^^^^"))));
sewction_list.add(myList_first.get(0));
myList_second =
new ArrayList<>(Arrays.asList(myList_first.get(1).split(Pattern.quote("^^"))));
ArrayList<String> id = new ArrayList<>();
ArrayList<String> url = new ArrayList<>();
ArrayList<String> img = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
for (int i = 0; i < myList_second.size(); i++) {
myList_third =
new ArrayList<>(Arrays.asList(myList_second.get(i).split(Pattern.quote("**"))));
url.add(myList_third.get(0));
img.add(myList_third.get(1));
name.add(myList_third.get(2));
id.add(myList_third.get(3));
tempModels.add(
new TempModel(
myList_third.get(2),
myList_third.get(0),
myList_third.get(1),
myList_third.get(3)));
}
sectionModelArrayList.add(new SectionModel(sewction_list, tempModels));
SectionRecyclerViewAdapter adapter =
new SectionRecyclerViewAdapter(
SectionRvSearchPrac.this, recyclerViewType, sectionModelArrayList);
recyclerView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here is myitemadapter class for child item
public class ItemRecyclerViewAdapter
extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ItemViewHolder> {
private static final String TAG = "adapter";
private Context context;
ArrayList<TempModel> tempModels;
public ItemRecyclerViewAdapter(Context context) {
this.context = context;
}
public void setData(ArrayList<TempModel> data) {
this.tempModels = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_custom_row_layout, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
String path = tempModels.get(position).getImage();
holder.itemLabel.setText(tempModels.get(position).getName());
Picasso.get().load(path).into(holder.imageView);
holder.cardView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {}
});
}
#Override
public int getItemCount() {
return tempModels.size();
}
/// here method for update filter list
public void filterList(ArrayList<TempModel> filterdNames) {
this.tempModels = filterdNames;
notifyDataSetChanged();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemLabel;
ImageView imageView;
CardView cardView;
public ItemViewHolder(View itemView) {
super(itemView);
itemLabel = (TextView) itemView.findViewById(R.id.item_label);
cardView = itemView.findViewById(R.id.cardview);
imageView = itemView.findViewById(R.id.img);
}
}
section model for section item
public class SectionModel {
private ArrayList<String> sectionLabel;
private ArrayList<TempModel> tempModels;
public SectionModel(ArrayList<String> sectionLabel, ArrayList<TempModel> tempModels) {
this.sectionLabel = sectionLabel;
this.tempModels = tempModels;
}
public ArrayList<String> getSectionLabel() {
return sectionLabel;
}
public ArrayList<TempModel> getTempModels() {
return tempModels;
}
}
model class for item
public class TempModel implements Parcelable{
String name;
String url;
String image;
String num;
public TempModel() {
}
public TempModel(String name, String url, String image, String num) {
this.name = name;
this.url = url;
this.image = image;
this.num = num;
}
protected TempModel(Parcel in) {
name = in.readString();
url = in.readString();
image = in.readString();
num = in.readString();
}
public static final Creator<TempModel> CREATOR = new Creator<TempModel>() {
#Override
public TempModel createFromParcel(Parcel in) {
return new TempModel(in);
}
#Override
public TempModel[] newArray(int size) {
return new TempModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
dest.writeString(image);
dest.writeString(num);
}
}
sectionadapter class
public class SectionRecyclerViewAdapter
extends RecyclerView.Adapter<SectionRecyclerViewAdapter.SectionViewHolder> {
private static final String TAG = "section";
class SectionViewHolder extends RecyclerView.ViewHolder {
private TextView sectionLabel, showAllButton;
private RecyclerView itemRecyclerView;
public SectionViewHolder(View itemView) {
super(itemView);
sectionLabel = (TextView) itemView.findViewById(R.id.section_label);
itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler_view);
}
}
private Context context;
private RecyclerViewType recyclerViewType;
private ArrayList<SectionModel> sectionModelArrayList;
public SectionRecyclerViewAdapter(
Context context,
RecyclerViewType recyclerViewType,
ArrayList<SectionModel> sectionModelArrayList) {
this.context = context;
this.recyclerViewType = recyclerViewType;
this.sectionModelArrayList = sectionModelArrayList;
}
#Override
public SectionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rrow, parent, false);
return new SectionViewHolder(view);
}
#Override
public void onBindViewHolder(SectionViewHolder holder, int position) {
final SectionModel sectionModel = sectionModelArrayList.get(position);
holder.sectionLabel.setText(sectionModel.getSectionLabel().get(position));
// recycler view for items
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setNestedScrollingEnabled(false);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
holder.itemRecyclerView.setLayoutManager(gridLayoutManager);
/* set layout manager on basis of recyclerview enum type */
ItemRecyclerViewAdapter adapter = new ItemRecyclerViewAdapter(context);
adapter.setData(sectionModel.getTempModels());
holder.itemRecyclerView.setAdapter(adapter);
}
#Override
public int getItemCount() {
return sectionModelArrayList.size();
}
Your code very confusing so i just write my solution.
public class SomeAdapter extends RecyclerView.Adapter<SomeAdapter.SomeViewHolder> implements Filterable{
...
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
mMainList = mYourJSONResponseList;
FilterResults results = new FilterResults();
ArrayList<YourModel> mFilter_list = new ArrayList<>();
//Place your logic
for (YourModel model : mMainList) {
if(model.getName().
toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(model);
}
}
results.count = mFilter_list.size();
results.values = mFilter_list;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mMainList = (ArrayList<YourModel>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
And add this into your text listener
#Override
public void afterTextChanged(Editable s) {
//Add this
adapter.getFilter().filter(s.toString())
}
NOTE!! You will show mMainList only this list in your RecyclerView, And check nullpointerexceptions

How to add data into RecyclerView

In my application I want use two recyclerView into one Activity.
I want when click on items of one of this recylerView's items , add item to another recyclerView.
I write below codes, when click on items just add lasted item info to another recyclerView.
But I want when click on each items, add this each items into another recyclerView not just add lasted items.
Now just add lasted items, but I want click each item add this item.
My Activity code:
public class SuggestFilmActivity extends AppCompatActivity implements SuggestedListener {
#BindView(R.id.toolbarTitleTxt)
TextView toolbarTitleTxt;
#BindView(R.id.suggestFilm_searchEditText)
EditText suggestFilm_searchEditText;
#BindView(R.id.suggestFilm_searchBtn)
ImageView suggestFilm_searchBtn;
#BindView(R.id.suggestFilm_recyclerView)
RecyclerView suggestFilm_recyclerView;
#BindView(R.id.suggestFilm_recyclerViewProgress)
ProgressBar suggestFilm_recyclerViewProgress;
#BindView(R.id.newsPageLoadLay)
RelativeLayout newsPageLoadLay;
#BindView(R.id.suggestFilm_recyclerViewSendUser)
RecyclerView suggestFilm_recyclerViewSendUser;
private Context context;
private SuggestFilmAdapter suggestFilmAdapter;
private SuggestFilmUserAdapter suggestFilmUserAdapter;
private List<Result> model = new ArrayList<>();
private InterfaceApi api;
private SharedPrefrencesHandler prefrencesHandler;
private String token;
private GridLayoutManager gridLayoutManager;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggest_film);
//Initialize
ButterKnife.bind(this);
context = this;
prefrencesHandler = new SharedPrefrencesHandler(context);
api = ApiClient.getClient().create(InterfaceApi.class);
suggestFilmAdapter = new SuggestFilmAdapter(context, model, this);
gridLayoutManager = new GridLayoutManager(context, 3);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
//Get token
token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
//Set toolbar title
toolbarTitleTxt.setText(context.getResources().getString(R.string.SuggestToFollowers));
//Init followers recyclerView
suggestFilm_recyclerView.setLayoutManager(gridLayoutManager);
suggestFilm_recyclerView.setHasFixedSize(true);
//Init send user recyclerView
suggestFilm_recyclerViewSendUser.setLayoutManager(linearLayoutManager);
suggestFilm_recyclerViewSendUser.setHasFixedSize(true);
//Load more
newsPageLoadLay.setVisibility(View.GONE);
suggestFilm_recyclerView.setOnScrollListener(new EndlessRecyclerGridPage1(gridLayoutManager) {
#Override
public void onLoadMore(int current_page) {
newsPageLoadLay.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(current_page));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
if (response.body().getData().getResult().size() > 0) {
suggestFilmAdapter.addNewItem(response.body().getData().getResult());
//Gone no explore
newsPageLoadLay.setVisibility(View.GONE);
}
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
newsPageLoadLay.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
newsPageLoadLay.setVisibility(View.GONE);
}
});
}
});
//Get user data
getUserData();
}
private void getUserData() {
suggestFilm_recyclerViewProgress.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(1));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getData().getResult().size() > 0
&& response.body().getStatusCode() != 401 && response.body().getStatusCode() != 402) {
model.clear();
model.addAll(response.body().getData().getResult());
suggestFilmAdapter.notifyDataSetChanged();
suggestFilm_recyclerView.setAdapter(suggestFilmAdapter);
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
});
}
private SuggestFilmSendData filmSendData(int page) {
SuggestFilmSendData sendData = new SuggestFilmSendData();
sendData.setKeyword("");
sendData.setPageIndex(page);
sendData.setPageSize(10);
return sendData;
}
private ArrayList<SuggestFilmAddUser> prepareData(int id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = new ArrayList<>();
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
return suggestFilmAddUserList;
}
#Override
public void onSend(int Id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = prepareData(Id, name, image);
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context, suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
}
}
One recyclerView adapter and send data Interface codes:
public class SuggestFilmAdapter extends RecyclerView.Adapter<SuggestFilmAdapter.ViewHolder> {
private Context context;
private List<Result> model;
private SuggestedListener suggestedListener;
public SuggestFilmAdapter(Context context, List<Result> model, SuggestedListener suggestedListener) {
this.context = context;
this.model = model;
this.suggestedListener = suggestedListener;
}
#Override
public SuggestFilmAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_suggest_film_users_followers, parent, false);
return new SuggestFilmAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final SuggestFilmAdapter.ViewHolder holder, final int position) {
//Name
holder.row_suggestFilmProfileName.setText(model.get(position).getName());
//Image
Glide.with(context)
.load(model.get(position).getImageUrl())
.asBitmap()
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(300, 300)
.into(new BitmapImageViewTarget(holder.row_suggestFilmProfileImage) {
#Override
protected void setResource(Bitmap resource) {
if (context == null) return;
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.row_suggestFilmProfileImage.setImageDrawable(circularBitmapDrawable);
}
});
//Is Mutual
if (model.get(position).getIsMutual()) {
holder.row_suggestFilmIsOk.setVisibility(View.VISIBLE);
} else {
holder.row_suggestFilmIsOk.setVisibility(View.GONE);
}
holder.row_suggestedLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestedListener.onSend(model.get(position).getUserId(),
model.get(position).getName(),
model.get(position).getImageUrl());
}
});
}
#Override
public int getItemCount() {
return model.size();
}
public void addNewItem(List<Result> newContent) {
int start = this.model.size();
int end = newContent.size();
model.addAll(newContent);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView row_suggestFilmProfileImage, row_suggestFilmIsOk;
private TextView row_suggestFilmProfileName;
private RelativeLayout row_suggestedLay;
public ViewHolder(View itemView) {
super(itemView);
row_suggestFilmProfileImage = (ImageView) itemView.findViewById(R.id.row_suggestFilmProfileImage);
row_suggestFilmIsOk = (ImageView) itemView.findViewById(R.id.row_suggestFilmIsOk);
row_suggestFilmProfileName = (TextView) itemView.findViewById(R.id.row_suggestFilmProfileName);
row_suggestedLay = (RelativeLayout) itemView.findViewById(R.id.row_suggestedLay);
}
}
}
Model class :
public class SuggestFilmAddUser {
private int id;
private String name;
private String image;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
How can I it? Please help me
Inside onSend() , you need to add each objects to an arraylist which should be declared globally. Then call notifyItemInserted(arraylist.size()-1) in adapter to refresh recyclerview
public class SuggestFilmActivity ....
{ ArrayList<SuggestFilmAddUser> suggestFilmAddUserList=new ArrayList();
SuggestFilmUserAdapter suggestFilmUserAdapter;
......
......
protected void onCreate(Bundle savedInstance)
{....
....
....
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context,
suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
.....
.....
}
public void onSend(int Id, String name, String image) {
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
suggestFilmUserAdapter.notifyItemInserted(suggestFilmAddUserList.size()-1)
}

Categories

Resources