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)
Related
I have Recycler view where I am displaying the items with Item name, Item rate and quantity of the items which is increased and decreased by +/- buttons respectively. now, i want to get all the values from each item of the Recycler view and send it over the server or save it to local database so how to achieve this.?
TeaListAdapter.java
public class TeaListAdapter extends RecyclerView.Adapter<TeaListAdapter.MyViewHolder> {
PlaceOrderActivity.DataTransferInterface dtInterface;
//private int num=0;
private List<TeaListPOJO> teaItemList;
private Context mContext;
private Cursor cursor;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tvitemName, tvitemRate,tvcount; //number
public ImageView ivItemImg,ivPlus,ivMinus;
public Button btnIncrease,btnDecrease;
RecyclerView.ViewHolder holder;
public MyViewHolder(View view) {
super(view);
tvitemName = (TextView) view.findViewById(R.id.txt_item_name);
tvitemRate = (TextView) view.findViewById(R.id.txt_item_price);
ivItemImg= (ImageView) view.findViewById (R.id.iv_item);
ivPlus=(ImageView) view.findViewById (R.id.row_view_final_order_iv_plus);
ivMinus=(ImageView) view.findViewById (R.id.row_view_final_order_iv_minus);
tvcount=(TextView) view.findViewById (R.id.row_view_final_order_tv_count);
}
}
public TeaListAdapter(List<TeaListPOJO> teaItemList) {
this.mContext=mContext;
this.cursor=cursor;
this.teaItemList = teaItemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_placeorder_items, parent, false);
return new MyViewHolder (itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final TeaListPOJO tealist = teaItemList.get(position);
holder.tvitemName.setText(tealist.getItemName ());
holder.tvitemRate.setText(AppConstants.INDIAN_RUPEE_SIGN.concat (tealist.getItemRate ()));
holder.ivPlus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
//count++;
count = Integer.parseInt(holder.tvcount.getText().toString());
holder.tvcount.setText(String.valueOf(count+ 1));
tealist.setCount (count);
Log.e ("count", String.valueOf (count));
}
});
holder.ivMinus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
if(count>0) {
//count--;
count = Integer.parseInt (holder.tvcount.getText ().toString ());
holder.tvcount.setText (String.valueOf (count - 1));
tealist.setCount (count);
}
}
});
byte[] decodedString = new byte[0];
try {
decodedString = Base64.decode(tealist.getImageStr(), Base64.DEFAULT);
// tenantModelPOJO.setLogo(decodedString);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivItemImg.setImageBitmap(Bitmap.createScaledBitmap(bmp, 50, 50,false));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return teaItemList.size();
}
}
PlaceOrderActivity.java
public class PlaceOrderActivity extends AppCompatActivity implements AppConstants, View.OnClickListener, WLAPIcalls.OnAPICallCompleteListener {
private List<TeaListPOJO> teaList = new ArrayList<> ();
private RecyclerView recyclerView;
private TeaListAdapter mAdapter;
private View view;
private Button btnPlaceorder;
EditText edtmsg;
public String str;
private Context mContext = PlaceOrderActivity.this;
private int itemCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_place_order);
setRecyclerView (view);
getallTeaItems ();
}
List<TeaListPOJO> getTeaItemList(String str) {
Gson gson = new Gson ();
Type listType = new TypeToken<List<TeaListPOJO>> () {
}.getType ();
List<TeaListPOJO> myModelList = gson.fromJson (str, listType);
return myModelList;
}
private List<TeaListPOJO> getallTeaItems() {
if (new AppCommonMethods (mContext).isNetworkAvailable ()) {
WLAPIcalls mAPIcall = new WLAPIcalls (mContext, getString (R.string.getTeaItem), this);
mAPIcall.GetTeaItemList ();
} else {
Toast.makeText (mContext, R.string.no_internet, Toast.LENGTH_SHORT).show ();
}
return null;
}
void setRecyclerView(View view) {
recyclerView = (RecyclerView) findViewById (R.id.recycler_view);
mAdapter = new TeaListAdapter (teaList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager (getApplicationContext ());
recyclerView.setLayoutManager (mLayoutManager);
recyclerView.setItemAnimator (new DefaultItemAnimator ());
recyclerView.setAdapter (mAdapter);
}
#Override
public void onClick(View view) {
}
#Override
public void onAPICallCompleteListner(Object item, String flag, String result) throws JSONException {
if (getString (R.string.getTeaItem).equals (flag)) {
Log.e ("Result", result);
teaList = getTeaItemList (result);
setRecyclerView (view);
}
}
}
So you are already passing the arraylist (teaItemList) in your constructor of your adapter. Since the reference is same you can use the same array list for saving or sending it to the database.
Since name and price of items are same, You need to get the value only like for if user clicks + = String.valueOf(count+ 1) and for (-) = String.valueOf(count - 1)
So add one more field like (int count) in teaPOJO and
whenever user clicks + :
Do this
holder.ivPlus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
TeaPojo teaPojo = teaItemList.get(getAdapterPosition);
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
//count++;
count = Integer.parseInt(holder.tvcount.getText().toString());
holder.tvcount.setText(String.valueOf(count+ 1));
teaPojo.setCount(count);
Log.e ("count", String.valueOf (count));
}
});
User clicks - :
holder.ivMinus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
TeaPojo teaPojo = teaItemList.get(getAdapterPosition);
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
if(count>0) {
//count--;
count = Integer.parseInt(holder.tvcount.getText().toString ());
holder.tvcount.setText (String.valueOf (count - 1));
teaPojo.setCount(count);
tealist.setCount (count);
}enter code here
}
});
// if you want to save in db from activity itself only
saveToDb(teaItemList);
// if you want to send to server from activity itself only
handleSendToServer(teaItemList);
I have a model class:
public class Home_Model_ViewPager {
public String buttonLink;
public String tipsDescription;
public String tipsButton;
public Context context;
public Home_Model_ViewPager( Context context, String tipsDescription, String tipsButton, String buttonLink) {
this.context = context;
this.tipsDescription = tipsDescription;
this.tipsButton = tipsButton;
this.buttonLink = buttonLink;
}
public String getButtonLink() {
return buttonLink;
}
public void setButtonLink(String buttonLink) {
this.buttonLink = buttonLink;
}
public String getTipsDescription() {
return tipsDescription;
}
public void setTipsDescription(String tipsDescription) {
this.tipsDescription = tipsDescription;
}
public String getTipsButton() {
return tipsButton;
}
public void setTipsButton(String tipsButton) {
this.tipsButton = tipsButton;
}
}
I have used this model class to use it in viewpager adapter.
So, I am using a recyclerview and setting data to it. Now I have a problem that I have a viewpager in recycleritem. I want to return the size of viewpager adapter of any element in Home_Model_ViewPager as each element has diff size.
This is what I tried in ViewPagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
List<Home_Model_ViewPager> totalList;
public ViewPagerAdapter(Context context, List<Home_Model_ViewPager> totalList) {
this.context = context;
this.totalList = totalList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// Declare Variables
TextView tricksDescription;
Button tricksButton;
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
tricksDescription = itemView.findViewById(R.id.xtv_tricks_description);
tricksButton = itemView.findViewById(R.id.tricks_button);
tricksDescription.setText(Html.fromHtml(totalList.get(position).getTipsDescription()));
tricksButton.setText(Html.fromHtml(totalList.get(position).getTipsButton()));
tricksButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = totalList.get(position).getButtonLink();
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I am using volley to get the values as JSON..
private void Home() {
try {
if (getActivity()!=null)
Commonfunctions.LoadPreferences(getActivity());
System.out.println("Authtoken:" + Commonfunctions.Token_key);
appservice.View_All_Events(Commonfunctions.Token_key, String.valueOf(pagenumber), new Server_Callback() {
#Override
public void onSuccess(String response) {
System.out.println("HOME Response :" + response);
try {
JSONObject signObject = new JSONObject(response);
String resStatus = signObject.getString(AppConstants.STATUS);
String resCode = signObject.getString(AppConstants.CODE);
String resMsg = signObject.getString(AppConstants.MSG);
if (resCode.equals(AppConstants.SUCCESS_CODE)) {
JSONArray allEvents = signObject.getJSONArray("all");
System.out.println("INNER Response :" + allEvents);
for (int i = 0; i < allEvents.length(); i++) {
JSONObject innerObj1 = allEvents.getJSONObject(i);
String backgroundImg = innerObj1.getString("backg_img");
String declinedCount = innerObj1.getString("decli_count");
String acceptedCount = innerObj1.getString("accep_count");
String invitedCount = innerObj1.getString("invi_count");
String messages = innerObj1.getString("i_chat");
String name = innerObj1.getString("name");
String eventTime = innerObj1.getString("duration");
String userPhoto = innerObj1.getString("photo");
JSONArray viewpagerEvents = innerObj1.getJSONArray("action");
for (int u = 0; u < viewpagerEvents.length(); u++) {
JSONObject innerObj3 = viewpagerEvents.getJSONObject(u);
String buttonText = innerObj3.getString("text");
String tipsDesc = innerObj3.getString("action_text");
String buttonLink = innerObj3.getString("button_link");
final Home_Model home_data = new Home_Model(name, messages,invitedCount,declinedCount,acceptedCount,eventTime,
userPhoto,backgroundImg);
data.add(home_data);
final Home_Model_ViewPager home_viewpager = new Home_Model_ViewPager(getContext(),tipsDesc,buttonText, buttonLink);
viewPagerData.add(home_viewpager);
}
}
adapter = new HomeAdapter(getContext(),data);
pagerAdapter = new ViewPagerAdapter(getActivity(), viewPagerData);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (adapter.getItemCount()==0) {
noeventLayout.setVisibility(View.VISIBLE);
}
else {
noeventLayout.setVisibility(View.GONE);
}
} else if (resCode.equals(AppConstants.UPDATE_CODE)) {
//Version_Update versionUpdate=new Version_Update(SignIn.this,response);
} else {
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Commonfunctions.showerrorsnackbar(resMsg, getActivity(), parentLayout);
}
} catch (JSONException e) {
e.printStackTrace();
}
}//on success close
});//server callback closed
} catch (Exception e) {
e.printStackTrace();
}
}
HomeAdapter:
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<Home_Model> students;
public HomeAdapter(Context context,List<Home_Model> students) {
this.context = context;
this.students = students;
}
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_home_list, viewGroup, false);
return new HomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final HomeAdapter.ViewHolder holder, final int position) {
holder.title.setText(students.get(position).getName());
holder.invited.setText(students.get(position).getInvited());
holder.accepted.setText(students.get(position).getAccept());
holder.declined.setText(students.get(position).getDecline());
holder.eventTime.setText(students.get(position).getEvent_time());
holder.messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(),Chat_view.class));
}
});
holder.viewPager.setAdapter(pagerAdapter);
holder.dots = new ImageView[holder.dotsCount];
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i] = new ImageView(context);
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray ));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
holder.sliderDots.addView(holder.dots[i], params);
}
holder.dots[0].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
holder.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray));
}
holder.dots[position].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (students.get(position).getMessages().contentEquals("false")) {
holder.status.setVisibility(View.INVISIBLE);
}
else {
holder.status.setVisibility(View.VISIBLE);
}
holder.status.setVisibility(View.INVISIBLE);
try {
Glide.with(getActivity()).load(students.get(position).getProimg()).into(holder.pro_img);
Glide.with(getActivity()).load(students.get(position).getBgimg()).into(holder.card_main);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return students.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, messages, invited, accepted, declined, eventTime;
private PorterShapeImageView pro_img;
ImageView card_main, status;
ViewPager viewPager;
LinearLayout sliderDots;
private ImageView[] dots;
private int dotsCount;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.xtv_welcome);
messages = itemView.findViewById(R.id.xtv_message);
invited = itemView.findViewById(R.id.xtv_invited);
accepted = itemView.findViewById(R.id.xtv_accepted);
declined = itemView.findViewById(R.id.xtv_decline);
eventTime = itemView.findViewById(R.id.contact_number);
pro_img = itemView.findViewById(R.id.pro_pic);
card_main = itemView.findViewById(R.id.card_main);
status = itemView.findViewById(R.id.incoming_image);
viewPager = itemView.findViewById(R.id.viewPagerTips);
sliderDots = itemView.findViewById(R.id.sliderDots);
dotsCount = pagerAdapter.getCount();
}
}
}
Please try to make one different array list for your viewpager's adapter:
ArrayList<Home_Model_ViewPager> tempList = new ArrayList<>();
for(int k=0;k<viewpagerData.size();k++){
Home_Model_ViewPager object = viewPagerData.get(k);
if(object.getTripDesc()!=null && object.getTripDesc().length() >0){
tempList.add(object);
}
}
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity(), tempList);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
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);
I have list of data in MenuItemsModel(model) class along with image url and two strings fetching from the API. How can I load the image url with Picasso and how to bind the loaded image to recyclerview?
Here is my code
Code for model class
public class MenuItemsModel {
public int image;
public String itemName;
public String itemCost;
public MenuItemsModel(int image, String itemName, String itemCost) {
this.image = image;
this.itemName = itemName;
this.itemCost = itemCost;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCost() {
return itemCost;
}
public void setItemCost(String itemCost) {
this.itemCost = itemCost;
}
}
Here is my RecyclerAdapter class
public class MenusRecyclearView extends
RecyclerView.Adapter<MenusRecyclearView.RecyclerViewHolder> {
Context context;
List<MenuItemsModel> menuItemsModel;
public MenusRecyclearView(Context context, List<MenuItemsModel> menuItemsModel) {
this.context = context;
this.menuItemsModel = menuItemsModel;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_items_list, parent, false);
return new RecyclerViewHolder(view, context, menuItemsModel);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.imageView.setImageResource(menuItemsModel.get(position).getImage());
holder.ItemName.setText(menuItemsModel.get(position).getItemName());
holder.ItemCost.setText(menuItemsModel.get(position).getItemCost());
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return menuItemsModel.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView imageView;
public TextView ItemName, ItemCost;
Context ctx;
List<MenuItemsModel> menuItemsModels;
public RecyclerViewHolder(View view, Context ctx, List<MenuItemsModel> menuItemsModels) {
super(view);
this.ctx = ctx;
this.menuItemsModels = menuItemsModels;
view.setOnClickListener(this);
imageView = view.findViewById(R.id.biriyani_menu_item);
ItemName = view.findViewById(R.id.item_name);
ItemCost = view.findViewById(R.id.item_cost);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
MenuItemsModel model = this.menuItemsModels.get(position);
Intent i = new Intent(this.ctx, CategoryDescription.class);
i.putExtra("ImageId", model.getImage());
i.putExtra("ItemName", model.getItemName());
i.putExtra("ItemCost", model.getItemCost());
this.ctx.startActivity(i);
}
}
}
** Here is my MainActivity class **
public class BiryanisActivity extends AppCompatActivity implements
View.OnClickListener, NetworkOperationListener{
RecyclerView recyclerView;
MenusRecyclearView menusRecyclearView;
RecyclerView.LayoutManager layoutManager;
List<MenuItemsModel> menuItemsModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.biriyanis_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
menuItemsModel = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclearview_menu);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
menusRecyclearView = new MenusRecyclearView(this, menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
HttpAdapter.getMenuItemsList(this,"MenuItemsList");
//prepareData();
}
/* public void prepareData() {
MenuItemsModel data = new MenuItemsModel(R.drawable.item5, "Chicken Dhum
Biriyani", "Rs.240");
menuItemsModel.add(data);
MenuItemsModel data1 = new MenuItemsModel(R.drawable.item2, "Chicken
Chilli Biriyani", "Rs.260");
menuItemsModel.add(data1);
MenuItemsModel data2 = new MenuItemsModel(R.drawable.item3, "Chicken
Tandhuri Biriyani", "Rs.280");
menuItemsModel.add(data2);
MenuItemsModel data3 = new MenuItemsModel(R.drawable.item4, "Chicken
Moghulai Biriyani", "Rs.230");
menuItemsModel.add(data3);
MenuItemsModel data4 = new MenuItemsModel(R.drawable.item1, "Chicken
Special Biriyani", "Rs.220");
menuItemsModel.add(data4);
MenuItemsModel data5 = new MenuItemsModel(R.drawable.item1, "Chicken
Mandi Biriyani", "Rs.210");
menuItemsModel.add(data5);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onClick(View view) {
}
#Override
public void operationCompleted(NetworkResponse response) {
if (response.getStatusCode() == 200) {
if (response.getTag().equals("MenuItemsList")) {
try {
JSONObject jsonObjects = new JSONObject(response.getResponseString());
if (jsonObjects.getString("Data").equals("null")) {
Toast.makeText(this, "No Data Found", Toast.LENGTH_SHORT).show();
return;
}
JSONArray jsonArray = jsonObjects.getJSONArray("Data");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
MenuItemsModel data = new Gson().fromJson(jsonObject.toString(),MenuItemsModel.class);
//Picasso.with(this).load(data.getImage()).into();
Picasso.with(this).load(data.getImage()).into(holder.imageView);
/* int image = data.getImage();
String name = data.getItemName();
String cost = data.getItemCost();
//picaso(image, imageView);*/
menuItemsModel.add(data);
}
MenusRecyclearView menusRecyclearView = new MenusRecyclearView(this,menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Failed to Connect Server, Please try again later", Toast.LENGTH_SHORT).show();
}
}
public void picaso(String path, ImageView imageView) {
if (!path.equals("")) {
Picasso.with(this).load(path).into(imageView);
}
}
}
Well, you are on the right track. You need to uncomment this line:
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
And, the .getImage() needs to become your URL. That means, you should store the image url inside MenuItemsModel. Now your image is an int, and should be of a type of String so you can pass the URL to it.
Also see this answer here:
https://stackoverflow.com/a/41157030/5457878
I have a recyclerview that display news.
News is composed by name_news,image_news,time_news.
I am getting the data from mysqldatabse.
This is my adapter class:
public class PostAdapter2 extends RecyclerView.Adapter<PostAdapter2.ViewHolder>{
public Context c;
public FragmentManager mContext;
public ArrayList<News_data> original_items = new ArrayList<>();
public ArrayList<News_data> filtered_items = new ArrayList<>();
public ArrayList<Simplenews_data> original_items2 = new ArrayList<>();
public ArrayList<Simplenews_data> filtered_items2 = new ArrayList<>();
// ItemFilter mFilters = new ItemFilter();
public PostAdapter2(Context c, ArrayList<News_data> postList) {
this.c = c;
this.original_items = postList;
this.filtered_items = postList;
}
public PostAdapter2(FragmentManager mContext, ArrayList<Simplenews_data> postList) {
this.mContext = mContext;
this.original_items2 = postList;
this.filtered_items2 = postList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_news, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
try {
final Simplenews_data post = filtered_items2.get(position);
PicassoClient.downloadImage(c, post.getImage_simplenews(), holder.image_news);
holder.txt_news_title.setText(post.getName_simplenews());
holder.txt_date.setText(post.getTime_simplenews());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick() {
Bundle x = new Bundle();
x.putString("news_title", post.getName_simplenews());
x.putString("news", post.getDesc_simplenews());
x.putString("image",post.getImage_simplenews());
x.putString("time",post.getTime_simplenews());
x.putString("date",post.getDate_simplenews());
Fragment descriptionFragment = new DescriptionFragment();
FragmentTransaction transaction = mContext.beginTransaction();
descriptionFragment.setArguments(x);
transaction.replace(R.id.framelayout, descriptionFragment).addToBackStack(null).commit();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return filtered_items2.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
TextView txt_news_title,txt_date;
ImageView image_news;
public ViewHolder(View itemView) {
super(itemView);
txt_news_title = (TextView) itemView.findViewById(R.id.txt_news_title);
txt_date = (TextView) itemView.findViewById(R.id.txt_timedate);
image_news = (ImageView) itemView.findViewById(R.id.image_news);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
this.itemClickListener.onItemClick();
}catch (Exception e)
{
e.printStackTrace();
}
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
}
}
I am using a PHP interface to add news.
The getTime_simplenews() contains the news sumbmitted time format as : 14:00
So i want to display the immediate news in Top of recyclerview not under the previous news.
Thanks a lot.
UPDATED :
public class Simplenews_data {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
Fragment Code:
public void parseJson2(String response) {
try {
JSONArray array = new JSONArray(response);
JSONObject jsonObject = null;
post_array2.clear();
Simplenews_data p;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
int id_simplenews = jsonObject.getInt("id_simplenews");
String name_simplenews = jsonObject.getString("name_simplenews");
String image_simplenews = jsonObject.getString("image_simplenews");
String desc_simplenews = jsonObject.getString("desc_simplenews");
String time_simplenews = jsonObject.getString("time_simplenews");
String date_simplenews = jsonObject.getString("date_simplenews");
p = new Simplenews_data();
p.setId_simplenews(id_simplenews);
p.setName_simplenews(name_simplenews);
p.setImage_simplenews(image_simplenews);
p.setDesc_simplenews(desc_simplenews);
p.setTime_simplenews(time_simplenews);
p.setDate_simplenews(date_simplenews);
post_array2.add(p);
}
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
e.printStackTrace();
}
adapter = new PostAdapter2(getFragmentManager(), post_array2);
recycler_post.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
I have updated your model class and implemented Comparable to it
public class Simplenews_data implements Comparable<Simplenews_data> {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
#Override
public int compareTo(MyObject o) {
Date newDate = formatDateTime(o.getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
Date inputDate = formatDateTime(getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
return inputDate.compareTo(newDate);
}
public Date formatDateTime(String date, String fromFormat, String toFormat) {
Date d = null;
try {
d = new SimpleDateFormat(fromFormat, Locale.US).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new SimpleDateFormat(toFormat, Locale.US).parse(d);
}
}
Sort the list using below code
Collections.sort(yourList);