How can i save changed data from RecyclerView and upload the changes - android

I am processing an image and getting 'data' from it. Then i show those in RecyclerView. I correct some data in RecyclerView if necessary. How to upload the corrected data with all the rest, Because even if the correction shows in RecyclerView it is not uploading the change ,Rather mistaken data are being uploaded. Can someone please help i am stuck for several days...
This is part of my mainActivity where i am adding the data to Recyclerview?
TextExtractionActivity.class
if (fileDirectory.isDirectory()) {
listCroppedImages.clear();
EmptyViewCroppedImage.setVisibility(View.GONE);
RVCroppedImages.setVisibility(View.VISIBLE);
listCroppedImages.clear();
String PhotoPath[] = new String[100];
final String StudentMatric[] = new String[100];
final String AttendanceRecord[] = new String[100];
for (int i = 1; i <= fileDirectory.listFiles().length; i++) {
PhotoPath[i] = croppedImageDirectory + i + ".jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap croppedimageold = BitmapFactory.decodeFile(PhotoPath[i], options);
Bitmap croppedimagenew = Bitmap.createScaledBitmap(croppedimageold, 460, 66, true);
StudentMatric[i] = TextImageProcess(croppedimagenew);
AttendanceRecord[i] = CircleDetection(croppedimagenew, StudentMatric[i]);
listCroppedImages.add(new CroppedImageModel(String.valueOf(i), PhotoPath[i], StudentMatric[i], AttendanceRecord[i]));
btnUploadAttendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int x = 1; x <= listCroppedImages.size(); x++) {
UploadData(StudentMatric[x], AttendanceRecord[x], x);
}
}
});
}
} else {
EmptyViewCroppedImage.setVisibility(View.VISIBLE);
RVCroppedImages.setVisibility(View.GONE);
}
-----------------------------------------------------------------------
public void UploadData(final String StudentMatric, final String AttendanceRecord, final int x) {
ProgressUploadAttendance.setVisibility(View.VISIBLE);
Query query = StudentsRef.orderByKey().equalTo(StudentMatric);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int progress = x / listCroppedImages.size() * 100;
DatabaseReference StudentMatricRef = StudentsRef.child(StudentMatric).child("Attendance").push();
StudentMatricRef.child("Status").setValue(AttendanceRecord);
StudentMatricRef.child("Date").setValue(getCurrentDate());
ProgressUploadAttendance.setProgress(progress);
} else {
Toast.makeText(TextExtractionActivity.this, "Could not Find " + StudentMatric, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
"RecyclerViewAdapterCroppedImages.class"
class RecyclerViewAdapterCroppedImages extends RecyclerView.Adapter<RecyclerViewAdapterCroppedImages.CroppedimageViewHolder> {
private Context mContext;
private List<CroppedImageModel> mData;
int x =0;
// private String StudentMatric, studentMatric, AttendanceStatus, attendanceStatus;
public RecyclerViewAdapterCroppedImages() { } //Constructor
public RecyclerViewAdapterCroppedImages(Context mContext, List<CroppedImageModel> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public CroppedimageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View croppedimageview;
LayoutInflater mInflater = LayoutInflater.from(mContext);
croppedimageview = mInflater.inflate(R.layout.item_cropped_image, parent, false);
return new CroppedimageViewHolder(croppedimageview);
}
#Override
public void onBindViewHolder(final CroppedimageViewHolder holder, final int position) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap croppedimageold = BitmapFactory.decodeFile(mData.get(position).getCroppedImagePath(), options);
Bitmap croppedimagenew = Bitmap.createScaledBitmap(croppedimageold, 528, 80, true);
holder.StudentNo.setText(mData.get(position).getStudentNo());
holder.CroppedImage.setImageBitmap(croppedimagenew);
holder.StudentId.setText(mData.get(position).getStudentMatric());
holder.StudentStatus.setText(mData.get(position).getAttendanceRecord());
holder.StudentStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mData.get(position).getAttendanceRecord().equals("Failed")) {
holder.StudentStatus.setText("Present");
} else if (mData.get(position).getAttendanceRecord().equals("Present")) {
holder.StudentStatus.setText("Absent");
} else if (mData.get(position).getAttendanceRecord().equals("Absent")) {
holder.StudentStatus.setText("Present");
}
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
class CroppedimageViewHolder extends RecyclerView.ViewHolder {
TextView StudentNo, StudentId, StudentStatus;
ImageView CroppedImage;
private CroppedimageViewHolder(View itemView) {
super(itemView);
StudentNo = itemView.findViewById(R.id.tvtxtprocessstudentno);
CroppedImage = itemView.findViewById(R.id.ivcroppedimage);
StudentId = itemView.findViewById(R.id.tvtxtprocessstudentid);
StudentStatus = itemView.findViewById(R.id.tvtxtprocessstudentstatus);
}
}
}

I found the solution. The thing is i thought i have to notifiyOnDatachange by adapter which located in my main activity. but i did not have to..
in my RecyclerViewAdapterCroppedImage.class
final CroppedImageModel changedRecord = mData.get(position);
holder.IVattendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (mData.get(position).getAttendanceRecord())
{
case "Failed":
mData.get(position).setAttendanceRecord("Present");
correctionAttendance(position, changedRecord);//code
break;
case "Present":
mData.get(position).setAttendanceRecord("Absent");
correctionAttendance(position, changedRecord);
break;
case "Absent":
mData.get(position).setAttendanceRecord("Present");
correctionAttendance(position, changedRecord);
break;
default:
break;
}
}
});
public void correctionAttendance(int position, CroppedImageModel attendanceRecord ) {
mData.set(position, attendanceRecord);
notifyItemChanged(position);
notifyDataSetChanged();
}
and in my TextExtractionActivity.class i fetch the data directly from Adapter rather than where i am processing and sending the data to Adapter.
btnUploadAttendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int x = 0; x < listCroppedImages.size(); x++) {
UploadData(listCroppedImages.get(x).getStudentMatric(),listCroppedImages.get(x).getAttendanceRecord(),x);
}
}
});
and lastly my UploadData() remain same as stated in the question..
Thank you anyone who intend to answer or provide format correction..

Related

I can't setProgress(0) of ALL Seekbars in RecyclerView when clicking a button (Android)

I have a RecyclerView of questions (which are saved and retrieved from database) and seekbars (which I save in database).
Link to image
After clicking on SUBMIT EXTRA QUESTIONS there is a dialog which appears
Link to image
I want after clicking on Okay the progress of ALL seekbars to be 0.
I tried to do this submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
holder.seekBar.setProgress(0);
But It changes only the progress of the last seekbar. Does anyone have any idea?
public class ExtraQuestionAdapter extends RecyclerView.Adapter<ExtraQuestionAdapter.ExtraQuestionViewHolder> {
private Context mCntx;
private List<ExtraQuestion> extraQuestionList;
private OnExtraAnswerListener onExtraAnswerListener;
private Button btn_submit_extra_questions;
private View rootView;
ArrayList<Integer> answersArray;
private Integer[] array = {};
String getId;
SessionManager sessionManager;
private Dialog dialog;
public ExtraQuestionAdapter(Context mCntx, List<ExtraQuestion> extraQuestionList, OnExtraAnswerListener onExtraAnswerListener) {
this.mCntx = mCntx;
this.extraQuestionList = extraQuestionList;
this.onExtraAnswerListener = onExtraAnswerListener;
}
#NonNull
#Override
public ExtraQuestionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCntx);
View view = inflater.inflate(R.layout.extra_question_layout, parent, false);
sessionManager = new SessionManager(mCntx);
HashMap<String, String> user = sessionManager.getUserDetail();
mCntx = parent.getContext();
rootView = ((Activity) mCntx).getWindow().getDecorView().findViewById(android.R.id.content);
//set the size of the array with answers to be equal to the size of the array with questions
array = new Integer[extraQuestionList.size()];
//initialise the array with answers with 0
for (int i = 0; i < extraQuestionList.size(); i++) {
array[i] = 0;
}
getId = user.get(sessionManager.ID);
btn_submit_extra_questions = rootView.findViewById(R.id.btn_submit_extra_questions);
ExtraQuestionViewHolder extraQuestionViewHolder = new ExtraQuestionViewHolder(view, onExtraAnswerListener);
return extraQuestionViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExtraQuestionViewHolder holder, int position) {
ExtraQuestion extraQuestion = extraQuestionList.get(position);
holder.title.setText(extraQuestion.getExtra_question());
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
array[holder.getAdapterPosition()] = seekBar.getProgress();
}
});
btn_submit_extra_questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(mCntx);
dialog.setContentView(R.layout.dialog_submit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(mCntx.getDrawable(R.drawable.dialog_background));
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button finalSubmit = dialog.findViewById(R.id.btn_submit);
Button cancelSubmit = dialog.findViewById(R.id.btn_cancel);
ImageView info = dialog.findViewById(R.id.info);
TextView termsConditions = dialog.findViewById(R.id.textView3);
// Cancel button in the dialog
cancelSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//Okay button in the dialog
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//fill the arraylist of answers with the array of answers
answersArray = new ArrayList<>(Arrays.asList(array));
ArrayList<Integer> FAnswerArray = new ArrayList<>();
ArrayList<Integer> FQuestionArray = new ArrayList<>();
if (!answersArray.isEmpty()) {
for (int i = 0; i < answersArray.size(); i++) {
FAnswerArray.add(answersArray.get(i));
FQuestionArray.add(i + 1);
}
}
JSONArray jsonArrayQuestion = new JSONArray();
for (Integer question : FQuestionArray) {
jsonArrayQuestion.put(question);
}
JSONArray jsonArrayAnswer = new JSONArray();
for (Integer answer : FAnswerArray) {
jsonArrayAnswer.put(answer);
}
dialog.dismiss();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
}
});
//Info button in the dialog
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
//Terms and conditions in the dialog
termsConditions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
dialog.show();
}
});
}
private void submitExpenseData(String extra_questions_id, String users_id, String extra_answer, String timeStamp_date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.EXTRA_ANSWERS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//we get the successful in String response
Log.e("response", response);
try {
JSONObject jsonObject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = jsonObject.getString("success");
if (success.equals("1")) {
sessionManager.saveAnswersOfTheDay(extra_questions_id, users_id, extra_answer, timeStamp_date);
Toast.makeText(mCntx.getApplicationContext(), R.string.successQuestionsOfTheDay, Toast.LENGTH_SHORT).show();
}
if (success.equals("alreadySubmitted")) {
Toast.makeText(mCntx.getApplicationContext(), R.string.submit_extra_questions_once_a_day, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(mCntx.getApplicationContext(), "Error! " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("sellresponseerror", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("extra_questions_id", extra_questions_id);
params.put("users_id", users_id);
params.put("extra_answer", extra_answer);
params.put("timeStamp_date", timeStamp_date);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mCntx);
requestQueue.add(stringRequest);
}
#Override
public int getItemCount() {
return extraQuestionList.size();
}
public class ExtraQuestionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
SeekBar seekBar;
OnExtraAnswerListener onExtraAnswerListener;
public ExtraQuestionViewHolder(#NonNull View itemView, OnExtraAnswerListener onExtraAnswerListener) {
super(itemView);
title = itemView.findViewById(R.id.textViewTitle);
seekBar = itemView.findViewById(R.id.seekBar);
this.onExtraAnswerListener = onExtraAnswerListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExtraAnswerListener.onExtraAnswerClick(getAdapterPosition());
}
}
public interface OnExtraAnswerListener {
void onExtraAnswerClick(int position);
}
}

While searching using EditText, the items in Recyclerview is duplicating, if i am searching fast

In my project, there is need of searching data from server using keyword. After search, i am displaying results using RecyclerView . While searching fast, the data in RecyclerView is duplicating. If searching slowly, it's working fine. Any suggestions are appreciated. Thank you.
The below code for making server call:
private void callSearchUserApi(final String searchText, int currentPage, boolean clearData) {
isApiCallInProcess = true;
String URL = "userinfo/api/v1/user-search/" + "?page=" + currentPage;
if (!Connectivity.isConnected(activity)) {
Common.snackBarNoConnection(activity, activity.getString(R.string.no_conection));
//setOnProgressbarVisibility(View.GONE);
return;
}
if (clearData) {
globalSearchUsersModelList.clear();
//BS globalSearchUserResultsAdapter.notifyDataSetChanged();
}
ApiInterface apiCall = ApiClient.getApiService(activity);
final Call<SearchUsersModel> globalUserSearchApiCall = apiCall.searchUser(
URL,
searchText);
globalUserSearchApiCall.enqueue(new Callback<SearchUsersModel>() {
#Override
public void onResponse(Call<SearchUsersModel> call, Response<SearchUsersModel> response) {
if (response.isSuccessful() && response.body().getStatus().equalsIgnoreCase(Common.SUCCESS_RESPONSE)) {
//BS globalSearchUsersModelList.addAll(response.body().getData().getData());
for (int i = 0; i < response.body().getData().getData().size(); i++) {
SearchUsersModel.DataBeanX.DataBean dataBean = new SearchUsersModel.DataBeanX.DataBean();
dataBean.setDesignation(response.body().getData().getData().get(i).getDesignation());
dataBean.setFull_name(response.body().getData().getData().get(i).getFull_name());
dataBean.setGender(response.body().getData().getData().get(i).getGender());
dataBean.setId(response.body().getData().getData().get(i).getId());
dataBean.setPlace(response.body().getData().getData().get(i).getPlace());
dataBean.setProfile_pic(response.body().getData().getData().get(i).getProfile_pic());
globalSearchUsersModelList.add(dataBean);
/*BS if (!globalSearchUsersModelList.contains(response.body().getData().getData().get(i)))
globalSearchUsersModelList.add(response.body().getData().getData().get(i));*/
}
CURRENT_PAGE = response.body().getData().getPage();
isLoading = false;
if (response.body().getData().isNext() == false)
isLastPage = true;
else
isLastPage = false;
if (globalSearchUsersModelList.size() == 0) {
rv_GlobalsearchList.setVisibility(View.GONE);
rl_placeholderGSPeople.setVisibility(View.VISIBLE);
tv_placeholderGSPeople.setText(activity.getString(R.string.no_search_found) + " " + searchText);
} else {
rv_GlobalsearchList.setVisibility(View.VISIBLE);
rl_placeholderGSPeople.setVisibility(View.GONE);
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
globalSearchUserResultsAdapter.notifyDataSetChanged();
}
});
}
if (searchTextsList.size() > 0) {
String sText = searchTextsList.get(0);
searchTextsList.remove(0);
callSearchUserApi(sText, FIRST_PAGE, true);
} else
isApiCallInProcess = false;
}
#Override
public void onFailure(Call<SearchUsersModel> call, Throwable t) {
isApiCallInProcess = false;
}
});
}
This is my Adapter.
public class GlobalSearchUserResultsAdapter extends RecyclerView.Adapter<GlobalSearchUserResultsAdapter.SearchViewHolder> {
private Context context;
private List<SearchUsersModel.DataBeanX.DataBean> searchUserList;
public GlobalSearchUserResultsAdapter(Context context, List<SearchUsersModel.DataBeanX.DataBean> searchUserList){
this.context = context;
this.searchUserList = searchUserList;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.v("Search", "Adapter Activity : "+context);
View view = LayoutInflater.from(context).inflate(R.layout.global_search_row, parent, false);
return new GlobalSearchUserResultsAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(GlobalSearchUserResultsAdapter.SearchViewHolder holder, int position) {
if ( searchUserList.get(position).getGender().equals("M")) {
holder.iv_userImage.setBackgroundResource(R.drawable.white_border_with_circle_appblue);
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
/*searchUsersModel*/searchUserList.get(position).getProfile_pic(),
R.drawable.male,
true);
} else if (searchUserList.get(position).getGender().equals("F")) {
holder.iv_userImage.setBackgroundResource(R.drawable.white_border_with_circle_pink);
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
searchUserList.get(position).getProfile_pic(),
R.drawable.female,
true);
} else {
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
searchUserList.get(position).getProfile_pic(),
R.drawable.deafult_profilepic,
true);
}
holder.tv_userName.setText(searchUserList.get(position).getFull_name());
holder.tv_userName.setTypeface(Common
.getFontTypeface(context, GlobalConstants.FONT_AVENIR_MEDIUM));
holder.tv_place.setText(searchUserList.get(position).getPlace());
holder.tv_place.setTypeface(Common
.getFontTypeface(context, GlobalConstants.FONT_AVENIR_MEDIUM));
holder.designation.setText(searchUserList.get(position).getDesignation());
}
#Override
public int getItemCount() {
return searchUserList.size();
}
public class SearchViewHolder extends RecyclerView.ViewHolder{
private ImageView iv_userImage;
private TextView tv_userName;
private TextView tv_place;
private TextView designation;
public SearchViewHolder(View itemView) {
super(itemView);
this.iv_userImage = (ImageView) itemView.findViewById(R.id.imageSearch);
this.tv_userName = (TextView) itemView.findViewById(R.id.nameSearch);
tv_userName.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_MEDIUM));
this.designation = (TextView) itemView.findViewById(R.id.designation);
designation.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_MEDIUM));
this.tv_place = (TextView) itemView.findViewById(R.id.placeSearch);
tv_place.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_LIGHT));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, ProfileActivity.class)//ThirdParty
.putExtra(GlobalConstants.KEY_THIRD_PARTY_ID, searchUserList.get(getAdapterPosition()).getId()));
}
});
}
}
}
You just had to clear the globalSearchUsersModelList list just before for loop, because API call is asynchronous.
globalSearchUsersModelList.clear();// Important one
for (int i = 0; i < response.body().getData().getData().size(); i++) {
// do your stuff
}
I think the issue come from your getItemId implementation. The way you implement it, the recycler view will identify an item according to its position in the list.
If you change this and use unique identification for instance searchUserList.get(position).id (if your User object has an unique ID) the problem should be fixed
You can also add in your activity adapter.setHasStableIds(true)

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

how to convert base64 to image in recyclerView

I am developing an app in which i am using recyclerView.In that i am calling my service for displaying the data. But my image is in Base64 format. I know how to convert Base64 to image without recyclerview, but i thins i am not getting how to do that. Below is my code for mainactivity
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
final DataJobs b1 = new DataJobs();
b1.ComapnayName = json.optString("CompanyName");
b1.DegreeName = json.optString("DegreeName");
b1.JobTitle = json.optString("JobTitle");
b1.Eventdate = json.optString("Eventdate");
b1.Comp_Req_Id=json.optInt("COMP_REQ_ID");
String img=json.optString("Image");
byte[] decodedString = Base64.decode(img, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image.setImageBitmap(decodedByte);
datajobs.add(b1);
}
} catch (JSONException e) {
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
Code for adapter
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.MyViewHolder> {
public List<DataJobs> datajobs;
private ClickListener clicklistener = null;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView JobTitle,DegreeName,ComapnayName,EventDate,Comp_Req_Id;
public MyViewHolder(View view){
super(view);
ComapnayName=(TextView) view.findViewById(R.id.ComapnayName);
DegreeName=(TextView) view.findViewById(R.id.DegreeName);
JobTitle=(TextView) view.findViewById(R.id.JobTitle);
EventDate=(TextView) view.findViewById(R.id.Eventdate);
Comp_Req_Id=(TextView) view.findViewById(R.id.Comp_Req_Id);
}
}
public EventsAdapter(List<DataJobs>datajobs){
this.datajobs=datajobs;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.data_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final DataJobs event = datajobs.get(position);
holder.ComapnayName.setText(event.getComapnayName());
holder.DegreeName.setText(event.getDegreeName());
holder.JobTitle.setText(event.getJobTitle());
holder.EventDate.setText(event.getEventdate());
holder.Comp_Req_Id.setText(String.valueOf(event.getComp_Req_Id()));
holder.itemView.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
int a=event.getComp_Req_Id();
Intent i = new Intent(v.getContext(), SecondActivity.class);
i.putExtra("Comp_Req_Id" , a);
v.getContext().startActivity(i);
//getActivity().finish();
}
});
}
}
code for datajobs:
public class DataJobs {
public String JobTitle,DegreeName,ComapnayName,Eventdate;
int Comp_Req_Id;
public DataJobs()
{
}
public DataJobs(String JobTitle,String PositionName,String ComapnayName,String Eventdate,int Comp_Req_Id)
{
this.JobTitle=JobTitle;
this.DegreeName=PositionName;
this.ComapnayName=ComapnayName;
this.Eventdate=Eventdate;
this.Comp_Req_Id=Comp_Req_Id;
}
public String getJobTitle(){
return JobTitle;
}
public void setJobTitle(String Jobname){
this.JobTitle=JobTitle;
}
public String getDegreeName(){
return DegreeName;
}
public void setDegreeNamee(String DegreeName){
this.DegreeName=DegreeName;
}
public String getComapnayName(){
return ComapnayName;
}
public void setCompanyName(String CompanyName){
this.ComapnayName=CompanyName;
}
public String getEventdate()
{
return Eventdate;
}
public void setEventdate(String Eventdate)
{
this.Eventdate=Eventdate;
}
public int getComp_Req_Id()
{
return Comp_Req_Id;
}
public void setComp_Req_Id(int Comp_Req_Id)
{
this.Comp_Req_Id=Comp_Req_Id;
}
}
You have add a Bitmap or String field to your DataJobs object.
Save the image/base64 string when you create the DataJobs list in the Main.
You can add an ImageView into your holder and pass the Bitmap/String to it. (like you do it with the other values)

RecyclerView fling and move not smooth

i am chinese coder.i am not good at english,so just try hard to describe the question. thank you very much for your answer.
when i first into activity with RecyclerView and scroll,it is not smooth especially showing next item next ,but when i have scrolled the Recyclerview,it is work,and smooth . some coder say we can't do much work on onCreateViewHolder() and onBindViewHolder() , but i can not get it.
here is my code:
fragment
public class HomeFragment extends RefreshableFragment implements IHomeView {
#Bind(R.id.refresh_view)
PullToRefreshRecyclerView refresh_view;
private RecyclerView refreshableView;
private HomePresenter homePresenter;
#Override
public View initSuccessView() {
View view = View.inflate(getContext(), R.layout.fragment_refreshable_success_recyclerview, null);
ButterKnife.bind(this, view);
initRefreshLayout();
initRecyclerView();
return view;
}
/**
* 初始化可刷新控件
*/
private void initRefreshLayout() {
refresh_view.setMode(PullToRefreshBase.Mode.BOTH);
refresh_view.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<RecyclerView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
homePresenter.refresh();
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
homePresenter.loadMore();
}
});
}
/**
* 初始化RecyclerView控件
*/
private void initRecyclerView() {
refreshableView = refresh_view.getRefreshableView();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
SpaceItemDecoration decor = new SpaceItemDecoration(2);
refreshableView.addItemDecoration(decor);
refreshableView.setLayoutManager(layoutManager);
refreshableView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int childCount = recyclerView.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = recyclerView.getChildAt(i);
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(view);
switch (holder.getItemViewType()){
case HomeAdapter.TYPE_TOPIC:
HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
topicViewHolder.setParentHeight(recyclerView.getHeight());
topicViewHolder.setOffset();
}
}
}
});
}
#Override
protected void requestNetwork() {
homePresenter = new HomePresenter(getContext(),this,null);
homePresenter.init();
}
#Override
public RecyclerView getRecyclerView() {
return refreshableView;
}
#Override
public RefreshView getRefreshView() {
return getParentRefreshView();
}
#Override
public void onRefreshFinish() {
if(refresh_view.isRefreshing()){
refresh_view.onRefreshComplete();
}
}
#Override
public void onLordMoreFinish() {
}
}
presenter
public class HomePresenter extends BasePresenter<IHomeView> implements IHomePresenter, StringLoaderCallback {
private Gson gson;
private HomeAdapter homeAdapter;
private final Pagination pagination;
public HomePresenter(Context context,IHomeView homeView,Bundle bundle) {
super(context,homeView,bundle);
gson = new Gson();
homeAdapter = new HomeAdapter();
getPresenterView().getRecyclerView().setAdapter(homeAdapter);
pagination = new Pagination();
pagination.setLimit(10);
pagination.setOffset(0);
}
#Override
public void init() {
String bannerUrl = ServerAPI.Home.buildHomeBannerUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(bannerUrl, null, bannerUrl, this);
String topicUrl = ServerAPI.Home.buildHomeTopicUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(topicUrl, null, topicUrl, this);
String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), REFRESH, this);
}
#Override
public void loadMore() {
String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
pagination.setOffset(pagination.getTotal());
pagination.setLimit(10);
NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), LOADMORE, this);
}
#Override
public void refresh() {
pagination.setOffset(0);
pagination.setLimit(10);
pagination.clearTotal();
init();
}
#Override
public void onLoadFinished(String url,Map<String,String> params, String data,Object tag) {
if(url.equals(ServerAPI.Home.buildHomeBannerUrl())){
Log.i(url,data);
HomeBanner.HomeBannerLists homeBannerLists = gson.fromJson(data,HomeBanner.HomeBannerLists.class);
homeAdapter.setBanners(homeBannerLists.list);
}
if(url.equals(ServerAPI.Home.buildHomeTopicUrl())){
Log.i(url,data);
HomeTopic.HomeTopicLists homeTopicLists = gson.fromJson(data,HomeTopic.HomeTopicLists.class);
homeAdapter.setTopics(homeTopicLists.list);
}
if(url.equals(ServerAPI.Home.buildHomeRouteUrl())){
Log.i(url,data);
int mode = (int) tag;
HomeRoute.HomeRouteLists homeRouteLists = gson.fromJson(data, HomeRoute.HomeRouteLists.class);
if (mode == REFRESH){
homeAdapter.setRoutes(homeRouteLists.list);
} else if(mode == LOADMORE){
homeAdapter.appendRoutes(homeRouteLists.list);
}
pagination.appendTotal(homeRouteLists.list.size());
}
getPresenterView().getRefreshView().setCurrentState(RefreshView.STATE_SUCCESS);
getPresenterView().onRefreshFinish();
}
#Override
public void onLoadError(VolleyError error) {
Log.i("error",error.getMessage());
}
}
adapter
public class HomeAdapter extends RecyclerView.Adapter {
public static final int TYPE_BANNER = 0;
public static final int TYPE_TOPIC = 1;
public static final int TYPE_ROUTE = 2;
private List<HomeBanner> banners = new ArrayList<>();
private List<HomeTopic> topics = new ArrayList<>();
private List<HomeRoute> routes = new ArrayList<>();
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case TYPE_BANNER:
View bannerView = HomeBannerViewHolder.getView(parent.getContext());
return new HomeBannerViewHolder(bannerView);
case TYPE_TOPIC:
View topicView = View.inflate(parent.getContext(), R.layout.item_home_topic,null);
// View topicView = HomeTopicViewHolder.getView(parent.getContext());
return new HomeTopicViewHolder(topicView);
case TYPE_ROUTE:
View routeView = View.inflate(parent.getContext(), R.layout.item_home_route,null);
// View routeView = HomeRouteViewHolder.getView(parent.getContext());
return new HomeRouteViewHolder(routeView);
default:
// View defaultView = new View(parent.getContext());
View view = EmptyViewHolder.getView(parent.getContext());
return new EmptyViewHolder(view);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(position == 0){
onBindBannerViewHolder(holder);
}else if(position>0 && position<topics.size()+1){
onBindTopicViewHolder(holder,position-1);
}else {
onBindRouteViewHolder(holder,position-topics.size()-1);
}
}
private void onBindRouteViewHolder(RecyclerView.ViewHolder holder, int position) {
HomeRouteViewHolder routeViewHolder = (HomeRouteViewHolder) holder;
routeViewHolder.setData(routes.get(position));
}
private void onBindTopicViewHolder(RecyclerView.ViewHolder holder,int position) {
HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
topicViewHolder.setData(topics.get(position));
}
private void onBindBannerViewHolder(RecyclerView.ViewHolder holder) {
HomeBannerViewHolder bannerViewHolder = (HomeBannerViewHolder) holder;
bannerViewHolder.setData(banners);
}
#Override
public int getItemCount() {
return 1 + topics.size()+routes.size();
}
#Override
public int getItemViewType(int position) {
if(position == 0){
return TYPE_BANNER;
}else if(position<topics.size()+1){
return TYPE_TOPIC;
}else {
return TYPE_ROUTE;
}
}
public void setBanners(List<HomeBanner> list){
banners.clear();
banners.addAll(list);
notifyDataSetChanged();
}
public void setTopics(List<HomeTopic> list) {
topics.clear();
topics.addAll(list);
notifyDataSetChanged();
}
public void setRoutes(List<HomeRoute> list) {
routes.clear();
routes.addAll(list);
notifyDataSetChanged();
}
public void appendRoutes(List<HomeRoute> list) {
routes.addAll(routes.size(),list);
notifyItemRangeInserted(getItemCount(),list.size());
}
}
holder
public class HomeTopicViewHolder extends BaseViewHolder<HomeTopic> {
private static SimpleDraweeView content_iv ;
private static TextView home_topic_title ;
private static TextView home_topic_discription ;
private int height;
public static View getView(Context context) {
View topicView = View.inflate(context, R.layout.item_home_topic,null);
return topicView;
}
public HomeTopicViewHolder(View itemView) {
super(itemView);
content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
if(content_iv!=null){
content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
}
if(home_topic_title!=null){
home_topic_title = (TextView) itemView.findViewById(R.id.home_topic_title);
}
if(home_topic_discription!=null){
home_topic_discription = (TextView) itemView.findViewById(R.id.home_topic_discription);
}
if(height==0){
SharedPreferences sp = SharedPreferenceHelper.getInstance().getSharedPreference(itemView.getContext(), SharedPreferenceHelper.EnumSPName.CONFIG);
int scale = sp.getInt(SharedPreferenceHelper.EnumSPName.windowWidth, 0);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(scale,scale);
content_iv.setLayoutParams(layoutParams);
}
}
#Override
protected void inflateView(HomeTopic data) {
NetworkImageLoader loader = NetworkImageLoader.getInstance();
loader.setUrlToSimpleDraweeView(data.getImage(),content_iv);
home_topic_title.setText(data.getName());
home_topic_discription.setText(String.format(getResources().getString(R.string.guider_route),data.getGuide(), data.getRoute()));
}
public void setOffset() {
int itemViewHeight = itemView.getHeight();
int imageViewHeight = content_iv.getHeight();
int parentOffsetMax = (getParentHeight() + itemViewHeight) / 2;
int offsetMax = imageViewHeight - itemViewHeight;
float y = itemView.getY();
float location = y + itemViewHeight/2;
float v = location - getParentHeight() / 2;
float percent = v/parentOffsetMax;
int margin = (int) ((offsetMax/2)*(percent + 1));
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) content_iv.getLayoutParams();
layoutParams.setMargins(0,-margin,0,0);
content_iv.setLayoutParams(layoutParams);
}
public void setParentHeight(int height) {
this.height = height;
}
public int getParentHeight() {
return height;
}
}

Categories

Resources