get serial number in recycler view - android

AmountCartModel.java
public class AmountCartModel {
private String testName;
private String testPrice;
private String 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 String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String 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);
}
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);
}
}
AmountCartAdapter.java
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();
}
}
HealthCartActivity
public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imlogo;
private TextView Date;
private TextView Time;
private TextView Day;
private ImageView settingsButton;
#BindView(R.id.back_to_add_patient)
TextView backToDashboard;
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice = "";
int count = 0;
/*
*Api call
* */
private RecyclerView recyclerView;
private ArrayList<TestListModel> mydataList;
private RecyclerAdapter madapter;
private ArrayList<TestListModel> mydb;
private Button submitButton;
private TextView deviceModeName;
private TextView centerId;
SharePreferenceManager<LoginModel> sharePreferenceManager;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);
sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());
imlogo=(ImageView) findViewById(R.id.action_bar_logo);
Day=(TextView) findViewById(R.id.day);
Date=(TextView) findViewById(R.id.date);
Time=(TextView)findViewById(R.id.time);
//backButton=(Button) findViewById(R.id.back_button);
centerId=(TextView)findViewById(R.id.center_id);
deviceModeName=(TextView)findViewById(R.id.device_mode_name);
settingsButton=(ImageView)findViewById(R.id.settings);
submitButton=(Button) findViewById(R.id.submit_button);
dayTimeDisplay();
showcenterid(sharePreferenceManager.getUserLoginData(LoginModel.class));
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(HealthServicesActivity.this, settingsButton);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.common_navigation_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id==R.id.home){
startActivity(new Intent(getApplicationContext(), DashBoardActivity.class));
finish();
}
if (id==R.id.my_profile){
startActivity(new Intent(getApplicationContext(), MyProfileActivity.class));
finish();
}
if (id==R.id.change_password){
startActivity(new Intent(getApplicationContext(), ChangePasswordActivity.class));
finish();
}
Toast.makeText(HealthServicesActivity.this, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT
).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
progressDialog = new ProgressDialog(HealthServicesActivity.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);
//registerOnline();
initViews();
submitButton.setOnClickListener(this);
backToDashboard.setOnClickListener(this);
}
/*
* Action Bar DATE N TIME
* */
private void dayTimeDisplay(){
SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE");
java.util.Date d = new Date();
String dayOfTheWeek = sdf1.format(d);
Day.setText(dayOfTheWeek);
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
Date.setText(currentDateTimeString);
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
String time1 = sdf.format(dt);
Time.setText(time1);
}
/*
* On Click Listner
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
AtomicInteger sharedOutput = new AtomicInteger(0);
List<TestListModel> stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
//testListId = testListId+ "\n" + singleStudent.getTestlist_id().toString();
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice+"\n" + singleStudent.getTest_price().toString();
//count = singleStudent.setSerial_number("\n" +i);
//singleStudent.getSerial_number(count);
count ++;
/* count = sharedOutput.get() + 1;
System.out.println(count);
sharedOutput.incrementAndGet();*/
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("serial_number", 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();
mydataList = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
madapter = new RecyclerAdapter(mydataList);
recyclerView.setAdapter(madapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
I am trying to display serial number 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 get the serial number.

Well, you can work-around. And you won't have to keep serialNumber variable in model just to track it's position.
You can use position parameter variable of onBindViewHolder() for serial number and counting.
i.e.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//here position is unique for every item in the list, so, you can use it as a serial number
// also, since it's starting from 0, you should add 1 with it, in case you wanna start from 1
// holder.textView2.setText(myDataList.get(position).getSerialNumber());
holder.textView2.setText("S.No. "+(position+1));
}

#Override
public void onBindViewHolder(ViewHolder holder, int position)
holder.id.setText(String.valueOf(" "+(position+1)));
Use above method.

You have to add serialNumber to your AmountCartModel.This will fix your problem

Put an id in your AmountCartModel as below;
public class AmountCartModel {
private int serialNumber; // add this line
private String testName;
private String testPrice;
private Integer totalPrice;
public AmountCartModel() {
this.serialNumber= serialNumber; // add this line
this.testName = testName;
this.testPrice = testPrice;
this.totalPrice = totalPrice;
}
public int getSerialNumber (){
} // add this line
public void setSerialNumber(int serialNumber) {
}// add this line also
Then retrieve this serialNumber from each view.
Since you are sending the intent form onBackPressed(); attach the list as an extra to the intent as follows,
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new
Intent(AmountCartActivity.this,HealthServicesActivity.class).putParcelableArrayList("the list", mDataList));
finish();
}
Please ensure the object (AmountCarModel) you are making a list from extends Parcelable, and catch it in the HealthServiceActivity in onResume()
Alternatively, and probably the best way, is to attach the serialNumber inside the HealthServiceActivity in the Retrofit onResponse() method as below;
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
if (data != null){
for (int i = 0; i<data.size(); i++) {
data.setSerialNumber(i);}}
madapter = new RecyclerAdapter(data);
recyclerView.setAdapter(madapter);
}

In AmountCartModel serialNumber is of String datatype
and while putting object you are setting
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);
and you are storing it in ArrayList without for loop so every time only one object will get inclued in your arraylist

try this way
int count = 0;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit_button:
int totalAmount = 0;
int totalPrice = 0;
String testName = "";
String testPrice="";
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("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;
}
}

I found the answer. I have done code for serial number like below. Here I am getting serial number in front of the elements. In this code I took one int variable and initialized with value 1. After that I call srNo variable in for loop then incremented at the end of the for loop.
int srNo = 1;
List < TestListModel > stList = ((RecyclerAdapter) madapter)
.getTestList();
for (int i = 0; i < stList.size(); i++) {
TestListModel singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
testListId = testListId + "\n" + Integer.parseInt(String.valueOf(srNo));
testName = testName + "\n" + singleStudent.getTest_name().toString();
testPrice = testPrice + "\n" + singleStudent.getTest_price().toString();
srNo++;
totalAmount = Integer.parseInt(stList.get(i).getTest_price());
totalPrice = totalPrice + totalAmount;
}
}

Related

The items added multiple times into the RecyclerView with pagining

I am working on android app with java. and now I have to do messaging activities. I use RecyclerView to display the messages items. Also my messages Api is work with pagining, every time I send the last id and the server return the previous 10 messages.(Page size is 10). For filling the RecyclerView I use an Adapter but my problem is, that the item is added multiple times into the RecyclerView.
I will put my activity code and the adapter code
My Activity:
public class ConversationsActivity extends RootActivity implements ConversationsAdapter.ConversationOnClickHandler {
RetrofitBuilder rB = new RetrofitBuilder();
IApi service = rB.retrofit.create(IApi.class);
String authorization;
RecyclerView rv;
ConversationsAdapter adapter;
ProgressBar progressBar;
LinearLayoutManager layoutManager;
//declare it as global var for future cancel refresh
private SwipeRefreshLayout swipeLayout;
boolean wasSwiped;
// initialise loading state
boolean mIsLoading, mIsLastPage = false;
// amount of items you want to load per page
final int pageSize = 10;
int mCurrentPage =0;
int lastId;
boolean f;
int p =1;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.7F);
int chatId, to;
String senderType, name, to_type;
TextView no_data;
Button btnActionBar11, send;
TextView tvActionBar;
EditText message;
Context context;
ArrayList<Conversation.Data> conversationArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversations);
context = this;
adapter = new ConversationsAdapter(this,context);
Intent intent = getIntent();
chatId = intent.getIntExtra("chatId",0);
Intent intent1 = getIntent();
senderType = intent1.getStringExtra("senderType");
Intent intent2 = getIntent();
name = intent2.getStringExtra("name");
Intent intent3 = getIntent();
to = intent3.getIntExtra("from",0);
Intent intent4 = getIntent();
to_type = intent4.getStringExtra("from_type");
buttonClick.setDuration(500);
authorization = checkAuthorization();
setContentView(R.layout.activity_conversations);
progressBar = (ProgressBar) findViewById(R.id.progress);
tvActionBar = (TextView) findViewById(R.id.tvActionBar);
tvActionBar.setText(name);
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
layoutManager.setReverseLayout(true);
adapter.setHasStableIds(true);
// layoutManager.setStackFromEnd(true);
rv = (RecyclerView) findViewById(R.id.ConversationList);
no_data = (TextView) findViewById(R.id.no_data);
message = (EditText) findViewById(R.id.message);
send = (Button) findViewById(R.id.send);
rv.setLayoutManager(layoutManager);
btnActionBar11 = (Button) findViewById(R.id.btnActionBar11);
btnActionBar11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(message.getText().length() > 0){
sendMessage();
}
}
});
getConversation();
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// number of visible items
int visibleItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getChildCount();
// number of items in layout
int totalItemCount = ((LinearLayoutManager)recyclerView.getLayoutManager()).getItemCount();
// the position of first visible item
int firstVisibleItemPosition = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
boolean isNotLoadingAndNotLastPage = !mIsLoading && !mIsLastPage;
// flag if number of visible items is at the last
boolean isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount;
// validate non negative values
boolean isValidFirstItem = firstVisibleItemPosition >= 0;
// validate total items are more than possible visible items
boolean totalIsMoreThanVisible = totalItemCount >= pageSize;
// flag to know whether to load more
boolean shouldLoadMore = isValidFirstItem && isAtLastItem && totalIsMoreThanVisible && isNotLoadingAndNotLastPage;
if (shouldLoadMore) loadMoreItems(false);
}
});
Intent intent11 = getIntent();
wasSwiped = intent11.getBooleanExtra("wasSwiped",false);
//where you initialize your views:
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wasSwiped = true;
//your method to refresh content
Intent intent = new Intent(getApplicationContext(), ConversationsActivity.class)
.putExtra("chatId", chatId)
.putExtra("senderType", senderType)
.putExtra("name",name)
.putExtra("from", to)
.putExtra("from_type", to_type)
.putExtra("wasSwiped", wasSwiped);
startActivity(intent);
}
});
if(wasSwiped){
//don't forget to cancel refresh when work is done
if(swipeLayout.isRefreshing()) {
swipeLayout.setRefreshing(false);
}
}
}
#Override
public void onClickConversation(Conversation.Data conversation) {
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
public void sendMessage(){
Call<Message> call = service.sendMessage(authorization, to, to_type, message.getText().toString());
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null);
message.setText("");
getConversation();
//
// adapter.notifyDataSetChanged();
} else {
if(response.body()!= null)
if(response.body().getMessage() != null)
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void getConversation(){
Call<Conversation> call = service.getConversation(authorization,chatId,"LANDLORD");
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(conversationArrayList != null)
if(!conversationArrayList.isEmpty())
conversationArrayList.clear();
if(response.isSuccessful()){
if(response.body()!= null)
if(response.body().getData() != null)
if(response.body().getData().size() > 0){
if (!conversationArrayList.isEmpty())
conversationArrayList.clear(); //The list for update recycle view
adapter.notifyDataSetChanged();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if (conversationArrayList.isEmpty()) {
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
} else {
progressBar.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
} else {
Toast.makeText(getApplicationContext(),"error: " + response.body().getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Toast.makeText(getApplicationContext(),"error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void configureRecyclerView(ArrayList chat) {
rv = (RecyclerView) findViewById(R.id.ConversationList);
rv.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
rv.setLayoutManager(linearLayoutManager);
adapter = new ConversationsAdapter(this,context);
adapter.setConversationData(chat);
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
}
private void loadMoreItems(boolean isFirstPage) {
mIsLoading = true;
f = isFirstPage;
p = p +1;
Call<Conversation> call = service.getConversationPagenation(authorization,chatId,senderType, lastId);
call.enqueue(new Callback<Conversation>() {
#Override
public void onResponse(Call<Conversation> call, Response<Conversation> response) {
if(response.isSuccessful()){
if(response.body() != null)
if(response.body().getData()!= null) {
// conversationArrayList.clear();
for(int i =0; i < response.body().getData().size(); i++){
conversationArrayList.add(response.body().getData().get(i));
if( i == ( response.body().getData().size() -1 ))
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
}
progressBar.setVisibility(View.GONE);
if(conversationArrayList == null){
rv.setVisibility(View.GONE);
no_data.setVisibility(View.VISIBLE);
return;
}
else if (!f) {
if (!conversationArrayList.isEmpty())
adapter.notifyDataSetChanged();
adapter.addAll(conversationArrayList);
// conversationArrayList.clear(); //The list for update recycle view
}
else {
rv.setVisibility(View.VISIBLE);
no_data.setVisibility(View.GONE);
configureRecyclerView(conversationArrayList);
}
if(conversationArrayList.size() > 0)
lastId = conversationArrayList.get(conversationArrayList.size() - 1).getId();
mIsLoading = false;
mIsLastPage = mCurrentPage == lastId;
mCurrentPage = lastId;
}
}
}
#Override
public void onFailure(Call<Conversation> call, Throwable t) {
Log.e("SomeActivity", t.getMessage());
}
});
}
public String checkAuthorization(){
SharedPreferences settings = getSharedPreferences("log",0);
return settings.getString("Authorization", null);
}
}
My Adapter:
public class ConversationsAdapter extends
RecyclerView.Adapter<ConversationsAdapter.ConversationsAdapterViewHolder> {
private Context context;
private ArrayList<Conversation.Data> mConversation;
private ConversationsAdapter.ConversationOnClickHandler mConversationOnClickHandler;
private static SharedPreferences pref;
public ConversationsAdapter(ConversationsAdapter.ConversationOnClickHandler conversationOnClickHandler, Context _context) {
mConversationOnClickHandler = conversationOnClickHandler;
pref = _context.getSharedPreferences("log", Context.MODE_PRIVATE);
}
public void setConversationData(ArrayList<Conversation.Data> conversation) {
mConversation = conversation;
notifyDataSetChanged();
}
public void addAll(ArrayList<Conversation.Data> newList) {
int lastIndex = mConversation.size() - 1;
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
}
#Override
public ConversationsAdapter.ConversationsAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_msg, parent, false);
// Return a new holder instance
ConversationsAdapter.ConversationsAdapterViewHolder viewHolder = new ConversationsAdapter.ConversationsAdapterViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ConversationsAdapter.ConversationsAdapterViewHolder viewHolder, int position) {
Conversation.Data conversation = mConversation.get(position);
TextView tv1 = viewHolder.tv1;
TextView tv2 = viewHolder.tv2;
// SharedPreferences preferences = context.getSharedPreferences("log", Context.MODE_PRIVATE);
String agentId = pref.getString("agentId", "");
String from_type = conversation.getFromType();
int from = conversation.getFrom();
if((agentId.equals(String.valueOf(from))) && from_type.equals("AGENT")){
tv2.setVisibility(View.GONE);
tv1.setVisibility(View.VISIBLE);
tv1.setText(conversation.getBody());
}
else {
tv2.setVisibility(View.VISIBLE);
tv1.setVisibility(View.GONE);
tv2.setText(conversation.getBody());
}
}
// Returns the total count of items in the list
#Override
public int getItemCount() {
if(mConversation == null) {
return 0;
}
return mConversation.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
public class ConversationsAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView tv1;
public final TextView tv2;
public ConversationsAdapterViewHolder(View view) {
super(view);
tv1 = (TextView) view.findViewById(R.id.tvMsgR);
tv2 = (TextView) view.findViewById(R.id.tvMsgL);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Conversation.Data selectedNotifiction = mConversation.get(position);
mConversationOnClickHandler.onClickConversation(selectedNotifiction);
}
}
public interface ConversationOnClickHandler {
void onClickConversation(Conversation.Data conversation);
}
public long myTimeInMillis(String givenDateString ){
// String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
// System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
}
any help or advice?
And thankyou
in your addAll() function on ConversationsAdapter class
int lastIndex = mConversation.size() - 1;
mConversation.clear();
mConversation.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
this should do the trick

RecyclerView filled with Objects from SharedPreferences is slow and laggy

I am building an app which has a RecyclerView which holds Objects that are retrieved from SharedPreferences.
Unfortunately the RecyclerView is lagging when it is binded.
This is my Adapter
public class ShiftAdapter extends RecyclerView.Adapter<ShiftAdapter.ViewHolder>{
private List<Shift> mDataSet;
private Context mContext;
private static final String TAG = "ShiftAdapter";
public int previousExpandedPosition = -1;
public int mExpandedPosition = -1;
private static SharedPreferences mPrefs;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Boolean isStart;
private Date shiftIn;
private Date shiftOut;
private Date mDate;
public EditText mshiftInText;
public EditText mshiftOutText;
public Date date;
public ShiftAdapter(Context context, List<Shift> list) {
mDataSet = list;
mContext = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mDate;
public TextView mTime;
public TextView mPay;
public RelativeLayout mRelativeLayout;
public LinearLayout mExepandableLayout;
public Date mshiftIn;
public Date mshiftOut;
public EditText mshiftInText;
public EditText mshiftOutText;
public Button mUpdateButton;
public Button mDeleteButton;
public ViewHolder(View v) {
super(v);
mDate = (TextView) v.findViewById(R.id.date_TV);
mTime = (TextView) v.findViewById(R.id.time_TV);
mPay = (TextView) v.findViewById(R.id.pay_TV);
mRelativeLayout = (RelativeLayout) v.findViewById(R.id.rel_layout);
mExepandableLayout = (LinearLayout) v.findViewById(R.id.expandableLayout);
mshiftInText = (EditText) v.findViewById(R.id.setShiftIn);
mshiftOutText = (EditText) v.findViewById(R.id.setShiftOut);
mUpdateButton = (Button) v.findViewById(R.id.updateButton);
mDeleteButton = (Button) v.findViewById(R.id.deleteButton);
}
}
#Override
public ShiftAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.shift, parent, false);
ViewHolder vh = new ViewHolder(itemView);
return vh;
}
//TODO:Bind all the view elements to Shift Properties
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
// Format double
String hours = new DecimalFormat("##.##").format(mDataSet.get(i).getHours());
String pay = new DecimalFormat("##.##").format(mDataSet.get(i).getPay());
//set the Text
holder.mTime.setText(hours);
holder.mDate.setText(mDataSet.get(i).dateToString());
holder.mPay.setText(pay);
Log.d(TAG, "onBindViewHolder: called");
// new AsyncTask<>().ex
//Expand mExapndableLayout
final int position = i;
final boolean isExpanded = position ==mExpandedPosition;
holder.mExepandableLayout.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
// //set shift Times
// shiftIn = mDataSet.get(position).getInDate();
// shiftOut = mDataSet.get(position).getInDate();
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
//fill expandable layout
holder.mshiftInText.setText(mDataSet.get(position).fullTimeToString(0));
final EditText in = holder.mshiftInText;
final EditText out = holder.mshiftOutText;
//edit mShiftIn Text
holder.mshiftInText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =true;
timePickerDialog(in,out);
}
});
holder.mshiftOutText.setText(mDataSet.get(position).fullTimeToString(1));
//edit MshiftOut Text
holder.mshiftOutText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isStart =false;
timePickerDialog(in,out);
}
});
//updateButton onClick
holder.mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
shiftIn = mDataSet.get(position).getInDate();
shiftOut = mDataSet.get(position).getOutDate();
if(Validate.getValidate().isDateValid(shiftIn,shiftOut)) {
SharedPrefs.getInstance(mContext).editShift(newShift(shiftIn, shiftOut),Integer.toString(position));
int length = SharedPrefs.getInstance(mContext).getLength() - 1;
if (SharedPrefs.getInstance(mContext).getShift(length) != null) {
Log.d(TAG, "Edit Shift onClick: Success");
SharedPrefs.getInstance(mContext).saveShiftList(SharedPrefs.getInstance(mContext).sortList(SharedPrefs.getInstance(mContext).getShiftList()));
ShiftsFragment.updateUI();
Toast.makeText(mContext, "success", Toast.LENGTH_SHORT).show();
}
} else {
mShiftOut.setBackgroundResource(R.drawable.red_border);
Toast.makeText(mContext, "error", Toast.LENGTH_SHORT).show(); }
} catch(Exception e){
Log.d(TAG, "onDateSelected: "+e.toString());
Toast.makeText(mContext,"update FAIL", Toast.LENGTH_SHORT).show();
}
// update the Shift
}
});
holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
areYouSure(mExpandedPosition);
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public Date timePickerDialog(EditText in,EditText out) {
mshiftInText = in;
mshiftOutText = out;
new SingleDateAndTimePickerDialog.Builder(mContext)
.title(mContext.getResources().getString(R.string.choose_time))
.displayListener(new SingleDateAndTimePickerDialog.DisplayListener() {
#Override
public void onDisplayed(SingleDateAndTimePicker picker) {
if(!isStart) {
date = mDate;
}
}
}).defaultDate(returnDate(date))
.listener(new SingleDateAndTimePickerDialog.Listener() {
#Override
public void onDateSelected(Date date) {
mDate = date;
if (isStart) {
updateShiftIn(mDate);
mshiftInText.setText(dateToString(mDate));
} else {
updateShiftOut(mDate);
mshiftOutText.setText(dateToString(mDate));
}
}
}).display();
return mDate;
}
public String dateToString(Date date)
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String string = df.format(date);
return string;
}
private void updateShiftIn(Date date) {
shiftIn = date;
}
private void updateShiftOut(Date date) {
shiftOut = date;
}
private Date returnDate(Date date)
{
if(date!=null)
{
return date;
}
else return mDate;
}
private void areYouSure(int i)
{
final String position = Integer.toString(i);
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Log.d(TAG, "onClick: isSure=true;");
SharedPrefs.getInstance(mContext).removeShift(position);
ShiftsFragment.updateUI();
case DialogInterface.BUTTON_NEGATIVE:
Log.d(TAG, "onClick: isSure= false");
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(mContext.getResources().getString(R.string.are_you_sure)).setPositiveButton(mContext.getResources().getString(R.string.confirm), dialogClickListener)
.setNegativeButton(mContext.getResources().getString(R.string.cancel), dialogClickListener).show();
}
private Shift newShift(Date start,Date stop)
{
int id = SharedPrefs.getInstance(mContext).getLength();
Shift shift = new Shift(dateToCalendar(start),dateToCalendar(stop),id);
return shift;
}
and this is the Fragment that has the RecyclerView
public class ShiftsFragment extends Fragment {
private Toolbar mToolbar;
private TimePicker timePicker1;
private List<Shift> shiftList = new ArrayList<>();
private RecyclerView recyclerView;
private RelativeLayout relativeLayout;
private RecyclerView.LayoutManager layoutManager;
private LinearLayout mShiftIn;
private LinearLayout mShiftOut;
private Context mContext;
private ShiftAdapter mAdapter;
private MenuItem mAdd;
private Menu optionsMenu;
private LinearLayout mShiftAddLL;
private SharedPreferences mPrefs;
private static FragmentManager mFragmentManager;
private static final String TAG = "ShiftsFragment";
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG,"Clicked");
final View view = inflater.inflate(R.layout.shifts_layout,container,false);
mToolbar = view.findViewById(R.id.topbar);
mToolbar.inflateMenu(R.menu.toolbarmenu);
mShiftAddLL = view.findViewById(R.id.add_shiftLayout);
mAdd = mToolbar.getMenu().getItem(0);
timePicker1 = (TimePicker) view.findViewById(R.id.timePicker);
mFragmentManager = getFragmentManager();
//TODO:Add a summary bar on the bottom.
//get the context
mContext = getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.shift_list);
// Define a layout for RecyclerView
layoutManager = new GridLayoutManager(mContext,1);
recyclerView.setLayoutManager(layoutManager);
// Initialize a new Shift array
List<Shift> shiftList = initShifts();
Log.d(TAG,"shift array initiated");
// Initialize an array list from array
// Initialize a new instance of RecyclerView Adapter instance
mAdapter = new ShiftAdapter(mContext,shiftList);
// Set the adapter for RecyclerView
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
//Menu add button onClick
//Opens Add_Shift_Fragment
mAdd.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Fragment selectedFragment = new Add_Shift_Fragment();
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return false;
}
});
return view;
}
//Initializes the Shift list from SharedPreferences and returns it.
private List<Shift> initShifts() {
return SharedPrefs.getInstance(mContext).getShiftList();
}
public static void updateUI()
{
Fragment selectedFragment = new ShiftsFragment();
mFragmentManager.beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
}
Everytime i launch the ShiftsFragment there are some frame skips, and the scrolling is choppy and laggy.
Maybe my SharedPreferences handling is what is slowing things down?
public class SharedPrefs {
private static SharedPrefs mSharedPrefs;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
protected Context mContext;
public static final String ID = "shiftList";
private SharedPrefs(Context context) {
mContext = context;
mPrefs = context.getSharedPreferences(ID, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
}
public static SharedPrefs getInstance(Context context) {
if (mSharedPrefs == null) {
mSharedPrefs = new SharedPrefs(context.getApplicationContext());
}
return mSharedPrefs;
}
public void saveShiftList(List<Shift> shiftList) {
Gson gson = new Gson();
String json = gson.toJson(shiftList);
mPrefsEditor.putString(ID, json);
mPrefsEditor.apply();
}
public void addShift (Shift shift)
{
List<Shift> shiftList= getShiftList();
shiftList.add(shift);
saveShiftList(shiftList);
}
//Replaced the shift#id with shift
public void editShift(Shift shift,String id)
{
removeShift(id);
addShift(shift);
}
public void removeShift(String id) {
List<Shift> shiftList = getShiftList();
int pos = Integer.parseInt(id);
shiftList.remove(pos);
saveShiftList(shiftList);
}
public void removeShift(int id) {
List<Shift> shiftList = getShiftList();
shiftList.remove(id);
saveShiftList(shiftList);
}
public Shift getShift(int id) {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
Shift shift = shiftList.get(id);
return shift;
}
public List<Shift> getShiftList() {
Gson gson = new Gson();
List<Shift> shiftList;
String json = mPrefs.getString(ID, null);
Type type = new TypeToken<List<Shift>>() {
}.getType();
shiftList = gson.fromJson(json, type);
if (shiftList!=null) {
return shiftList;
} else{
shiftList = new ArrayList<>();
return shiftList;
}
}
public List<Shift> sortList(List<Shift> shiftList)
{
Collections.sort(shiftList, new Comparator<Shift>() {
public int compare(Shift shift1, Shift shift2) {
if (shift1.getShiftStart() == null || shift2.getShiftStart() == null)
return 0;
return shift1.getShiftStart().compareTo(shift2.getShiftStart());
}
});
return shiftList;
}
public int getLength()
{
return getShiftList().size();
}
}
I have only found this problem with image loading, not just Strings from Object from SharedPrefs.

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");

My data of recyclerview loss in scroll down

I have a recyclerview and set text some textview in it. when I scroll down or my fragment goes to onPause state my data loss.
what can i do?
import static com.test.mohammaddvi.snappfood.Adapter.SectionListDataAdapter.decodeSampledBitmapFromResource;
public class RecyclerViewMenuFragmentAdapter extends RecyclerView.Adapter<RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment> {
private ArrayList<Food> foodList;
private Context mContext;
public RecyclerViewMenuFragmentAdapter(ArrayList<Food> foodList, Context mContext) {
this.foodList = foodList;
this.mContext = mContext;
}
#NonNull
#Override
public RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.foodlist, null);
return new RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment(v);
}
#Override
public void onBindViewHolder(final RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment holder, int position) {
Food food = foodList.get(position);
holder.foodName.setText(food.getName());
holder.foodDetails.setText(food.getDetails());
holder.foodPrice.setText(food.getPrice() + " تومان ");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
holder.foodOrderNumber.setText(0 + "");
holder.foodImage.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mContext.getResources().getIdentifier(food.getImage(),
"drawable", mContext.getPackageName()), 50, 50));
handleClick(holder, position);
}
private void handleClick(final SingleItemInMenuFragment holder, final int position) {
holder.foodPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
holder.foodOrderNumber.setText(orderNumber + 1 + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
holder.foodMinusButton.setVisibility(View.VISIBLE);
}
});
holder.foodMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
if (orderNumber > 1) {
holder.foodOrderNumber.setText(orderNumber - 1 + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
}
if (orderNumber == 1) {
holder.foodOrderNumber.setText(orderNumber - 1 + "");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
}
}
});
}
#Override
public int getItemCount() {
return (null != foodList ? foodList.size() : 0);
}
public class SingleItemInMenuFragment extends RecyclerView.ViewHolder {
TextView foodName;
TextView foodPrice;
Button foodPlusButton;
Button foodMinusButton;
TextView foodOrderNumber;
ImageView foodImage;
TextView foodDetails;
SingleItemInMenuFragment(View itemView) {
super(itemView);
this.foodName = itemView.findViewById(R.id.foodName);
this.foodImage = itemView.findViewById(R.id.imageFood);
this.foodPrice = itemView.findViewById(R.id.foodPrice);
this.foodDetails = itemView.findViewById(R.id.foodDetails);
this.foodPlusButton = itemView.findViewById(R.id.plusbutton);
this.foodMinusButton = itemView.findViewById(R.id.minusbutton);
this.foodOrderNumber = itemView.findViewById(R.id.ordernumber);
}
}
}
and this is my fragment that i use recyclerview in that:
public class MenuFragment extends Fragment{
private static final String TAG = "menufragment";
ArrayList<Food> allfoods = new ArrayList<>();
RecyclerView recyclerview;
private static Bundle bundle;
private final String KEY_RECYCLER_STATE= "recycler_state";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.menufragment, container, false);
}
#Override
public void onStart() {
super.onStart();
String jsonFilePath = "foods.json";
recyclerview = getActivity().findViewById(R.id.lstitems);
RecyclerViewMenuFragmentAdapter adapter = new RecyclerViewMenuFragmentAdapter(allfoods, getContext());
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerview.setHasFixedSize(true);
recyclerview.setAdapter(adapter);
parsJson(jsonFilePath);
}
//this method is for read a local json and return a string
public String readLocalJson(String jsonFile) {
String json;
try {
InputStream is = getActivity().getAssets().open(jsonFile);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
public void parsJson(String jsonFilePath) {
try {
JSONObject obj = new JSONObject(readLocalJson(jsonFilePath));
JSONArray jsonArray = obj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String image = jsonObject.getString("image");
JSONArray jsonArrayFoot = jsonObject.getJSONArray("foots");
for (int j = 0; j < jsonArrayFoot.length(); j++) {
JSONObject jsonObjectFoot = jsonArrayFoot.getJSONObject(j);
String foodName = jsonObjectFoot.getString("name");
String fooddetails = jsonObjectFoot.getString("fooddetails");
String price = jsonObjectFoot.getString("price");
allfoods.add(new Food(foodName, price, fooddetails, image));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Basically, you just initialized the data on onStart which will eventually called when your activity/fragment is resumed, and because of that all data you've changed was overwritten to initial data.
Move your onStart initialization to onViewCreated:
#Override
public void onViewCreated() {
super.onViewCreated();
String jsonFilePath = "foods.json";
recyclerview = getActivity().findViewById(R.id.lstitems);
RecyclerViewMenuFragmentAdapter adapter = new RecyclerViewMenuFragmentAdapter(allfoods, getContext());
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerview.setHasFixedSize(true);
recyclerview.setAdapter(adapter);
parsJson(jsonFilePath);
}
And for scrolling, its normal because RecyclerView recycles the view from the list above but the data is not, so what you need to do is store values from the list source.
#Override
public void onBindViewHolder(final RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment holder, int position) {
Food food = foodList.get(position);
holder.foodName.setText(food.getName());
holder.foodDetails.setText(food.getDetails());
holder.foodPrice.setText(food.getPrice() + " تومان ");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
holder.foodOrderNumber.setText(food.getFoodOrderNumber());
holder.foodImage.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mContext.getResources().getIdentifier(food.getImage(),
"drawable", mContext.getPackageName()), 50, 50));
handleClick(holder, position);
}
private void handleClick(final SingleItemInMenuFragment holder, final int position) {
holder.foodPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
int newOrderNumber = orderNumber + 1;
Food food = foodList.get(position);
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
holder.foodMinusButton.setVisibility(View.VISIBLE);
}
});
holder.foodMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Food food = foodList.get(position);
int orderNumber = food.getFoodOrderNumber();
if (orderNumber > 1) {
int newOrderNumber = orderNumber - 1;
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
}
if (orderNumber == 1) {
int newOrderNumber = orderNumber - 1;
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
}
}
});
}
And on your Food object just add this field and functions:
public class Food {
int foodOrderNumber;
public int getFoodOrderNumber() {
return foodOrderNumber;
}
public void setFoodOrderNumber(int foodOrderNumber) {
this.foodOrderNumber = foodOrderNumber;
}
}
add this line to your onBindViewHolder method and check again if the problem still exits:
holder.setIsRecyclable(false);

changing items in recyclerview adapter

I inserted/removing from particular position in ArrayList onBindViewHolder . Now , i want to show this modified list on recyclerview .
Adapter Code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyAdapterViewHolder> {
private List<Info> dataList;
private Context mAct;
private List<Info> totalCandidatesList;
private String TAG = "OWD";
public MyAdapter(List<Info> dataList, Context context) {
this.dataList = dataList;
this.mAct = context;
}
public void addApplications(List<Info> candidates) {
if(this.totalCandidatesList == null){
totalCandidatesList = new ArrayList<>();
}
this.dataList.addAll(candidates);
this.totalCandidatesList.addAll(candidates);
this.notifyItemRangeInserted(0, candidates.size() - 1);
}
public void clearApplications() {
int size = this.dataList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
dataList.remove(0);
totalCandidatesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public int getItemCount() {
return dataList.size();
}
public void onBindViewHolder(MyAdapterViewHolder mAdapterViewHolder, int i) {
if (i % 2 == 1) {
mAdapterViewHolder.cardView.setCardBackgroundColor(Color.parseColor("#ecf5fe"));
mAdapterViewHolder.layoutRipple.setBackgroundColor(Color.parseColor("#ecf5fe"));
} else {
mAdapterViewHolder.cardView.setCardBackgroundColor(Color.parseColor("#e2f1ff"));
mAdapterViewHolder.layoutRipple.setBackgroundColor(Color.parseColor("#e2f1ff"));
}
final WorkHolders workHolders = SingleTon.getInstance().getWorkHolders();
final String customerName = SingleTon.getInstance().getCustomerName();
String siteName = null;
if(customerName !=null) {
String[] sitenamearray = customerName.split("--");
if (sitenamearray.length > 1) {
siteName = sitenamearray[1];
}
}
final Info ci = dataList.get(i);
mAdapterViewHolder.title.setText(ci.heading1);
mAdapterViewHolder.jobNumber.setText(ci.heading2);
mAdapterViewHolder.distance.setText(ci.distance);
if(siteName != null && siteName.equalsIgnoreCase(ci.heading2)) {
mAdapterViewHolder.cardView.setCardBackgroundColor(Color.parseColor("#a7ffeb"));
mAdapterViewHolder.layoutRipple.setBackgroundColor(Color.parseColor("#a7ffeb"));
if(i!=0){
> //Here i removed and inserted item in list .
> dataList.remove(i);
> dataList.add(0,ci);
}
}
final String finalSiteName = siteName;
final Bundle bundle = new Bundle();
mAdapterViewHolder.layoutRipple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
String name = ci.heading1 + "--" + ci.heading2;
Log.d(TAG,"new Jobname : "+ name);
if (finalSiteName == null || finalSiteName.equalsIgnoreCase("")) {
bundle.putString("name", customerName);
bundle.putString("oldwork", "yes");
bundle.putString("running_job_selected", "yes");
} else {
Log.d(TAG,"StartedOn Before Sending Bundle :" + workHolders.startedOn);
Log.d(TAG, "running Job is not selected");
bundle.putString("name", name);
bundle.putString("oldwork", "yes");
bundle.putString("running_job_selected", "no");
}
FragmentTransaction ft = ((FragmentActivity) mAct).getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.glide_fragment_horizontal_in, R.anim.glide_fragment_horizontal_out);
fragment = new WorkDescriptionFragment();
fragment.setArguments(bundle);
ft.addToBackStack("myadapter");
ft.replace(R.id.content_frame, fragment).commit();
SingleTon.getInstance().setWorkStatus("start");
}
});
}
#Override
public MyAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.single_item1, viewGroup, false);
return new MyAdapterViewHolder(itemView);
}
public static class MyAdapterViewHolder extends RecyclerView.ViewHolder {
protected TextView title;
protected TextView dateTime;
protected TextView distance;
protected TextView jobNumber;
protected CardView cardView;
protected LayoutRipple layoutRipple;
public MyAdapterViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.title);
dateTime = (TextView) v.findViewById(R.id.dateTimeTextView);
distance = (TextView) v.findViewById(R.id.distanceTextView);
jobNumber = (TextView) v.findViewById(R.id.jobNumber);
cardView = (CardView) v.findViewById(R.id.cv);
layoutRipple = (LayoutRipple)v.findViewById(R.id.singleitemripple);
}
}
}
you will see following lines in above code where i am removing/inserting item in a list onBindview and would like to show same in recyclerview .
But right now i am getting normal datalist(unchanged) .
//Here i removed and inserted item in list .
dataList.remove(i);
dataList.add(0,ci);
Please help me to achieve this .
onBindViewHolder is not the place where you should update your adapter. The staregy is to update item inside your Adapter data list and then notifyDataChanged(). For example thise are the methods for updating info inside my adapter:
public void update(Track track) {
tracks.remove(track);
add(track);
}
public void add (Track track) {
tracks.add(track);
this.notifyDataSetChanged();
}
public void addTracks(List<Track> tracks){
this.tracks.addAll(tracks);
this.notifyDataSetChanged();
}
public void clearAndAddTracks(List<Track> tracks) {
for (int i = 0; i < this.tracks.size(); i++) {
if (!this.tracks.get(i).isRunning()){
}
}
this.tracks.clear();
this.tracks.addAll(tracks);
this.notifyDataSetChanged();
}

Categories

Resources