changing items in recyclerview adapter - android

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();
}

Related

get serial number in recycler view

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;
}
}

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

notifyDataSetChanged() not refreshing adapter

My adapter list is refreshing on broadcast receiver .
Everything is working fine if adapter list size is greater than 1 ,
means if my recyclerview has already one row shwoing then list refreshing just fine .
But if list size goes from 0 to 1 then my adapter notify dataset
Changed stop working . No data shows on recyclerview. I don't know why it is not working .
Recyclerview Class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.job_recyclerview, container, false);
getActivity());
initialise(v);
init();
showNoTaskMessage();
new loadListTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here you can refresh your listview or other UI
SlidingTab.slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
SlidingTab.slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");;
SlidingTab.slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");
}
};
try {
IntentFilter filter = new IntentFilter("newJob");
LocalBroadcastManager.getInstance(context).registerReceiver(mMyBroadcastReceiver,
filter);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return v;
}
Adapter class :
public JobAdapter(ArrayList<Info> myDataset, Context context) {
this.mDataset = myDataset;
this.mAct = context;
}
public void addApplications(ArrayList<Info> candidates) {
if (this.filterList == null) {
filterList = new ArrayList<>();
}
this.mDataset.clear();
this.mDataset.addAll(candidates);
this.filterList.addAll(mDataset);
this.notifyItemRangeInserted(0, candidates.size() - 1);
}
public void clearApplications() {
int size = this.mDataset.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
mDataset.remove(0);
filterList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public int getItemViewType(int position) {
return VIEW_NORMAL;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_job_card, parent, false);
ViewHolder fh = new ViewHolder(v);
return fh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
// holder.jobPhone.setText(mDataset.get(position).mobileNo);
holder.jobNumber.setText(mDataset.get(position).jobNumber);
holder.jobTime.setText(mDataset.get(position).time);
holder.jobAddress.setText(mDataset.get(position).address);
// holder.jobInstructionText.setText(mDataset.get(position).spclInstruction);
if (mDataset.get(position).jobStatus != null && mDataset.get(position).jobStatus.equalsIgnoreCase("Completed")) {
holder.endsat.setText("Submitted at");
holder.jobTime.setText(mDataset.get(position).completedOnString);
holder.jobTimeLeft.setVisibility(View.INVISIBLE);
holder.timerImage.setVisibility(View.INVISIBLE);
} else {
if (mDataset.get(position).status.equalsIgnoreCase("Active")) {
holder.jobTimeLeft.setText(mDataset.get(position).appointmentTime);
} else {
holder.jobTimeLeft.setText("-" + mDataset.get(position).appointmentTime);
}
}
holder.jobLayout1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SingleTon.getInstance().setWorkDescHolder(mDataset.get(position).descHolder);
FragmentManager fragmentManager = ((FragmentActivity) mAct).getSupportFragmentManager();
FragmentTransaction ft = ((FragmentActivity) mAct).getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.glide_fragment_horizontal_in, R.anim.glide_fragment_horizontal_out);
ft.replace(R.id.content_frame1, new DetailsFragment(), "persondetails");
ft.addToBackStack("persondetails");
// Start the animated transition.
ft.commit();
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView jobNumber, jobTimeLeft, jobStatus, jobAddress, jobEmail, jobPhone, timeTimer, jobInstructionText, jobTime, endsat;
private ImageView timerImage;
private FrameLayout frameLayout;
private CardView cardView;
private LayoutRipple jobLayout1;
public ViewHolder(View v) {
super(v);
this.jobNumber = (TextView) v.findViewById(R.id.job_number);
this.jobTime = (TextView) v.findViewById(R.id.job_time);
this.jobTimeLeft = (TextView) v.findViewById(R.id.job_timertext);
this.timerImage = (ImageView) v.findViewById(R.id.timerimage);
this.cardView = (CardView) v.findViewById(R.id.card_view);
// this.jobStatus = (TextView) v.findViewById(R.id.job_status);
this.jobAddress = (TextView) v.findViewById(R.id.job_addresstext);
// this.jobInstructionText = (TextView) v.findViewById(R.id.instruction_text);
// this.jobLayout = (LayoutRipple)v.findViewById(R.id.job_cardLayout);
this.jobLayout1 = (LayoutRipple) v.findViewById(R.id.cardLayout1);
this.endsat = (AppCompatTextView) v.findViewById(R.id.endsat);
this.jobNumber.setTypeface(Utils.RegularTypeface(mAct));
this.jobAddress.setTypeface(Utils.RegularTypeface(mAct));
this.jobTimeLeft.setTypeface(Utils.RegularTypeface(mAct));
this.jobTime.setTypeface(Utils.RegularTypeface(mAct));
}
}
}
Please help me finding the bug or some other approach . Thanks
Call the data loading task inside the onReceive() of BroadcastReceiver
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here you can refresh your listview or other UI
new loadListTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
SlidingTab.slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
SlidingTab.slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");;
SlidingTab.slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");
}
};
And also do following changes in your Adapter class.
public void addApplications(ArrayList<Info> candidates) {
if (this.filterList == null) {
filterList = new ArrayList<>();
}
this.mDataset.clear();
this.mDataset.addAll(candidates);
this.filterList.addAll(mDataset);
this.notifyItemRangeInserted(0, candidates.size());
}
public void clearApplications() {
int size = this.mDataset.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
mDataset.remove(i);
filterList.remove(i);
}
this.notifyItemRangeRemoved(0, size);
}
}
Hope that works!
Change this:
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here you can refresh your listview or other UI
recycleAdapter.addItems(SingleTon.getInstance()
.getInfoArrayList());
// I'm assuming your "SingleTon.getInstance().getInfoArrayList()" is the received data.
}
On your Adapter
public void addItems(List<Info> itemsList) {
// This check could be avoided if you declared your mDataset final
if(mDataset == null) {
mDataset = new ArrayList<>();
}
int prevSize = mDataset.size();
mDataset.addAll(itemsList);
notifyItemRangeInserted(prevSize, itemsList.size());
}
You shouldn't call notifyDataSetChanged() after this.notifyItemRangeInserted(0, candidates.size() - 1); try something like this:
put this method to your adapter class
public void setData(ArrayList<Info> infos) {
this.mDataset = infos;
notifyDataSetChanged();
}
and call it like this:
ArrayList<Info> list = SingleTon.getInstance().getInfoArrayList().isEmpty();
if (list != null && !list.isEmpty()) {
recycleAdapter.setData(list);
}
correct this method in your adapter
#Override
public int getItemCount() {
return mDataset != null && !mDataset.isEmpty() ? mDataset.size() : 0;
}
Base on your code, we need a variable list to store your info data.
//Declare the info list
private ArrayList<Info> mInfos = new ArrayList<Info>()
In your onCreateView(), set mInfos to your recycleAdapter
recycleAdapter = new JobAdapter(mInfos, getActivity());
recyclerView.setAdapter(recycleAdapter);
So, every time you want to set new info list. Just assign it to mInfos
and make sure, you clear your previous list data to avoid duplicate data.
mInfos.clear()
mInfos.addAll(SingleTon.getInstance().getInfoArrayList());
//refresh data
recycleAdapter.notifyDataSetChanged();
I am not sure where you are using clearApplications() in JobAdapter.class.
But, it seems to be wrong. In the for-loop, you are trying to remove the value at index 0 every time rather than index 'i'. Hope this helps.
when you are using custom adapter then notifyDatasetChange() not called from outside that adapter so make addItem function in adapter and add new List in Adapter list and call notifyDataSetChanged
public void addItem(List<Model> list) {
if (lit != null) {
clear();
adapterList.addAll(list);
}
notifyDataSetChanged();
}
Do Change In your recyclerview class.
//Change condition ">1" to "!=null"
if (SingleTon.getInstance().getInfoArrayList().size() != null) {
recycleAdapter.addApplications(SingleTon.getInstance().getInfoArrayList());
recycleAdapter.notifyDataSetChanged();
and then do change in your adapter.
public void addApplications(ArrayList<Info> candidates) {
if (this.filterList == null) {
filterList = new ArrayList<>();
}
this.mDataset.clear();
this.mDataset.addAll(candidates);
this.filterList.addAll(mDataset);
this.notifyItemRangeInserted(0, mDataset.size()); //notify to mDataset
}
hope this will work!

RecyclerView with multiple Adapters and SharedPreferences

I am using a RecyclerView inside a Fragment to display a list of categories ( as shown in the images). When a category is selected, a new Activity starts with a RecyclerView. Each item from the list has a TextView and an icon for favorite ( the star from the top-right corner ). Once the favorite icon is pressed, the TextView will be saved to another Activity called Favorites.
The problem: let's say that I select Category A and I press the favorite button for the first 2 items. Everything looks good, the items are saved to Favorites. If I select Category B, bamm, I find the first 2 items selected...I go to Category C, same thing!
So if I check the favorite button once, it checks for all Adapters, like they're communicating. Why is this happening?
Although the favorite buttons are checked, I can't find the TextView's from Category B or C in the Favorites activity.
The Activity that starts when a category item is selected:
public class CategoriesDetailActivity extends AppCompatActivity {
Adapter0 ca0;
RecyclerView recList;
public CategoriesDetailActivity() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories_detail_activity);
Bundle bundle = this.getIntent().getExtras();
// Bundle bundle = this.getArguments();
bundle.getInt("id");
int position = bundle.getInt("id");
if (bundle.containsKey("id")) {
position = bundle.getInt("id");
} else {
this.finish();
}
recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
switch (position) {
case 0:
ca0 = new Adapter0(this, createList0(99));
recList.setAdapter(ca0);
break;
case 1:
ca0 = new Adapter0(this, createList1(80));
recList.setAdapter(ca0);
break;
...
}
}
private List<BeanSampleList> createList0(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text1[i];
ci.id = i;
result.add(ci);
}
return result;
}
private List<BeanSampleList> createList1(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text2[i];
ci.id = i;
result.add(ci);
}
return result;
}
#Override
public void onResume() {
super.onResume();
if (recList.getAdapter() == ca0) {
ca0.notifyDataSetChanged();
} if (recList.getAdapter() == ca1) {
ca1.notifyDataSetChanged();
} else {
// nothing
}
}
}
The Adapter class:
public class Adapter0 extends RecyclerView.Adapter<Adapter0 .ContactViewHolder> {
private Context context;
List<BeanSampleList> postBeanSampleList;
SharedPreference sharedPreference;
BeanSampleList beanSampleList;
public Adapter0 (Context context, List<BeanSampleList> postBeanSampleList) {
this.context = context;
this.postBeanSampleList = postBeanSampleList;
sharedPreference = new SharedPreference();
}
#Override
public int getItemCount() {
return postBeanSampleList.size();
}
public Object getItem(int position) {
return postBeanSampleList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void onBindViewHolder(final ContactViewHolder holder,final int i) {
beanSampleList = (BeanSampleList) getItem(i);
holder.vName.setText(beanSampleList.getTitle());
if (checkFavoriteItem(beanSampleList)) {
holder.btnFavourite.setLiked(true);
holder.btnFavourite.setTag("active");
} else {
holder.btnFavourite.setLiked(false);
holder.btnFavourite.setTag("deactive");
}
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.categories_detail_adapter, viewGroup, false);
return new ContactViewHolder(itemView);
}
public class ContactViewHolder extends RecyclerView.ViewHolder implements OnLikeListener {
protected TextView vName;
protected LikeButton btnFavourite;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.t1);
btnFavourite = (LikeButton) v.findViewById(R.id.favouritesToggle);
btnFavourite.setOnLikeListener(this);
}
#Override
public void liked(LikeButton likeButton) {
final int position = getAdapterPosition();
if (likeButton.getId() == btnFavourite.getId()) {
String tag = btnFavourite.getTag().toString();
if (tag.equalsIgnoreCase("deactive")) {
sharedPreference.addFavorite(context, postBeanSampleList.get(position));
btnFavourite.setTag("active");
btnFavourite.setLiked(true);
}
Snackbar snackbar = Snackbar
.make(likeButton, "Added to Favorites!", Snackbar.LENGTH_SHORT);
snackbar.show();
}
}
#Override
public void unLiked(LikeButton likeButton) {
final int position = getAdapterPosition();
if (likeButton.getId() == btnFavourite.getId()) {
sharedPreference.removeFavorite(context, postBeanSampleList.get(position));
btnFavourite.setTag("deactive");
btnFavourite.setLiked(false);
Snackbar snackbar = Snackbar
.make(likeButton, "Removed from Favorites!", Snackbar.LENGTH_SHORT);
snackbar.show();
}
}
}
public boolean checkFavoriteItem(BeanSampleList checkProduct) {
boolean check = false;
List<BeanSampleList> favorites = sharedPreference.loadFavorites(context);
if (favorites != null) {
for (BeanSampleList product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
}
For the past 2 days I've been trying to fix this but I just can't figure out what's causing this. I also tried to use different Adapters for each position but with no success.
public class BeanSampleList {
public int id;
public String title;
public String subTitle;
public String bottomTitle;
public String imageView;
public BeanSampleList() {
super();
}
public BeanSampleList(int id, String title, String subTitle, String bottomTitle, String imageView) {
super();
this.id = id;
this.title = title;
this.subTitle = subTitle;
this.bottomTitle = bottomTitle;
this.imageView = imageView;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitleBottom() {
return bottomTitle;
}
public void setTitleBottom(String bottomTitle) {
this.bottomTitle = bottomTitle;
}
public String getImageView() {
return imageView;
}
public void setImageView(String imageView) {
this.imageView = imageView;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BeanSampleList other = (BeanSampleList) obj;
if (id != other.id)
return false;
return true;
}
}
Thank you so much and sorry for my english.
I think the error is in your id generation for BeanSampleList
private List<BeanSampleList> createList0(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text1[i];
ci.id = i;
result.add(ci);
}
return result;
}
private List<BeanSampleList> createList1(int size) {
List<BeanSampleList> result = new ArrayList<>();
for (int i = 0; i <= size; i++) {
BeanSampleList ci = new BeanSampleList();
ci.title = DataText.Text2[i];
ci.id = i;
result.add(ci);
}
return result;
}
You need to generate unique id for your BeanSamleList objects in createList* method. As in your current code the objects are the same from the equals method side (their id are from 0 to list_size range).
Or add some unique modifier to compare in equal, like add the position of parent list
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BeanSampleList other = (BeanSampleList) obj;
if (id != other.id)
return false;
if (listId != other.listId)
return false;
return true;
}
You need to find a different way to uniquely identify each BeanSampleList element. Just matching id is not good enough. Perhaps you could also match the titles if you know they will be unique. Or generate unique Ids for each of these elements say by dividing the integer domain in different ranges e.g. 1 to 1000000 is for category 1, 1000001 to 2000000 for category 2 and so on.

Categories

Resources