No adapter attached skipping layout for recyclerview - android

Hi in the below code I am getting the below error for displaying a list using recyclerview .
When I am trying to display the list I am getting the below error.
java.lang.ClassCastException: java.lang.String cannot be cast to helper.GetBuildingList
at com.deepshikha.lightingsystem.SwipeRecyclerViewAdapter.onBindViewHolder(SwipeRecyclerViewAdapter.java:41)
at com.deepshikha.lightingsystem.SwipeRecyclerViewAdapter.onBindViewHolder(SwipeRecyclerViewAdapter.java:22)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
Response :
[{"ID":"1","Name":"Building1"},{"ID":"2","Name":"appexx"}]
In the below adapter displays the what are the item presents in the getbuildinglist pojo class.As well as Once user swiped from right to left .We are displaying two options for the list items to edit and delete the items.
SwipeAdapter:
public class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {
private Context mContext;
private List<GetBuildingList> buildingLists;
public SwipeRecyclerViewAdapter(Context context, List<GetBuildingList> strings) {
this.mContext = context;
this.buildingLists = strings;
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
final GetBuildingList item = buildingLists.get(position);
System.out.println ("item"+item);
viewHolder.tvName.setText((item.getName ()) + " - Row Position " + position);
System.out.println (item.getName ());
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
// Drag From Left
// viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));
// Drag From Right
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));
// Handling different events when swiping
viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
//when the SurfaceView totally cover the BottomView.
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
//you are swiping.
}
#Override
public void onStartOpen(SwipeLayout layout) {
}
#Override
public void onOpen(SwipeLayout layout) {
//when the BottomView totally show.
}
#Override
public void onStartClose(SwipeLayout layout) {
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
/*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
//Start your activity
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
}
});*/
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, " onClick : " + item.getName () + " \n" + item.getID (), Toast.LENGTH_SHORT).show();
}
});
// viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
// }
// });
//
//
// viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
// Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
// }
// });
viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Edit " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
buildingLists.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, buildingLists.size());
mItemManger.closeAllItems();
Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
// mItemManger is member in RecyclerSwipeAdapter Class
mItemManger.bindView(viewHolder.itemView, position);
}
#Override
public int getItemCount() {
return buildingLists.size();
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
// ViewHolder Class
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
TextView tvName;
TextView tvDelete;
TextView tvEdit;
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
tvName = (TextView) itemView.findViewById(R.id.tvName);
// tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
// tvShare = (TextView) itemView.findViewById(R.id.tvShare);
// btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);
}
}
}
In the below code describes the without refreshing the activity I am getting the response from the server.
That response I am adding to arraylist then setting the adapter to the recyclerview to display the list of items with swipe options.
Add.java:
private void doTheAutoRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
progressDialog = new ProgressDialog (getActivity ());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Communicating...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client (client)
.build();
API service = retrofit.create (API.class);
Call<List<GetBuildingList>> userCall = service.getbuildinglist ();
userCall.enqueue(new Callback<List<GetBuildingList>> () {
#Override
public void onResponse(Call <List<GetBuildingList>> call, Response <List<GetBuildingList>> response) {
if(response.isSuccessful()) {
progressDialog.dismiss ( );
Log.d ("Response body", new Gson ( ).toJson (response.body ( )));
String Status = new Gson ( ).toJson (response.body ( ));
JSONArray jsonArray = null;
try {
JSONObject jsonObject=null;
jsonArray = new JSONArray (Status);
arrayList = new ArrayList <> ( );
for (int i=0;i<jsonArray.length ();i++) {
name=jsonArray.getJSONObject (i).getString ("Name");
arrayList.add (name);
}
// Creating Adapter object
SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter((Context) getActivity (), arrayList);
mAdapter.notifyDataSetChanged ();
mRecyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace ( );
}
}
else {
progressDialog.dismiss ();
Log.d("Response errorBody", String.valueOf(response.errorBody()));
}
}
#Override
public void onFailure(Call<List<GetBuildingList>> call, Throwable t) {
// lv.setAdapter (adapter);
System.out.println("onFailure");
System.out.println(t.fillInStackTrace());
progressDialog.dismiss();
Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();;
// progressDialog.dismiss();
}
});
}
}, 5000);
return ;
}
GetBuildingList.java:
public class GetBuildingList{
#SerializedName("ID")
private String ID;
#SerializedName("Name")
private String Name;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}

In your onResponse() method you have these lines:
name=jsonArray.getJSONObject (i).getString ("Name");
...
arrayList.add (name);
Then you pass this list to your adapter. This list is assigned to the GetBuildingList field of your adapter. Then in your adapter you do:
final GetBuildingList item = buildingLists.get(position);
So you're trying to cast String type to GetBuildingList type, hence the exception.
Not really familiar with the library but you should try something like this:
for (int i=0;i<jsonArray.length ();i++) {
String name = jsonArray.getJSONObject (i).getString ("Name");
String id = jsonArray.getJSONObject (i).getString ("Id");
GetBuildingList gbl = new GetBuildingList();
gbl.setId(id);
gbl.setName(name);
arrayList.add(gbl);
}
I haven't used this library yet so if I'm wrong, someone please correct the above sample.

Related

Update Recyclerview List After Deleting Row [duplicate]

This question already has answers here:
How to update RecyclerView Adapter Data
(16 answers)
Closed 2 years ago.
I have tried most answers from this site without getting the desired result.
I have recyclerview with a list of items and a button contained in each row. When the button is clicked, I want the entire row to be deleted and list updated automatically.
Here's my adapter class code:
public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> {
private static final String TAG = CartAdapter.class.getSimpleName();
private final Context context;
private List<Cart> itemsList;
private String id;
public CartAdapter(Context context, List<Cart> itemsList) {
this.context = context;
this.itemsList = itemsList;
}
#Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout, parent, false);
return new CartViewHolder(view);
}
#Override
public void onBindViewHolder(final CartViewHolder viewholder, final int position) {
final Cart cart = itemsList.get(position);
id = cart.getProductId();
AndroidNetworking.get(Constants.PRODUCT_DETAILS_ENDPOINT + id)
.setTag("Get Product Image")
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Cart Item Image Response:\t" + response.toString());
String imagePath = null;
try {
JSONObject itemObject = new JSONObject(response.toString());
JSONObject data = itemObject.getJSONObject("data");
imagePath = data.getString("image");
Picasso.with(context)
.load(imagePath)
.placeholder(R.drawable.noimage)
.into(viewholder.cartItemImg);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
viewholder.cartItemTitle.setText(cart.getProductTitle());
viewholder.cartQtyTV.setText(cart.getCartQty() + "");
viewholder.clearProductIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeProductRow(cart);
}
});
viewholder.decreaseCartIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
decreaseProduct();
}
});
viewholder.increaseCartIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
increaseProduct();
}
});
}
private void increaseProduct() {
}
private void decreaseProduct() {
}
public void removeProductRow(final Cart cart) {
AndroidNetworking.get(Constants.REMOVE_PRODUCT_CART + id)
.setTag("Delete Product From Cart")
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Delete Product From Cart Response:\t" + response.toString());
int position = itemsList.indexOf(cart);
itemsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, itemsList.size());
}
#Override
public void onError(ANError anError) {
}
});
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
}
This code works and the item is deleted. However, the list does not update until I re-visit the activity again. How can I update the view immediately?
private update(Cart cart){
Log.d(TAG, "Delete Product From Cart Response:\t" +
response.toString());
int position = itemsList.indexOf(cart);
itemsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, itemsList.size());
}
And then, onResponse just call update(cart); <- You may need to pass some other data into this function based on your needs.
Update (related to your second problem):
#Override
public long getItemId(int position) {
return itemList != null ? itemList.get(position).getId() : 0;
}
Or, you could make a public function that return the full item for you
public Cart getItem(int position){
return itemList != null itemList.get(position) : null;
} // you have to check if this is null when you call it
maybe not UI thread running below code,cause not timely refresh interface
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Delete Product From Cart Response:\t" + response.toString());
int position = itemsList.indexOf(cart);
itemsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, itemsList.size());
}

Recyclerview : Load more in Blogger API doesn't smooth

I have successfully to get next page of post using Blogger's API, but i can't achieve the smooth scrolling of recyclerview, it look lagging.
I have tried using recyclerViewData.setNestedScrollingEnabled(false) and adapter.notifyDataSetChanged() but still doesn't work.
My point is How to achieve smooth of recyclerview. Any suggestion will be appreciate. thank is advance.
Here is my code
private void getData() {
showLoading(true);
final Call<ResponseBlogPost> postList = apiService.getListPost(GlobalVariable.APP_KEY);
postList.enqueue(new Callback<ResponseBlogPost>() {
#Override
public void onResponse(Call<ResponseBlogPost> call, Response<ResponseBlogPost> response) {
showLoading(false);
ResponseBlogPost responseBlogPost = response.body();
initDataView(responseBlogPost);
}
#Override
public void onFailure(Call<ResponseBlogPost> call, Throwable t) {
showLoading(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void initDataView(ResponseBlogPost listpost){
GlobalFunction.saveString(this,GlobalVariable.TOKEN_PAGINATION, listpost.getNextPageToken());
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.TOKEN_PAGINATION);
itemsList.addAll(listpost.getItems());
adapter = new MainAdapter(itemsList) {
#Override
public void load() {
if(nextPageToken==null){
return;
}
getNextListPost();
}
};
recyclerViewData.setAdapter(adapter);
recyclerViewData.setHasFixedSize(true);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,1);
staggeredGridLayoutManager.setGapStrategy(0);
recyclerViewData.setLayoutManager(staggeredGridLayoutManager);
}
private void getNextListPost(){
showLoading(true);
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.TOKEN_PAGINATION);
Call<ResponseBlogPost> call = apiService.getNexPageListPost(GlobalVariable.APP_KEY,nextPageToken);
call.enqueue(new Callback<ResponseBlogPost>() {
#Override
public void onResponse(Call<ResponseBlogPost> call, Response<ResponseBlogPost> response) {
showLoading(false);
ResponseBlogPost responseModel = response.body();
if(nextPageToken!=null){
initDataView2(responseModel);
}else{
Toast.makeText(MainActivity.this, "tidak ada data lagi ya", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBlogPost> call, Throwable t) {
showLoading(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void initDataView2(ResponseBlogPost listpost){
GlobalFunction.saveString(this,GlobalVariable.TOKEN_PAGINATION, listpost.getNextPageToken());
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.TOKEN_PAGINATION);
itemsList.addAll(listpost.getItems());
adapter = new MainAdapter(itemsList) {
#Override
public void load() {
if(nextPageToken!=null){
getNextListPost();
}
}
};
recyclerViewData.setAdapter(adapter);
recyclerViewData.setHasFixedSize(true);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1);
staggeredGridLayoutManager.setGapStrategy(0);
recyclerViewData.setLayoutManager(staggeredGridLayoutManager);
}
My Adapter Code :
public abstract class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder>{
private List<BlogPostModel> responseBlogPost;
public MainAdapter(List<BlogPostModel> responseBlogPost) {
this.responseBlogPost = responseBlogPost;
}
public abstract void load();
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main,parent,false);
return new MainViewHolder(view);
}
#Override
public void onBindViewHolder(final MainViewHolder holder, int position) {
final BlogPostModel model = responseBlogPost.get(position);
ArrayList<String> urlImage = pullLinks(model.getContent());
String firstImage = "";
for (int i = 0; i < urlImage.size(); i++) {
firstImage = urlImage.get(1);
GlideCustomLoading.setImageFromURL(holder.itemView.getContext(), urlImage.get(0)
,holder.avLoadingIndicatorView, holder.ivItemPost,holder.tvFailedLoadImage);
}
holder.tvTitleItemPost.setText(model.getTitle());
final String finalFirstImage = firstImage;
holder.llItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = String.valueOf(model.getId());
DetailPostActivity.start(holder.itemView.getContext(), id, finalFirstImage, model.getTitle(), model.getUrl());
}
});
if(position>=getItemCount()-1){
load();
}
}
#Override
public int getItemCount() {
return responseBlogPost.size();
}
public class MainViewHolder extends RecyclerView.ViewHolder{
CardView cardViewItemPost;
ImageView ivItemPost;
TextView tvTitleItemPost;
AVLoadingIndicatorView avLoadingIndicatorView;
TextView tvFailedLoadImage;
LinearLayout llItem;
public MainViewHolder(View itemView) {
super(itemView);
cardViewItemPost = itemView.findViewById(R.id.cardview_item_post);
ivItemPost = itemView.findViewById(R.id.iv_image_post);
tvTitleItemPost = itemView.findViewById(R.id.tv_title_post);
avLoadingIndicatorView = itemView.findViewById(R.id.avi_load);
tvFailedLoadImage = itemView.findViewById(R.id.tv_gagal_menampilkan_gambar);
llItem = itemView.findViewById(R.id.ll_item_post);
}
}
private ArrayList pullLinks(String html) {
ArrayList links = new ArrayList();
Elements srcs = Jsoup.parse(html).select("[src]"); //get All tags containing "src"
for (int i = 0; i < srcs.size(); i++) {
links.add(srcs.get(i).attr("abs:src")); // get links of selected tags
}
return links;
}
}
While I'm not familiar with Jsoup I'm reasonably confident that it's the source of your scroll lag.
You are calling the method pullLinks in your onBindViewHolder method which is called every time a new view is added to your RecyclerView. I'm assuming pullLinks does some pretty intensive work that takes some time to complete.
What you would be better off doing is to add all of the data to each item in your responseBlogPost List before loading it in to the adapter.

API successfull called, but not displayed

i am trying to call local API server using retrofit, in my Logcat shows that the API success called, but in my app there is nothing displayed. how i can fix this issue? and here is my code :
interface.java :
public interface Service {
#GET("vocabulary/id/*")
Call<APIResponse<List<VocabMaster>>> getVocabMaster();
}
Vocab Master.java to collect data from API :
public class VocabMaster implements Serializable {
private BigDecimal vocab_id;
private String hanzi_t;
private String hanzi_s;
private String pinyin;
private BigDecimal level_id;
private List<VocabMeaning> meaning;
public BigDecimal getVocab_id() {
return vocab_id;
}
public void setVocab_id(BigDecimal vocab_id) {
this.vocab_id = vocab_id;
}
public String getHanzi_t() {
return hanzi_t;
}
public void setHanzi_t(String hanzi_t) {
this.hanzi_t = hanzi_t;
}
public String getHanzi_s() {
return hanzi_s;
}
public void setHanzi_s(String hanzi_s) {
this.hanzi_s = hanzi_s;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
public List<VocabMeaning> getMeaning() {
return meaning;
}
public void setMeaning(List<VocabMeaning> meaning) {
this.meaning = meaning;
}
public BigDecimal getLevel_id() {
return level_id;
}
public void setLevel_id(BigDecimal level_id) {
this.level_id = level_id;
}
#Override
public String toString() {
return "VocabMaster{" +
"vocab_id=" + vocab_id +
", hanzi_t='" + hanzi_t + '\'' +
", hanzi_s='" + hanzi_s + '\'' +
", pinyin='" + pinyin + '\'' +
", level_id=" + level_id +
", meaning=" + meaning +
'}';
}
}
And this is MainActivity.java :
public class MainActivity extends AppCompatActivity {
RecyclerView rvReligiVideo;
List<VocabMaster> vocabMasters = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvReligiVideo = findViewById(R.id.rvReligi);
initReligiVideo();
loadReligiVideo();
}
private void initReligiVideo() {
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.HORIZONTAL);
rvReligiVideo.setLayoutManager(layout);
VocabAdapter ar = new VocabAdapter(vocabMasters);
rvReligiVideo.setAdapter(ar);
}
//=========== Request to API ==========
private void loadReligiVideo() {
Call<APIResponse<List<VocabMaster>>> call = ServicesFactory.getService().getVocabMaster();
call.enqueue(new Callback<APIResponse<List<VocabMaster>>>() {
#Override
public void onResponse(Call<APIResponse<List<VocabMaster>>> call, Response<APIResponse<List<VocabMaster>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<VocabMaster> data = response.body().data;
if (data != null) {
vocabMasters.clear();
vocabMasters.addAll(data);
rvReligiVideo.getAdapter().notifyDataSetChanged();
}
} else {
Toast.makeText(MainActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<VocabMaster>>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
logcat on android studio :
JSON Data Structure :
Here is my Adapter :
public class VocabAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<VocabMaster> data;
public VocabAdapter(List<VocabMaster> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.vocabulary_model, null);
return new VH(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
VocabMaster vm = data.get(position);
VH vh = (VH) holder;
vh.hanziS.setText(vm.getHanzi_s());
vh.hanziT.setText(vm.getHanzi_t());
vh.pinyin.setText(vm.getPinyin());
vh.sound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Sound", Toast.LENGTH_SHORT).show();
}
});
vh.favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Favorite", Toast.LENGTH_SHORT).show();
}
});
vh.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Share", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return (data == null) ? 0 : data.size();
}
public class VH extends RecyclerView.ViewHolder {
TextView hanziS;
TextView hanziT;
TextView pinyin;
TextView desc;
ImageView sound, share, favorite;
Context context;
public VH(View itemView) {
super(itemView);
hanziS = itemView.findViewById(R.id.hanziS);
hanziT = itemView.findViewById(R.id.hanziT);
pinyin = itemView.findViewById(R.id.pinyin);
desc = itemView.findViewById(R.id.txtDesc);
sound = itemView.findViewById(R.id.imgSpeaker);
share = itemView.findViewById(R.id.imgShare);
favorite = itemView.findViewById(R.id.imgFavotite);
}
}
}
i did some changes in your code... use this
private VocabAdapter ar;
private void initReligiVideo() {
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.HORIZONTAL);
rvReligiVideo.setLayoutManager(layout);
ar = new VocabAdapter(vocabMasters);
rvReligiVideo.setAdapter(ar);
}
private void loadReligiVideo() {
Call<APIResponse<List<VocabMaster>>> call = ServicesFactory.getService().getVocabMaster();
call.enqueue(new Callback<APIResponse<List<VocabMaster>>>() {
#Override
public void onResponse(Call<APIResponse<List<VocabMaster>>> call, Response<APIResponse<List<VocabMaster>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<VocabMaster> data = response.body().data;
if (data != null) {
ar.setVocoList(data);
}
} else {
Toast.makeText(MainActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<VocabMaster>>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
Add this method in your adapter Class
public void setVocoList(List<VocabMaster> list){
if(list!=null)
data=list;
notifyDataSetChanged();
}
Do not change adapter's list when you have new list.
//incorrect except that the adapter is first time set to recyclerview and setVocoList is called before recyclerview.setAdater
public void setVocoList(List<VocabMaster> list){
if(list!=null)
data=list;
notifyDataSetChanged();
}
//correct
private List<VocabMaster> datas = new ArrayList()
public void setVocoList(List<VocabMaster> list){
if(list==null) return;
datas.clear();
datas.addAll(list);
notifyDataSetChanged();
}

Add Button Click Event in RecyclerView

UserAdapter.java :
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private List<Users> usersList;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private Context mContext;
public class UsersViewHolder extends RecyclerView.ViewHolder {
public TextView txtUsername, txtCreatedAt;
public NetworkImageView imgUser;
public ImageButton btnMsg, btnDel;
public UsersViewHolder(View view) {
super(view);
txtUsername = (TextView) view.findViewById(R.id.txt_username);
txtCreatedAt = (TextView) view.findViewById(R.id.txt_created_at);
imgUser = (NetworkImageView) view.findViewById(R.id.img_user);
btnMsg = (ImageButton) view.findViewById(R.id.btn_msg);
btnDel = (ImageButton) view.findViewById(R.id.btn_delete);
}
}
public UsersAdapter(Context context, List<Users> usersList) {
mContext = context;
this.usersList = usersList;
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_row, parent, false);
return new UsersViewHolder(itemView);
}
#Override
public void onBindViewHolder(UsersViewHolder holder, int position) {
Users users = usersList.get(position);
holder.txtUsername.setText(users.getUserName() + " " + users.getUserSurname());
holder.txtCreatedAt.setText(users.getCreatedAt());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.imgUser.setImageUrl(users.getUserImgPath(), imageLoader);
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
}
AppliersActivity :
public class AppliersActivity extends AppCompatActivity {
private static final String TAG = AppliersActivity.class.getSimpleName();
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog pDialog;
private String uid, api_key, adId;
private List<Users> usersList = new ArrayList<>();
private RecyclerView recyclerView;
private UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appliers);
definitions();
getAppliers();
}
private void definitions() {
adId = getIntent().getStringExtra("adId");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
uid = user.get("uid");
api_key = user.get("api_key");
recyclerView = (RecyclerView) findViewById(R.id.appliers_recycler_view);
mAdapter = new UsersAdapter(getApplicationContext(), usersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new OnTouchActionListener() {
#Override
public void onLeftSwipe(View view, int position) {
}
#Override
public void onRightSwipe(View view, int position) {
}
#Override
public void onClick(View view, int position) {
String adId = usersList.get(position).getUserId();
}
}));
}
public static interface OnTouchActionListener {
public void onLeftSwipe(View view, int position);
public void onRightSwipe(View view, int position);
public void onClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private OnTouchActionListener mOnTouchActionListener;
private GestureDetectorCompat mGestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, OnTouchActionListener onTouchActionListener) {
mOnTouchActionListener = onTouchActionListener;
mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchActionListener != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchActionListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void getAppliers() {
// Tag used to cancel the request
String tag_string_req = "req_appliers";
pDialog.setMessage("Lütfen Bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.GET,
ApiRoutes.URL_JOB_APPLIERS+ "/" + adId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Appliers Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
usersList.clear();
mAdapter.notifyDataSetChanged();
JSONArray usersArray = jObj.getJSONArray("appliers");
Users users;
for (int i = 0; i < usersArray.length(); i++) {
JSONObject jsonobject = usersArray.getJSONObject(i);
users = new Users(jsonobject.getString("uid"), jsonobject.getString("name"), jsonobject.getString("surname"), ApiRoutes.FOLDER_IMG + "/" + jsonobject.getString("uid") + "/profile_img.png", jsonobject.getString("created_at"));
usersList.add(users);
}
mAdapter.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "User Ads Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", api_key);
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I have two imagebutton on recyclerviewer' s rows. I want to add click event for each row. I sent the applicationcontext to an adapter from activity. And i added to onclicklistener event in adapter class. But it does not show toast on the screen. How can i solve this problem ?
You don't call show() method of Toast in your adapter class.
Change it as following
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});

EditText values in a RecyclerView gives same value after 5th position

I have a RecyclerView and each row has a EditText also. I am adding item to RecyclerView by searching them and then I type the quantity in the edit text. Then I send it to the server to store using json format. Item add is working perfectly. There is no edit text value swapping problem also when scrolling. I can display 5 rows in the screen.
Problem is when I send item to the server, edit text values in bottom rows get the same after 5th row.
These are the rows I am adding to the recyclerview.Printed List that send to the server.
Item : 7.50-15 10PR FM CEAT Quantity : 1
Item : 5.60-15 04PR K 511 CEAT Quantity : 2
Item : 2.75-18 04PR SECURA F85 CEAT (F) Quantity : 3
Item : 3.00-17 06PR SECURA ZOOM CEAT (R) Quantity : 4
Item : 6.50-14 10PR FM CEAT Quantity : 5
Item : 5.00-12 04PR GRIP MASTER CEAT Quantity : 5
Item : 4.00-08 06PR AUTO RAJA RPG Quantity : 5
Item : 9.00-20 14PR CEAT CLT LUG Quantity : 5
Item : 8.25-20 14PR TR PLUS SUNTRAC Quantity : 5
Item : 7.00-15 12PR FM CEAT Quantity : 5
After the 5th position Quantity is the same. My input value is not coming.
This is my SelectItem class -
public class SelectItem extends AppCompatActivity implements SelectItemAdapter.OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_item);
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
myRecyclerView = (RecyclerView) findViewById(R.id.selectedItemRecyclerView);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
spinner = (Spinner) findViewById(R.id.selectDistribChannel);
arrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, YourDealerListFragment.disChannel);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
selectedDisChannel = spinner.getSelectedItem().toString();
sqLiteHandler = new SQLiteHandler(getApplicationContext());
myRecyclerViewAdapter = new SelectItemAdapter(this);
myRecyclerViewAdapter.setOnItemClickListener(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
myRecyclerViewAdapter.notifyDataSetChanged();
dealerName = DealerListAdapter.getDealerName();
dealerID = DealerListAdapter.getDealerID();
repID = DealerListAdapter.getRepID();
//order number
orderId = "70000001";
if (newOrderId == null) {
newOrderId = orderId;
}
bAdd = (Button) findViewById(R.id.bAdd);
bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (myRecyclerViewAdapter.getItemCount() != 0) {
new AlertDialog.Builder(SelectItem.this)
.setTitle("Confirmation")
.setMessage("Do you want to send?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
checkOrderNo();
}
})
.setNegativeButton(android.R.string.no, null).show();
} else {
Toast.makeText(getApplicationContext(), "Empty List", Toast.LENGTH_SHORT).show();
}
}
});
//textView.setText(dealerName);
getSupportActionBar().setTitle(dealerName);
final AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
adapter = new MaterialSuggestionAdapter(getApplicationContext());
acTextView.setAdapter(adapter);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product result = adapter.getItem(position);
String newName = result.getMatName().toString();
String newQty = String.valueOf(result.getMatQuantity());
String newPCode = result.getMatNo().toString();
String newPlant = result.getMatPlant().toString();
if (!newName.equals("")) {
if (myRecyclerViewAdapter.getItemCount() > 0) {
if (!isPresent(newPlant, newPCode, myRecyclerViewAdapter)) {
myRecyclerViewAdapter.add(1, newName, newQty, newPCode, newPlant);
} else {
Toast.makeText(getApplicationContext(), "Product Already in the List", Toast.LENGTH_SHORT).show();
}
} else {
myRecyclerViewAdapter.add(0, newName, newQty, newPCode, newPlant);
}
} else {
Toast.makeText(getApplicationContext(), "Invalied Item!", Toast.LENGTH_SHORT).show();
}
acTextView.setText("");
}
});
}
private boolean isPresent(String newPlant, String newPCode, SelectItemAdapter myRecyclerViewAdapter) {
boolean isPresent = false;
for (int i = 0; i < myRecyclerViewAdapter.getItemCount(); i++) {
if (newPCode.equalsIgnoreCase(myRecyclerViewAdapter.getItemPCode(i).toString()) && newPlant.equalsIgnoreCase(myRecyclerViewAdapter.getItemPlant(i).toString())) {
isPresent = true;
break;
}
}
return isPresent;
}
//send items for one order
private class SendItemAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... arg0) {
//Create JSON string start
json_string = "{\"sending_items\":[";
for (int i = 0; i < myRecyclerViewAdapter.getItemCount(); i++) {
/* if (myRecyclerView.findViewHolderForLayoutPosition(i) instanceof SelectItemAdapter.ItemHolder) {
SelectItemAdapter.ItemHolder childHolder = (SelectItemAdapter.ItemHolder) myRecyclerView.findViewHolderForLayoutPosition(i);
numberPickerNumber = childHolder.getQtyNumber();
}*/
getNumPicNumber(i);
//Repeat and loop this until all objects are added (and add try+catch)
try {
JSONObject obj_new = new JSONObject();
obj_new.put("order_no", orderIdForItemTable);
obj_new.put("items", myRecyclerViewAdapter.getItemName(i).toString());
obj_new.put("items_no", myRecyclerViewAdapter.getItemPCode(i).toString());
obj_new.put("plant", myRecyclerViewAdapter.getItemPlant(i).toString());
obj_new.put("quantity", numberPickerNumber);
json_string = json_string + obj_new.toString() + ",";
} catch (JSONException e) {
e.printStackTrace();
}
}
//Close JSON string
json_string = json_string.substring(0, json_string.length() - 1);
json_string += "]}";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 3500);
HttpConnectionParams.setSoTimeout(httpParams, 1000);
HttpClient client = new DefaultHttpClient(httpParams);
String url = AppConfig.URL_ITEMS_SEND;
HttpPost request = new HttpPost(url);
try {
request.setEntity(new ByteArrayEntity(json_string.getBytes("UTF8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.setHeader("json", json_string);
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
Log.i("", "excuting request");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("HTTP Response", response.getStatusLine().toString());
try {
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("Server Response", responseBody);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
finish();
Bundle basket = new Bundle();
basket.putString("dealerName", dealerName);
basket.putString("orderNo", newOrderId);
basket.putString("jsonString", json_string);
Intent intent = new Intent(SelectItem.this, ItemCart.class);
intent.putExtras(basket);
startActivity(intent);
finish();
//Toast.makeText(getApplicationContext(), json_string, Toast.LENGTH_LONG).show();
}
}
private String getNumPicNumber(int i) {
if (myRecyclerView.findViewHolderForLayoutPosition(i) instanceof SelectItemAdapter.ItemHolder) {
SelectItemAdapter.ItemHolder childHolder = (SelectItemAdapter.ItemHolder) myRecyclerView.findViewHolderForLayoutPosition(i);
numberPickerNumber = childHolder.getQtyNumber();
}
return numberPickerNumber;
}
#Override
public void onItemClick(SelectItemAdapter.ItemHolder item, int position) {
Toast.makeText(this,
"Remove " + position + " : " + item.getItemName(),
Toast.LENGTH_SHORT).show();
myRecyclerViewAdapter.remove(position);
}
private void checkOrderNo() {
showDialog();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
final String nowDate = df.format(new Date());
//final day of the month
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
final String lastDate = sdf.format(lastDayOfMonth);
Log.d("Last day ", sdf.format(lastDayOfMonth) + " // Today" + nowDate);
// Tag used to cancel the insert
String tag_string_req = "req_insert";
final StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_ITEM_DETAILS_SEND, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
if (jObj.names().get(0).equals("found")) {
newOrderId = jObj.getString("found").toString();
orderIdForItemTable = newOrderId;
new SendItemAsync().execute();
Log.d(TAG, "newOrderId: " + newOrderId);
Log.d(TAG, "New repID 2 inserted into sqlite: " + newOrderId + " " + nowDate);
sqLiteHandler.addItemDetails(newOrderId, repID, dealerID, nowDate, lastDate, selectedDisChannel);
} else {
Toast.makeText(getApplicationContext(), "Invalied Request", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Inserting Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("order_no", orderId);
params.put("repID", repID);
params.put("dealerID", dealerID);
params.put("nowDate", nowDate);
params.put("lastDate", lastDate);
params.put("disChannel", selectedDisChannel);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(6000, 1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
My Adapter class.
public class SelectItemAdapter extends RecyclerView.Adapter<SelectItemAdapter.ItemHolder> {
private List<String> itemsName, itemsQty, itemsPCode, itemPlant;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
private RecyclerView myRecyclerview;
public SelectItemAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
itemsName = new ArrayList<String>();
itemsQty = new ArrayList<String>();
itemsPCode = new ArrayList<String>();
itemPlant = new ArrayList<String>();
}
#Override
public SelectItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.custom_row_selected_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(SelectItemAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
holder.setItemQty(itemsQty.get(position));
holder.setItemPCode(itemsPCode.get(position));
holder.setItemPlant(itemPlant.get(position));
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return itemsName.size();
}
public Object getItemName(int position) {
return itemsName.get(position);
}
public Object getItemPCode(int position) {
return itemsPCode.get(position);
}
public Object getItemPlant(int position) {
return itemPlant.get(position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public interface OnItemClickListener {
public void onItemClick(ItemHolder item, int position);
}
public void add(int location, String iName, String iQty, String iPCode, String iPlant) {
itemsName.add(location, iName);
itemsQty.add(location, iQty);
itemsPCode.add(location, iPCode);
itemPlant.add(location, iPlant);
notifyItemInserted(location);
}
public void remove(int location) {
if (location >= itemsName.size())
return;
itemsName.remove(location);
notifyItemRemoved(location);
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private SelectItemAdapter parent;
TextView textItemName, txtPCode, txtAvailableQty, txtTempQty, txtPlant;
Button bRemove;
EditText numPicker;
public ItemHolder(View itemView, SelectItemAdapter parent) {
super(itemView);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.txtProductName);
txtAvailableQty = (TextView) itemView.findViewById(R.id.txtAvailbleQty);
txtPCode = (TextView) itemView.findViewById(R.id.txtPCode);
txtPlant = (TextView) itemView.findViewById(R.id.txtPlant);
bRemove = (Button) itemView.findViewById(R.id.bRemove);
numPicker = (EditText) itemView.findViewById(R.id.numberPicker);
bRemove.setOnClickListener(this);
}
public void setItemName(CharSequence name) {
textItemName.setText(name);
}
public void setItemQty(CharSequence name) {
txtAvailableQty.setText(name);
}
public void setItemPCode(CharSequence name) {
txtPCode.setText(name);
}
public void setItemPlant(CharSequence name) {
txtPlant.setText(name);
}
public String getQtyNumber() {
return numPicker.getText().toString();
}
public CharSequence getItemName() {
return textItemName.getText();
}
public CharSequence getItemPCode() {
return txtPCode.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if (listener != null) {
listener.onItemClick(this, getPosition());
}
}
}
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
holder.setIsRecyclable(false);// set this in your adapter class as like it is
}
Override getItemViewType method
override fun getItemViewType(position: Int): Int {
return position
}
RecyclerView creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and rebinds them to the data which is scrolling onto the screen
// Items for recycler View
//binding data
private ArrayList<Data> Items;
//HashMap to store editText text afterTextChanged
//each editext in RecyclerView contains Unique Key And Value
private HashMap<String,String> sourceData=new HashMap<>();
Refer This RecyclerView Program
public class DataRecyclerView extends RecyclerView.Adapter<DataRecyclerView.DataViewHolder> {
private Context context;
// Items for recycler View
//binding data
private ArrayList<Data> Items;
private LayoutInflater layoutInflater;
//HashMap to store editText text afterTextChanged
//each editext in RecyclerView contains Unique Key And Value
private HashMap<String,String> sourceData=new HashMap<>();
DataRecyclerView(Context context,ArrayList<Data> Items)
{
this.Items=Items;
this.context=context;
layoutInflater=LayoutInflater.from(context);
}
#NonNull
#Override
public DataViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//DataBinding is used to bind Data
DataViewHolderBinding binding= DataBindingUtil.inflate(layoutInflater, R.layout.template,parent,false);
return new DataViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull DataViewHolder holder, int position) {
//Pass Data pojo to Holder
holder.bindData(Items.get(position));
}
#Override
public int getItemCount() {
return Items.size();
}
class DataViewHolder extends RecyclerView.ViewHolder {
private EditText amount;
DataViewHolder(DataViewHolderBinding itemView) {
super(itemView.getRoot());
binding=itemView;
amount=binding.PayAmount;
}
void bindData(Data data)//Data pojo for DataBinding
{
if(binding!=null) {
// data will automatically set to textViews In DataBinding
binding.setData(data);
//every time data binds to views
//get text of respective edittext and assign to that current edittext
if (sourceData.containsKey((String.valueOf(getAdapterPosition())))) {// checks current editText key is availible or not
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
amount.setText(sourceData.get((String.valueOf(getAdapterPosition()))).getAmount());
}else
{
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
amount.setText(null);
}
amount.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) {
//when user enter text into edittext
//editetext key already availible in sourceData
// then update the value to hashmap sourceData
if (sourceData.containsKey(String.valueOf(getAdapterPosition()))) {
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
if (!s.toString().trim().isEmpty()) {
if (!s.toString().trim().equals("0")) {
sourceData.put(String.valueOf(getAdapterPosition()),s.toString().trim());
} else {
sourceData.put(String.valueOf(getAdapterPosition()), s.toString().trim();
}
} else {
sourceData.put(String.valueOf(getAdapterPosition()),null );
}
}
}
else {
//when user enter text into edittext for the first time
//check for current Data pojo IDNumber with getAdapterPosition Items Data pojo IDNumber
//if it equal
//then we store text into hashmap for specific edittext by using adapterPosition as key
if (data.getIDNumber().equals(Items.get(getAdapterPosition()).getData.getIDNumber())) { //
if (!s.toString().trim().isEmpty()) {
if (!s.toString().trim().equals("0")) {
sourceData.put(String.valueOf(getAdapterPosition()),s.toString().trim());
} else {
sourceData.put(String.valueOf(getAdapterPosition()), s.toString().trim();
}
} else {
sourceData.put(String.valueOf(getAdapterPosition()),null );
}
}
}
}
});
}
}
}
}
### Image Reference I can't show proper Image but Its Look Like this
The rows in RecyclerView is reusing while scrolling. So you need to create an array for save each EditText value
Then addTextChangedListener to your EditText to save the EditText value while you input
public void onBindViewHolder(SelectItemAdapter.ItemHolder holder, int position) {
...
holder.numPicker.setText(arrayForSaveEditTextValue[position]);
holder.numPicker.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
arrayForSaveEditTextValue[position] = arg0.toString();
}
});
...
}

Categories

Resources