I developed a vocabulary app that has a Recycler View in main activity and shows two column of database: unit number and Unit name.When I click on each item it goes to another activity called inner page that has 6 text views and it must show other items of that row like word definition unit number spell meaning and part of speech. But unfortunately text views are empty and it shows only one value which is unit number.Please take a look at my codes and tell me what I missed.
Here's my codes:
Main page:
public class TabWord extends Fragment {
private RecyclerView recyclerView;
private ArrayList<WordItem> items = new ArrayList<>();
private WordTab adapter;
private DatabaseHelper databaseHelper;
private Cursor cursor ;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.tab_word, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerview_word);
adapter = new WordTab(items, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
loadDatabase();
return viewGroup;
}
public void loadDatabase() {
databaseHelper = new DatabaseHelper(getActivity());
try {
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from ielts");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
WordItem item = new WordItem();
item.setUnitName(cursor.getString(2));
item.setUnitNumber(cursor.getString(1));
items.add(item);
} while (cursor.moveToNext());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new WordTab(items, getActivity());
adapter.setOnTapListener(new OnTapListener() {
#Override
public void OnTapView(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class WordTab extends RecyclerView.Adapter<WordTab.ViewHolder> {
public static List<WordItem> wordItems;
private Context context;
private OnTapListener onTapListener;
public WordTab(List<WordItem> wordItems, Context context) {
this.wordItems = wordItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_word, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
WordItem wordItem = wordItems.get(position);
holder.unitNumber.setText(wordItem.getUnitNumber());
holder.unitName.setText(wordItem.getUnitName());
holder.cardView.setId(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onTapListener != null) {
onTapListener.OnTapView(position);
int position = v.getId();
Intent intent = new Intent(context, InnerPage.class);
intent.putExtra("name", "words");
intent.putExtra("id", position + "");
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return wordItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView unitName, unitNumber;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
unitName = itemView.findViewById(R.id.unit_name);
unitNumber = itemView.findViewById(R.id.unit_number);
cardView= itemView.findViewById(R.id.card_view_word);
}
}
public void setOnTapListener(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
}
Model:
public class WordItem {
private int id;
private String unitNumber;
private String unitName;
private String word;
private String phonetic,pos,persian,definition;
public WordItem() {
this.unitName = unitName;
this.unitNumber = unitNumber;
this.word = word;
this.phonetic = phonetic;
this.pos = pos;
this.persian = persian;
this.definition = definition;
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getPersian() {
return persian;
}
public void setPersian(String persian) {
this.persian = persian;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
Inner Page:
public class InnerPage extends AppCompatActivity {
private int id;
private String unitNumber,word,phonetic,pos,persian,definition;
private TextView unitTxt,wordTxt,phoneticTxt,posTxt,persianTxt,definitionTxt;
private int layoutId;
private String pageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inner_page);
Bundle extras = getIntent().getExtras();
if (extras != null) {
layoutId = Integer.parseInt(extras.getString("id"));
pageName = extras.getString("name");
if (pageName.equals("words")){
id = WordTab.wordItems.get(layoutId).getId();
unitNumber = WordTab.wordItems.get(layoutId).getUnitNumber();
word = WordTab.wordItems.get(layoutId).getWord();
phonetic = WordTab.wordItems.get(layoutId).getPhonetic();
pos = WordTab.wordItems.get(layoutId).getPos();
persian = WordTab.wordItems.get(layoutId).getPersian();
definition = WordTab.wordItems.get(layoutId).getDefinition();
}
}
unitTxt = findViewById(R.id.unit);
wordTxt = findViewById(R.id.word);
phoneticTxt = findViewById(R.id.phonetic);
posTxt = findViewById(R.id.txtSpell);
persianTxt = findViewById(R.id.farMean);
definitionTxt = findViewById(R.id.definition);
unitTxt.setText(unitNumber);
wordTxt.setText(word);
phoneticTxt.setText(phonetic);
posTxt.setText(pos);
persianTxt.setText(persian);
definitionTxt.setText(definition);
}
}
Related
I have a RecyclerView with an ImageView being a part of the items. I want to hide the ImageView from an item in the RecyclerView if a certain condition is met. How can I do that? I am attaching the image of how I want it to look like.
I am just defining the ImageViews in my xml layout file, so I cannot figure out how to actually remove it based on a certain condition in my android activity. I am attaching the code for the adapter class and my activity as well.
Here is the code for my adapter class
Adapter Class
public class ReportAdapter extends RecyclerView.Adapter<ReportAdapter.ReportViewHolder> {
private ArrayList<ReportItem> reportlist;
private OnItemClickListener mListener;
private Context mContext;
public ReportAdapter(ArrayList<ReportItem> reportlist, Context context) {
this.reportlist = reportlist;
this.mContext = context;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ReportViewHolder extends RecyclerView.ViewHolder {
public TextView departureDate;
public TextView flightNumber;
public View relativelayout;
public ReportViewHolder(#NonNull View itemView, OnItemClickListener listener, Context context) {
super(itemView);
departureDate = itemView.findViewById(R.id.departureDaterecyclerview);
flightNumber = itemView.findViewById(R.id.flightnumberrecyclerview);
relativelayout = itemView.findViewById(R.id.relativeLayoutReports);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
#NonNull
#Override
public ReportViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.report_listing_item, parent, false);
ReportViewHolder rvh= new ReportViewHolder(v,mListener,mContext);
return rvh;
}
#SuppressLint("ResourceAsColor")
#Override
public void onBindViewHolder(#NonNull ReportViewHolder holder, int position) {
ReportItem currentItem = reportlist.get(position);
if(position%2==0){
holder.relativelayout.setBackgroundColor(mContext.getResources().getColor(R.color.reportlistingteal));
} else {
holder.relativelayout.setBackgroundColor(mContext.getResources().getColor(R.color.reportlistinglightteal));
}
holder.departureDate.setText((currentItem.getDepartureDate()));
holder.flightNumber.setText(currentItem.getFlightNumber());
}
Here is the code for my activity file
Activity file
public class ReportListingActivity extends AppCompatActivity {
private Button uploadAllBtn;
private EditText searchFlights;
private RecyclerView mRecyclerView;
private ReportAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
ArrayList<ReportItem> reportitems = new ArrayList<>();
private FlightViewModel flightViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_listing);
uploadAllBtn = findViewById(R.id.uploadAllReports);
searchFlights = findViewById(R.id.searchFlightText);
mRecyclerView = findViewById(R.id.recyclerView);
flightViewModel = new ViewModelProvider(this).get(FlightViewModel.class);
flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
#Override
public void onChanged(List<Flight> flight_list) {
if (flight_list.size() == 0) return;
String flightno = flight_list.get(0).getFlightNumber();
String flightdate = flight_list.get(0).getDate();
String[] flight_details = new String[2];
flight_details[0]= flightno;
flight_details[1] = flightdate;
Log.v("pp", flight_details[0]);
for(int i = 0; i <flight_list.size();i++){
String flightnumber = flight_list.get(i).getFlightNumber();
String departuredate = flight_list.get(i).getDate();
reportitems.add(new ReportItem(flightnumber,departuredate));
}
mRecyclerView.getAdapter().notifyDataSetChanged();
flightViewModel.getAllFlights().removeObservers(ReportListingActivity.this);
}
});
mLayoutManager = new LinearLayoutManager(ReportListingActivity.this);
mAdapter = new ReportAdapter(reportitems, ReportListingActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
Report Item
public class ReportItem {
private String departureDate;
private String flightNumber;
public ReportItem(String departureDate, String flightNumber) {
this.departureDate = departureDate;
this.flightNumber = flightNumber;
}
public String getDepartureDate() {
return departureDate;
}
public String getFlightNumber() {
return flightNumber;
}
}
Add a boolean flag to your ReportItem class for each RecyclerView item. You will need to specify which rows show or hide this field when each item is created:
public class ReportItem {
private String departureDate;
private String flightNumber;
private Boolean showMailIcon;
public ReportItem(String departureDate, String flightNumber, Boolean showMailIcon) {
this.departureDate = departureDate;
this.flightNumber = flightNumber;
this.showMailIcon = showMailIcon
}
public String getDepartureDate() {
return departureDate;
}
public String getFlightNumber() {
return flightNumber;
}
public String getShowMailIcon() {
return showMailIcon;
}
}
Then update the onBindViewHolder() method override to use this flag to show/hide the ImageView:
#Override
public void onBindViewHolder(#NonNull ReportViewHolder holder, int position) {
ReportItem currentItem = reportlist.get(position);
if (currentItem.getShowMailIcon() == true) {
holder.mailIcon.setVisibility(View.VISIBLE);
} else {
holder.mailIcon.setVisibility(View.GONE);
}
//.......
}
I'm trying to read everything in my external text file and put it into an array list that is send to another class via a parcel class. Although I can get the strings set on textview, but not the image.
One of the lines in my external text file looks like:
McDonalds| Any McDonalds outlet| Applicable to any lunch meal set| Buy 1 get 1 free| 1 Aug - 31 Aug| RM 32.00| RM 16.00| icon_nandos.png
MainActivity.java:
public class MainActivity extends AppCompatActivity implements listAdapter.sendInfo{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_fragment lf = new list_fragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.mainAct, lf);
fragmentTransaction.commit();
}
#Override
public void detailInfo(outletData outDat, int pos) {
fragmentDetail fd = fragmentDetail.newInstance(outDat);
getSupportFragmentManager().beginTransaction()
.replace(R.id.mainAct, fd)
.addToBackStack(null)
.commit();
}
}
list_fragment.java:
public class list_fragment extends Fragment {
ArrayList<outletData> outletDatas = new ArrayList<outletData>();
BufferedReader bufferedReader = null;
String food;
public View onCreateView( LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
RecyclerView recyclerView = view.findViewById(R.id.fragRecycler);
outletDatas.clear();
try{
bufferedReader = new BufferedReader(new
InputStreamReader(getContext().getAssets().open("food_catalog.txt")));
while ((food = bufferedReader.readLine())!=null) {
if (!food.equals("")) {
String[] foodInfo = food.split("\\|");
outletDatas.add(new outletData(foodInfo[0], foodInfo[1], foodInfo[2], foodInfo[3], foodInfo[4], foodInfo[5], foodInfo[6], foodInfo[7]));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
listAdapter mylistAdapter = new listAdapter(outletDatas, getContext());
recyclerView.setAdapter(mylistAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
outletData.java:
package com.example.user.assignmentthreethree;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Parcel;
import android.os.Parcelable;
public class outletData implements Parcelable {
private String name, location, details, deals, offerPeriod, normalPrice, discountPrice, imagePath;
public outletData(String name, String location, String details, String deals, String offerPeriod, String normalPrice, String discountPrice, String imagePath) {
this.name = name;
this.location = location;
this.details = details;
this.deals = deals;
this.offerPeriod = offerPeriod;
this.normalPrice = normalPrice;
this.discountPrice = discountPrice;
this.imagePath = imagePath;
}
private outletData(Parcel in) {
name = in.readString();
location = in.readString();
details = in.readString();
deals = in.readString();
offerPeriod = in.readString();
normalPrice = in.readString();
discountPrice = in.readString();
imagePath = in.readString();
}
public static final Creator<outletData> CREATOR = new Creator<outletData>() {
#Override
public outletData createFromParcel(Parcel in) {
return new outletData(in);
}
#Override
public outletData[] newArray(int size) {
return new outletData[size];
}
};
public String getName() {
return name;
}
public String getLocation() {
return location;
}
public String getDetails() {
return details;
}
public String getDeals() {
return deals;
}
public String getOfferPeriod() {
return offerPeriod;
}
public String getNormalPrice() {
return normalPrice;
}
public String getDiscountPrice() {
return discountPrice;
}
public String getImagePath() {
return imagePath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(location);
parcel.writeString(details);
parcel.writeString(deals);
parcel.writeString(offerPeriod);
parcel.writeString(normalPrice);
parcel.writeString(discountPrice);
parcel.writeString(imagePath);
}
}
listAdapter.java:
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;
listAdapter(ArrayList<outletData> outletDataFromFragment) {
this.outletDataFromFragment = outletDataFromFragment;
}
#Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
this.mContext = viewGroup.getContext();
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull listAdapter.ViewHolder viewHolder, int i) {
outletData data = outletDataFromFragment.get(i);
viewHolder.listName.setText(data.getName());
viewHolder.listDeal.setText(data.getDeals());
viewHolder.listOffer.setText(data.getOfferPeriod());
// viewHolder.listImg.setImageURI(Uri.parse(data.getImagePath()));
try {
InputStream ims = mContext.getAssets().open(""+data.getImagePath().trim());
Drawable d = Drawable.createFromStream(ims, null);
viewHolder.listImg.setImageDrawable(d);
ims.close();
} catch (IOException ex) {
return;
}
}
#Override
public int getItemCount() {
return outletDataFromFragment.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView listName, listDeal, listOffer;
ImageView listImg;
public ViewHolder(View itemView) {
super(itemView);
listName = (TextView)itemView.findViewById(R.id.txtName);
listDeal = (TextView)itemView.findViewById(R.id.txtDeals);
listOffer = (TextView)itemView.findViewById(R.id.txtOffer);
listImg = (ImageView)itemView.findViewById(R.id.imgFood);
recyclerView = (RecyclerView)itemView.findViewById(R.id.reCyclerView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
((sendInfo)view.getContext()).detailInfo(outletDataFromFragment.get(getLayoutPosition()), getLayoutPosition());
}
}
interface sendInfo {
void detailInfo(outletData outletData, int pos);
}
}
fragmentDetail.java:
public class fragmentDetail extends Fragment {
TextView fragName, fragDeal, fragOffer, fragDetail, fragOldPrice, fragNewPrice, fragLocation;
ImageView fragImage;
outletData OD;
Bundle bundle;
public fragmentDetail() {}
public static fragmentDetail newInstance(outletData oData) {
fragmentDetail fragmentDetail = new fragmentDetail();
Bundle b = new Bundle();
b.putParcelable("pData", oData);
fragmentDetail.setArguments(b);
return fragmentDetail;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
OD = bundle.getParcelable("pData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
fragName = (TextView)view.findViewById(R.id.frag_name);
fragDeal = (TextView)view.findViewById(R.id.frag_Deal);
fragOffer = (TextView)view.findViewById(R.id.frag_Offer);
fragDetail = (TextView)view.findViewById(R.id.frag_Detail);
fragOldPrice = (TextView)view.findViewById(R.id.frag_oldPrice);
fragNewPrice = (TextView)view.findViewById(R.id.frag_newPrice);
fragLocation = (TextView)view.findViewById(R.id.frag_location);
fragImage = (ImageView)view.findViewById(R.id.frag_image);
Toast.makeText(getContext(), OD.getImagePath(), Toast.LENGTH_LONG).show();
fragOldPrice.setPaintFlags(fragOldPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
fragName.setText(OD.getName());
fragDeal.setText(OD.getDeals());
fragOffer.setText(OD.getOfferPeriod());
fragDetail.setText(OD.getDetails());
fragOldPrice.setText(OD.getNormalPrice());
fragNewPrice.setText(OD.getDiscountPrice());
fragLocation.setText(OD.getLocation());
fragImage.setImageURI(Uri.parse(OD.getImagePath()));
return view;
}
}
Based on suggestions online I have tried trimming the string but it doesn't change the outcome. I am still learning the logic flows and syntax of Android Studio, but I don't know why its not getting the image even the images are in the same folder as the text file (Assests) and it does gets the food[7] string as icon_nandos.png when I tried printing it out.
You can try to get drawable from asset file and setting it to your imageview. Use the following code.
try {
InputStream ims = getAssets().open(""+your_image_name);
Drawable d = Drawable.createFromStream(ims, null);
mImage.setImageDrawable(d);
ims.close();
} catch(IOException ex) {
return;
}
so you need to edit your code as below.
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
ArrayList<outletData> outletDataFromFragment;
RecyclerView recyclerView;
Context mContext;
listAdapter(ArrayList<outletData> outletDataFromFragment) {
this.outletDataFromFragment = outletDataFromFragment;
}
#Override
public listAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
this.mContext = viewGroup.getContext();
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull listAdapter.ViewHolder viewHolder, int i) {
outletData data = outletDataFromFragment.get(i);
viewHolder.listName.setText(data.getName());
viewHolder.listDeal.setText(data.getDeals());
viewHolder.listOffer.setText(data.getOfferPeriod());
try {
InputStream ims = mContext.getAssets().open(""+your_image_name);
Drawable d = Drawable.createFromStream(ims, null);
viewHolder.listImg.setImageDrawable(d);
ims.close();
} catch(IOException ex) {
return;
}
}
This is the Data model
package com.basirahmad.qpaisa.data_model;
public class Banner_data_model {
private String banner_url_com_logo;
private String banner_txt_title;
private String banner_txt_name;
private String banner_txt_description;
private String banner_url_banner;
private String banner_date_publish;
private String banner_date_expire;
private String banner_max_view;
private int banner_com_id;
private int banner_schedual_id;
private int banner_id;
public String getBanner_url_com_logo() {
return banner_url_com_logo;
}
public void setBanner_url_com_logo(String banner_url_com_logo) {
this.banner_url_com_logo = banner_url_com_logo;
}
public String getBanner_txt_title() {
return banner_txt_title;
}
public void setBanner_txt_title(String banner_txt_title) {
this.banner_txt_title = banner_txt_title;
}
public String getBanner_txt_name() {
return banner_txt_name;
}
public void setBanner_txt_name(String banner_txt_name) {
this.banner_txt_name = banner_txt_name;
}
public String getBanner_txt_description() {
return banner_txt_description;
}
public void setBanner_txt_description(String banner_txt_description) {
this.banner_txt_description = banner_txt_description;
}
public String getBanner_url_banner() {
return banner_url_banner;
}
public void setBanner_url_banner(String banner_url_banner) {
this.banner_url_banner = banner_url_banner;
}
public String getBanner_date_publish() {
return banner_date_publish;
}
public void setBanner_date_publish(String banner_date_publish) {
this.banner_date_publish = banner_date_publish;
}
public String getBanner_date_expire() {
return banner_date_expire;
}
public void setBanner_date_expire(String banner_date_expire) {
this.banner_date_expire = banner_date_expire;
}
public String getBanner_max_view() {
return banner_max_view;
}
public void setBanner_max_view(String banner_max_view) {
this.banner_max_view = banner_max_view;
}
public int getBanner_com_id() {
return banner_com_id;
}
public void setBanner_com_id(int banner_com_id) {
this.banner_com_id = banner_com_id;
}
public int getBanner_schedual_id() {
return banner_schedual_id;
}
public void setBanner_schedual_id(int banner_schedual_id) {
this.banner_schedual_id = banner_schedual_id;
}
public int getBanner_id() {
return banner_id;
}
public void setBanner_id(int banner_id) {
this.banner_id = banner_id;
}
}
This is the Adapter Class
package com.basirahmad.qpaisa.adapter;
public class Banner_adapter_con extend
RecyclerView.Adapter<Banner_adapter_con.BannerViewHolder> {
private Context context;
private List<Banner_data_model> banner_data_models;
//the class canstractor;
public Banner_adapter_con(Context context, List<Banner_data_model>banner_data_models ){
this.context = context;
this.banner_data_models = banner_data_models;
}
#Override
public BannerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.banner_view,parent,false);
return new BannerViewHolder(view);
}
#Override
public void onBindViewHolder(BannerViewHolder holder, int position) {
Banner_data_model data_model = banner_data_models.get(position);
holder.company_logo.setImageURI(Uri.parse(data_model.getBanner_url_com_logo()));
holder.title.setText(data_model.getBanner_txt_title());
holder.name.setText(data_model.getBanner_txt_name());
holder.description.setText(data_model.getBanner_txt_description());
holder.banner.setImageURI(Uri.parse(data_model.getBanner_url_banner()));
}
#Override
public int getItemCount() {
return banner_data_models.size();
}
public class BannerViewHolder extends RecyclerView.ViewHolder{
private ImageView company_logo;
private ImageView banner;
private TextView title;
private TextView name;
private ReadMoreTextView description;
public BannerViewHolder(View itemView) {
super(itemView);
company_logo = (ImageView) itemView.findViewById(R.id.img_company_logo);
banner = (ImageView) itemView.findViewById(R.id.img_banner);
title = (TextView) itemView.findViewById(R.id.banner_txt_title);
name = (TextView) itemView.findViewById(R.id.banner_txt_name);
description = (ReadMoreTextView) itemView.findViewById(R.id.banner_txt_description);
}
}
}
This is the Fragment Class
package com.basirahmad.qpaisa.Fragment;
public class Banner_fragment extends Fragment {
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.banner_fragment,container,false);
Banner_data_server banner_data_server = new Banner_data_server(this.getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.banner_fragment);
banner_data_server.getBanner(new Banner_data_server.OnbannerRecevid() {
#Override
public void onRecevid(List<Banner_data_model> banner_data_models) {
Banner_adapter banner_adapter =new Banner_adapter(getActivity(),banner_data_models);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
recyclerView.setAdapter(banner_adapter);
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
It will not throw any error. It just means when you initialized your RecyclerView you've not set its adapter,
IF you still want to remove this warning, you can call
recyclerview.setAdapter(adapter)
just after its initialization. will remove the warning.
how derar this is the class the get data from server i forgot this class to add to the quastion.
enter code here the class code
package com.basirahmad.qpaisa.connect_to_server;
public class Banner_data_server {
private Context context;
public Banner_data_server(Context context){
this.context = context;
}
public void getBanner(final OnbannerRecevid onbannerRecevid){
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, Url_of_server.urlReadBanner, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<Banner_data_model> banner_data_models = new ArrayList<>();
for (int i =0;i<response.length();i++){
Banner_data_model data_model = new Banner_data_model();
try {
JSONObject jsonObject =response.getJSONObject(i);
data_model.setBanner_id(jsonObject.getInt("Banner_id"));
data_model.setBanner_txt_name(jsonObject.getString("Banner_name"));
data_model.setBanner_txt_description(jsonObject.getString("Banner_description"));
data_model.setBanner_url_banner(jsonObject.getString("location"));
data_model.setBanner_schedual_id(jsonObject.getInt("id"));
data_model.setBanner_date_publish(jsonObject.getString("date_publish"));
data_model.setBanner_date_expire(jsonObject.getString("expire_date"));
data_model.setBanner_com_id(jsonObject.getInt("com_id"));
data_model.setBanner_url_com_logo(jsonObject.getString("logo"));
banner_data_models.add(data_model);
} catch (JSONException e) {
e.printStackTrace();
}
}
onbannerRecevid.onRecevid(banner_data_models);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(arrayRequest);
}
public interface OnbannerRecevid{
void onRecevid(List<Banner_data_model> banner_data_models);
}
}
I Just need to fix the value inside Spinner when i select some value and SetEnabled True/False when i checked the CheckBox.
For example when i check the chekcbox, the spinner will be enabled and do the opposite when i uncheck the checkbox.
However it will changing randomly when i just scrolling.
This my code :
CustomListView.java
class CustomListView extends BaseAdapter {
private ArrayList<ListItem2> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListView adapter = this;
String jmlCmbSiap;
ArrayList<String> a = new ArrayList<>();
public CustomListView(Context context, ArrayList<ListItem2> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_detail_order, null);
holder = new ViewHolder();
newsItem.setAdapter(Integer.parseInt(newsItem.getJumlah()));
holder.txtBarang = (TextView) convertView.findViewById(R.id.txtBarang);
holder.txtJumlah = (TextView) convertView.findViewById(R.id.txtJumlah);
holder.txtBox = (TextView) convertView.findViewById(R.id.txtBoxes);
holder.cmbSiap = (Spinner) convertView.findViewById(R.id.cmbSiap);
holder.cmbSiap.setAdapter(newsItem.getAdapter());
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.chkOk = (CheckBox) convertView.findViewById(R.id.chkOk);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Picasso
.with(context)
.load(newsItem.getImg())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(holder.thumbImage);
holder.txtBarang.setText(newsItem.getNamaProduk().toUpperCase());
holder.txtJumlah.setText(newsItem.getJumlah().toUpperCase());
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
holder.cmbSiap.setEnabled(newsItem.getcmbSiap());
holder.txtBox.setEnabled(newsItem.gettxtBox());
holder.cmbSiap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
jmlCmbSiap = parent.getItemAtPosition(position).toString();
newsItem.setJumlah(jmlCmbSiap);
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
System.out.println("JML : " + newsItem.getJumlah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.chkOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (newsItem.getchkOk() == false) {
newsItem.setcmbSiap(true);
newsItem.setchkOk(true);
newsItem.settxtBox(true);
holder.cmbSiap.setEnabled(true);
holder.chkOk.setChecked(true);
txtBox.setEnabled(true);
numberChecked = numberChecked + 1;
idChkOk.add(position);
System.out.println("Chk : " + idChkOk);
} else {
numberChecked = numberChecked - 1;
newsItem.setcmbSiap(false);
newsItem.setchkOk(false);
holder.cmbSiap.setEnabled(false);
holder.chkOk.setChecked(false);
if (numberChecked == 0) {
newsItem.settxtBox(false);
txtBox.setEnabled(false);
}
idChkOk.remove(position);
System.out.println("Chk : " + idChkOk);
}
}
});
cmdPak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.clear();
for (int i = 0; i < listData.size(); i++)
{
newsItem = listData.get(i);
a.add(newsItem.getJumlah().toString());
}
System.out.println("Pak : " + a);
}
});
return convertView;
}
class ViewHolder {
TextView txtBarang,txtJumlah,txtBox;
Spinner cmbSiap;
ImageView thumbImage;
CheckBox chkOk;
}
}
ListItem2.java
class ListItem2 {
private String shipment;
private String truck;
private String transporter;
private String tanggal;
private String order;
private String nilai;
private String alamat;
private String status;
private String jumlah;
private String namaProduk;
private String img;
private String sopir;
private String jumlahTerima;
private String alasan;
private String orderTemp;
private Boolean chkOk;
private Boolean cmbSiap;
private Boolean txtBox;
private ArrayAdapter<CharSequence> adapter;
private ArrayList<String> array = new ArrayList<String>();
public void setAdapter(Integer jml)
{
for (int i = 0; i<= jml; i++) {
array.add(String.valueOf(i));
}
adapter = new ArrayAdapter(DetailOrder.this,android.R.layout.simple_spinner_item,array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter()
{
return adapter;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getNilai() {
return nilai;
}
public void setNilai(String nilai) {
this.nilai = nilai;
}
public String getKodeProduk() {
return nilai;
}
public void setKodeProduk(String nilai) {
this.nilai = nilai;
}
public String getNamaProduk() {
return namaProduk;
}
public void setNamaProduk(String namaProduk) {
this.namaProduk = namaProduk;
}
public String getJumlah() {
return jumlah;
}
public void setJumlah(String jumlah) {
this.jumlah = jumlah;
}
public Boolean getchkOk() {
return chkOk;
}
public void setchkOk(Boolean chkOk) {
this.chkOk = chkOk;
}
public Boolean getcmbSiap() {
return cmbSiap;
}
public void setcmbSiap(Boolean cmbSiap) {
this.cmbSiap = cmbSiap;
}
public Boolean gettxtBox() {
return txtBox;
}
public void settxtBox(Boolean txtBox) {
this.txtBox = txtBox;
}
}
Could you lend me a hand ?
Update :
chkAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View views;
CheckBox chkOkx;
Spinner cmbSiap;
for (int i = 0; i < jArray; i++) {
final ListItem2 newsItem = listData.get(i);
views = listView.getChildAt(i);
if (views == null) {
return;
} else {
chkOkx = (CheckBox) views.findViewById(R.id.chkOk);
cmbSiap = (Spinner) views.findViewById(R.id.cmbSiap);
if (chkOkx.isChecked()) {
newsItem.setchkOk(true);
newsItem.setcmbSiap(true);
chkOkx.setChecked(newsItem.getchkOk());
cmbSiap.setEnabled(newsItem.getcmbSiap());
} else {
newsItem.setchkOk(false);
newsItem.setcmbSiap(false);
chkOkx.setChecked(newsItem.getchkOk());
cmbSiap.setEnabled(newsItem.getcmbSiap());
}
idChkOk.add(i);
}
}
if (chkAll.isChecked()) {
txtBox.setEnabled(true);
numberChecked = 0;
} else {
txtBox.setEnabled(false);
numberChecked = listviewChild;
}
listView.invalidateViews();
}
});
In ListView when you scroll, the views are destroyed and re-created. To overcome the issue you need to preserve both of the checkbox status and spinner item's value.
For the checkbox, save the checked status from setOnClickListener inside a boolean array,
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
The boolean array should like this,
private boolean[] checkBoxState;
Later on getView() apply the check/uncheck status of each checkbox items based on the array
holder.checkBox.setChecked(checkBoxState[position]);
Similarly to save the spinner data, create a Hashmap
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
and save the spinner data once it's selected from the setOnItemSelectedListener
myMap.put(position, pos);
Later restore the spinner selection position from the saved data,
if (myMap.containsKey(position)) {
viewHolder.spinner.setSelection(myMap.get(position));
}
Full code,
class CustomListView extends BaseAdapter {
private ArrayList<ListItem2> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListView adapter = this;
String jmlCmbSiap;
ArrayList<String> a = new ArrayList<>();
private boolean[] checkBoxState;
private Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public CustomListView(Context context, ArrayList<ListItem2> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
checkBoxState = new boolean[listData.size()];
this.context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_detail_order, null);
holder = new ViewHolder();
newsItem.setAdapter(Integer.parseInt(newsItem.getJumlah()));
holder.txtBarang = (TextView) convertView.findViewById(R.id.txtBarang);
holder.txtJumlah = (TextView) convertView.findViewById(R.id.txtJumlah);
holder.txtBox = (TextView) convertView.findViewById(R.id.txtBoxes);
holder.cmbSiap = (Spinner) convertView.findViewById(R.id.cmbSiap);
holder.cmbSiap.setAdapter(newsItem.getAdapter());
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.chkOk = (CheckBox) convertView.findViewById(R.id.chkOk);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setChecked(checkBoxState[position]);
if (checkBoxState[position])
{
holder.chkOk.setChecked(true);
newsItem.setcmbSiap(true);
newsItem.settxtBox(true);
holder.cmbSiap.setEnabled(true);
holder.cmbSiap.setClickable(true);
txtBox.setEnabled(true);
}
else
{
holder.chkOk.setChecked(false);
newsItem.setcmbSiap(false);
newsItem.settxtBox(false);
holder.cmbSiap.setEnabled(false);
holder.cmbSiap.setClickable(false);
txtBox.setEnabled(false);
}
Picasso
.with(context)
.load(newsItem.getImg())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(holder.thumbImage);
holder.txtBarang.setText(newsItem.getNamaProduk().toUpperCase());
holder.txtJumlah.setText(newsItem.getJumlah().toUpperCase());
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
holder.cmbSiap.setEnabled(newsItem.getcmbSiap());
holder.txtBox.setEnabled(newsItem.gettxtBox());
if (myMap.containsKey(position)) {
viewHolder.spinner.setSelection(myMap.get(position));
}
holder.cmbSiap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
jmlCmbSiap = parent.getItemAtPosition(position).toString();
newsItem.setJumlah(jmlCmbSiap);
myMap.put(position, pos);
System.out.println("JML : " + newsItem.getJumlah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.chkOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//is chkOk checked?
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
viewHolder.spinner.setEnabled(true);
viewHolder.spinner.setClickable(true);
} else {
checkBoxState[position] = false;
viewHolder.spinner.setEnabled(false);
viewHolder.spinner.setClickable(false);
}
}
});
cmdPak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.clear();
for (int i = 0; i < listData.size(); i++)
{
newsItem = listData.get(i);
a.add(newsItem.getJumlah().toString());
}
System.out.println("Pak : " + a);
}
});
return convertView;
}
class ViewHolder {
TextView txtBarang,txtJumlah,txtBox;
Spinner cmbSiap;
ImageView thumbImage;
CheckBox chkOk;
}
}
Update:
In order to make a select all/deselect all checkbox feature,
create a boolean flag at the top of adapter's class,
boolean isCheckAll = false;
then create a toggle method,
public void toggleCheckAll() {
isCheckAll = !isCheckAll;
for (int i = 0; i < listData.size(); i++) {
if (isCheckAll) {
checkBoxState[i] = true;
notifyDataSetInvalidated();
} else {
checkBoxState[i] = false;
notifyDataSetInvalidated();
}
}
}
Now call the method from your aactivity's check all button's click,
btnCheckAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.toggleCheckAll();
}
});
I have a RecyclerView with 5 items and drag & drop feature. I want to save items's positions into SharedPreferences in order to restore them when the App is launched. Currently I'm able to save their positions into SharedPreferences using Json but the App crashes when I restore positions. Any solution? Thanks.
public static AppCompatActivity mActivity;
public static SharedPreferences SP;
public static SharedPreferences.Editor mEditor;
public static RecyclerView mRecyclerView;
public static RecyclerViewDragDropManager mRecyclerViewDragDropManager;
public static List<Long> mSaveItemsOrder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = this;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mEditor = SP.edit();
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerViewDragDropManager = new RecyclerViewDragDropManager();
mRecyclerViewDragDropManager.setInitiateOnMove(false);
mRecyclerViewDragDropManager.setInitiateOnLongPress(true);
mRecyclerViewDragDropManager.setLongPressTimeout(300);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mRecyclerViewDragDropManager.createWrappedAdapter(new Adapter()));
mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView);
}
public static class Item {
public final long id;
public final String text;
public Item(long id, String text) {
this.id = id;
this.text = text;
}
}
public static class ViewHolder extends AbstractDraggableItemViewHolder {
Button mButton;
public ViewHolder(View itemView) {
super(itemView);
mButton = (Button) itemView.findViewById(R.id.button);
}
}
public static class Adapter extends RecyclerView.Adapter<ViewHolder> implements DraggableItemAdapter<ViewHolder> {
List<Item> mItems;
public Adapter() {
setHasStableIds(true);
mItems = new ArrayList<>();
if (SP.getString("items_order", null) == null) {
for (int mInt = 0; mInt < 5; mInt++) {
mItems.add(new Item(mInt, "Item " + mInt));
}
} else {
mItems = new Gson().fromJson(SP.getString("items_order", null), new TypeToken<Item>(){}.getType());
}
}
#Override
public long getItemId(int position) {
return mItems.get(position).id;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
return new ViewHolder(mView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Item mItem = mItems.get(position);
holder.mButton.setText(mItem.text);
}
#Override
public int getItemCount() {
return mItems.size();
}
#Override
public void onMoveItem(int fromPosition, int toPosition) {
Item mMovedItem = mItems.remove(fromPosition);
mItems.add(toPosition, mMovedItem);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public boolean onCheckCanStartDrag(ViewHolder holder, int position, int x, int y) {
return true;
}
#Override
public ItemDraggableRange onGetItemDraggableRange(ViewHolder holder, int position) {
return null;
}
#Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return true;
}
}
#Override
protected void onPause() {
super.onPause();
mSaveItemsOrder = new ArrayList<>();
for (int mInt = 0; mInt < mRecyclerView.getAdapter().getItemCount(); mInt++) {
mSaveItemsOrder.add(mRecyclerView.getAdapter().getItemId(mInt));
}
mEditor.putString("items_order", new Gson().toJson(mSaveItemsOrder)).commit();
}
This is the error:
https://www.dropbox.com/s/j2tf4n08depyynt/Error.txt?dl=0
The problem is with your JSON.
You the object you are serializing to JSON is mSaveItemsOrder which is an ArrayList. But on deserializing you give GSON the Class new TypeToken<Item>(){}.getType().
So you store an ArrayList in your JSON but trying to deserialzie a different Class, that won't work.
This should work:
mItems = new Gson().fromJson(SP.getString("items_order", null), new TypeToken<ArrayList>(){}.getType(););