When I first start up my app and the user clicks on an item in a recyclerview, everything initializes as expected.
When the user hits the back button to go back to the main item list page and then clicks on the same or another item, the page is not loaded the same.
My initial layout is the same as the second image without the location name and coordinates updated.
What frustrates me is the day names are initialized in the same exact method. I have debugged it in many ways and have found that the code must not be run - the code inside of it has NO affect on the outcome of the item's detail page when it is reloaded. This code only affects the actual layout the FIRST time it is run and has no affect any other time.
RecyclerView Adapter:
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<LocationContent.LocationItem> mValues;
public SimpleItemRecyclerViewAdapter(List<LocationContent.LocationItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public LocationContent.LocationItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
Code that is supposed to be run:
Log.i("LOAD DATA", "Called");
Log.e("SWITCH CASE (IDF)", AssetLoader.getMondayName(mItem.id));
// To layout below the textView to avoid crashes
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, R.id.textView);
switch(AssetLoader.getLastItemDayName(mItem.id)) {
case "Sun":
sunday.setLayoutParams(p);
break;
case "Mon":
monday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Tues":
tuesday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Wed":
wednesday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Thurs":
thursday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Fri":
friday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Sat":
saturday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "":
sunday.setLayoutParams(p);
break;
}
Log.e("MONDAY NAME EDIT()", AssetLoader.getMondayName(mItem.id));
if (!AssetLoader.dataInMonday(mItem.id)/*AssetLoader.getMondayName(mItem.id).equals("") || AssetLoader.getMondayName(mItem.id).equals("Monday:")*/) {
monday.setVisibility(View.GONE);
monday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsMonday(mItem.id, "");
} else {
monday.setVisibility(View.VISIBLE);
monday_detail.setVisibility(View.VISIBLE);
monday.setText(AssetLoader.getMondayName(mItem.id));
if(AssetLoader.getItemDetailsMonday(mItem.id).equals("")) {
monday_detail.setText(R.string.no_data);
} else {
monday_detail.setText(AssetLoader.getItemDetailsMonday(mItem.id));
}
}
if (!AssetLoader.dataInTuesday(mItem.id)/*AssetLoader.getTuesdayName(mItem.id).equals("") || AssetLoader.getTuesdayName(mItem.id).equals("Tuesday:")*/) {
tuesday.setVisibility(View.GONE);
tuesday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsTuesday(mItem.id, "");
} else {
tuesday.setVisibility(View.VISIBLE);
tuesday_detail.setVisibility(View.VISIBLE);
tuesday.setText(AssetLoader.getTuesdayName(mItem.id));
if(AssetLoader.getItemDetailsMonday(mItem.id).equals("")) {
tuesday_detail.setText(R.string.no_data);
} else {
tuesday_detail.setText(AssetLoader.getItemDetailsTuesday(mItem.id));
}
}
if (!AssetLoader.dataInWednesday(mItem.id)/*AssetLoader.getWednesdayName(mItem.id).equals("") || AssetLoader.getWednesdayName(mItem.id).equals("Wednesday:")*/) {
wednesday.setVisibility(View.GONE);
wednesday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsWednesday(mItem.id, "");
} else {
wednesday.setVisibility(View.VISIBLE);
wednesday_detail.setVisibility(View.VISIBLE);
wednesday.setText(AssetLoader.getWednesdayName(mItem.id));
if(AssetLoader.getItemDetailsWednesday(mItem.id).equals("")) {
wednesday_detail.setText(R.string.no_data);
} else {
wednesday_detail.setText(AssetLoader.getItemDetailsWednesday(mItem.id));
}
}
if (!AssetLoader.dataInThursday(mItem.id)/*AssetLoader.getThursdayName(mItem.id).equals("") || AssetLoader.getThursdayName(mItem.id).equals("Thursday:")*/) {
thursday.setVisibility(View.GONE);
thursday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsThursday(mItem.id, "");
} else {
thursday.setVisibility(View.VISIBLE);
thursday_detail.setVisibility(View.VISIBLE);
thursday.setText(AssetLoader.getThursdayName(mItem.id));
if(AssetLoader.getItemDetailsThursday(mItem.id).equals("")) {
thursday_detail.setText(R.string.no_data);
} else {
thursday_detail.setText(AssetLoader.getItemDetailsThursday(mItem.id));
}
}
if (!AssetLoader.dataInFriday(mItem.id)/*AssetLoader.getFridayName(mItem.id).equals("") || AssetLoader.getFridayName(mItem.id).equals("Friday:")*/) {
friday.setVisibility(View.GONE);
friday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsFriday(mItem.id, "");
} else {
friday.setVisibility(View.VISIBLE);
friday_detail.setVisibility(View.VISIBLE);
friday.setText(AssetLoader.getFridayName(mItem.id));
if(AssetLoader.getItemDetailsFriday(mItem.id).equals("")) {
friday_detail.setText(R.string.no_data);
} else {
friday_detail.setText(AssetLoader.getItemDetailsFriday(mItem.id));
}
}
if (!AssetLoader.dataInSaturday(mItem.id)/*AssetLoader.getSaturdayName(mItem.id).equals("") || AssetLoader.getSaturdayName(mItem.id).equals("Saturday:")*/) {
saturday.setVisibility(View.GONE);
saturday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsSaturday(mItem.id, "");
} else {
saturday.setVisibility(View.VISIBLE);
saturday_detail.setVisibility(View.VISIBLE);
saturday.setText(AssetLoader.getSaturdayName(mItem.id));
if(AssetLoader.getItemDetailsSaturday(mItem.id).equals("")) {
saturday_detail.setText(R.string.no_data);
} else {
saturday_detail.setText(AssetLoader.getItemDetailsSaturday(mItem.id));
}
}
if (!AssetLoader.dataInSunday(mItem.id)/*AssetLoader.getSundayName(mItem.id).equals("") || AssetLoader.getSundayName(mItem.id).equals("Sunday:")*/) {
sunday.setVisibility(View.GONE);
sunday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsSunday(mItem.id, "");
} else {
sunday.setVisibility(View.VISIBLE);
sunday_detail.setVisibility(View.VISIBLE);
sunday.setText(AssetLoader.getSundayName(mItem.id));
if(AssetLoader.getItemDetailsSunday(mItem.id).equals("")) {
sunday_detail.setText(R.string.no_data);
} else {
sunday_detail.setText(AssetLoader.getItemDetailsSunday(mItem.id));
}
}
Please note that the Log.e and Log.i calls are not even being displayed in logcat/Android Monitor when the app is run. THE CODE IS BEING CALLED WHEN THE REST OF THE USER INTERFACE IS BEING CALLED! Thanks for any information you may have!
Set your adapter for RecyclerView inside onResume method.
Well I found the problem. When the DetailView for my Item was loading the first time, my variables for monday, tuesday, etc were null so they were set to the TextViews on the current layout. When the back button was pressed, these variables were no longer null but still pointed to the previous layout's variables.
Incorrect Code:
if(monday == null) {
monday = (TextView) rootView.findViewById(R.id.monday);
tuesday = (TextView) rootView.findViewById(R.id.tuesday);
wednesday = (TextView) rootView.findViewById(R.id.wednesday);
thursday = (TextView) rootView.findViewById(R.id.thursday);
friday = (TextView) rootView.findViewById(R.id.friday);
saturday = (TextView) rootView.findViewById(R.id.saturday);
sunday = (TextView) rootView.findViewById(R.id.sunday);
}
if(monday_detail == null) {
monday_detail = (TextView) rootView.findViewById(R.id.monday_detail);
tuesday_detail = (TextView) rootView.findViewById(R.id.tuesday_detail);
wednesday_detail = (TextView) rootView.findViewById(R.id.wednesday_detail);
thursday_detail = (TextView) rootView.findViewById(R.id.thursday_detail);
friday_detail = (TextView) rootView.findViewById(R.id.friday_detail);
saturday_detail = (TextView) rootView.findViewById(R.id.saturday_detail);
sunday_detail = (TextView) rootView.findViewById(R.id.sunday_detail);
}
Correct Code (Without null checks):
monday = (TextView) rootView.findViewById(R.id.monday);
tuesday = (TextView) rootView.findViewById(R.id.tuesday);
wednesday = (TextView) rootView.findViewById(R.id.wednesday);
thursday = (TextView) rootView.findViewById(R.id.thursday);
friday = (TextView) rootView.findViewById(R.id.friday);
saturday = (TextView) rootView.findViewById(R.id.saturday);
sunday = (TextView) rootView.findViewById(R.id.sunday);
monday_detail = (TextView) rootView.findViewById(R.id.monday_detail);
tuesday_detail = (TextView) rootView.findViewById(R.id.tuesday_detail);
wednesday_detail = (TextView) rootView.findViewById(R.id.wednesday_detail);
thursday_detail = (TextView) rootView.findViewById(R.id.thursday_detail);
friday_detail = (TextView) rootView.findViewById(R.id.friday_detail);
saturday_detail = (TextView) rootView.findViewById(R.id.saturday_detail);
sunday_detail = (TextView) rootView.findViewById(R.id.sunday_detail);
So by removing the null checks, my code is all initialized correctly every time and has no errors.
Related
I am currently working on tab layout. Almost i have done it.
My scenario is at my 0 position i have used custom view which includes imageview and textview.
My first tab at 0 position have some conditions. Which they are
1) At 0 index fragment i am calling API. so if there is no data then display no data available and tab layout simply shows a icon.
2) After if user wants to add data from button click then from new acttiviy he can fill the data and icon at 0 position of tablayout should be changed and textview will be displayed with selected date.
Problem :
If i call setUpTabIcons() method in onResume() method then imageview icons are repeated.
Here is screenshot.
Here is my code.
private void setupTabIcons() {
if (mediaPrefs.getString(Constant.SharedPreferences_wedding_id, "").length() > 0) {
List<EventData> eventData = appDatabase.eventListDao().getSelectedWeddingEvents(Integer.parseInt(mediaPrefs.getString(Constant.SharedPreferences_wedding_id, "0")));
View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab_event_date_view, null);
TextView txt_day = (TextView) view.findViewById(R.id.txt_day);
TextView txt_month = (TextView) view.findViewById(R.id.txt_month);
ImageView img_event = (ImageView)view.findViewById(R.id.img_icon_events);
if (eventData != null && eventData.size() > 0) {
if (eventData.get(0).getEventdate().length() > 0) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat day_format = new SimpleDateFormat("dd");
DateFormat month_format = new SimpleDateFormat("MMM");
Date date_day = null, date_month = null;
try {
date_day = simpleDateFormat.parse(eventData.get(0).getEventdate());
date_month = simpleDateFormat.parse(eventData.get(0).getEventdate());
String day = day_format.format(date_day);
String month = month_format.format(date_month);
txt_day.setText(day);
txt_month.setText(month);
img_event.setVisibility(View.GONE);
txt_day.setVisibility(View.VISIBLE);
txt_month.setVisibility(View.VISIBLE);
Log.v("asfasf","heree2");
tabs.getTabAt(0).setCustomView(view);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
Log.v("asfasf","heree1");
img_event.setVisibility(View.VISIBLE);
txt_day.setVisibility(View.GONE);
txt_month.setVisibility(View.GONE);
img_event.setImageResource(R.mipmap.host_add_event_small);
tabs.getTabAt(0).setCustomView(view);
}
} else {
Log.v("asfasf","heree");
img_event.setVisibility(View.VISIBLE);
txt_day.setVisibility(View.GONE);
txt_month.setVisibility(View.GONE);
img_event.setImageResource(R.mipmap.host_add_event_small);
tabs.getTabAt(0).setCustomView(view);
}
}
tabs.getTabAt(1).setIcon(R.mipmap.camera_icon);
tabs.getTabAt(2).setIcon(R.mipmap.chat_icon);
tabs.getTabAt(3).setIcon(R.mipmap.notification_icon);
tabs.getTabAt(4).setIcon(R.mipmap.chat_userprofile_light);
tabs.setRotationX(180);
LinearLayout tabListed = ((LinearLayout) tabs.getChildAt(0));
for (int position = 0; position < tabListed.getChildCount(); position++) {
LinearLayout item = ((LinearLayout) tabListed.getChildAt(position));
item.setRotationX(180);
}
tabs.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(view_pager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
if (tab.getPosition() == 0) {
View tabView = tab.getCustomView();
TextView txt_day = (TextView) tabView.findViewById(R.id.txt_day);
TextView txt_month = (TextView) tabView.findViewById(R.id.txt_month);
if(txt_day.getText().toString().trim().length()>0 && txt_month.getText().toString().trim().length()>0){
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.dark_gray_wedding);
txt_day.setTextColor(tabIconColor);
txt_month.setTextColor(tabIconColor);
}else{
ImageView img_event = (ImageView)tabView.findViewById(R.id.img_icon_events);
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.dark_gray_wedding);
if(img_event!=null){
img_event.setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
} else {
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.dark_gray_wedding);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
if (tab.getPosition() == 0) {
TextView txt_day = (TextView) tab.getCustomView().findViewById(R.id.txt_day);
TextView txt_month = (TextView) tab.getCustomView().findViewById(R.id.txt_month);
if(txt_day.getText().toString().trim().length()>0 && txt_month.getText().toString().trim().length()>0){
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.light_gray_wedding);
txt_day.setTextColor(tabIconColor);
txt_month.setTextColor(tabIconColor);
}else{
ImageView img_event = (ImageView)tab.getCustomView().findViewById(R.id.img_icon_events);
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.light_gray_wedding);
if(img_event!=null){
img_event.setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
} else {
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.light_gray_wedding);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
super.onTabReselected(tab);
}
});
}
In order to remove a custom view from a tab layout you just need to set the custom view for that tab to null. Here's an example in Java:
tabs.getTabAt(0).setCustomView(null);
and Kotlin:
tabs.getTabAt(0)?.customView = null
TextView txt_day =(TextView)tabs.getTabAt(0).getCustomView().findViewById(R.id.txt_day);
TextView txt_month =(TextView)tabs.getTabAt(0).getCustomView().findViewById(R.id.txt_month);
txt_day.setText("");
txt_month.setText("");
#Piyush You can find the textview of the custom tab then set textview blank
As you can see looking at some parts of my code I'm very new to Android and Java, but as bad as the code looks to the pro guys, it’s doing what I want it to do so far (I’m sure I’ll get there…lol). I have a custom adapter with a recycler view. There are some text views. I also have a bottom menu with an email button and I would like to use 2 of the views (R.id.brand_name & R.id.cases_text_view) and sent them as text in an email intent. The bottom menu and the email intent is working where it is, but I don’t how to call the two text views into the EXTRA_TEXT. Please help me out.
Just one more thing: thank you to all you guys, I wouldn't have been so far with this app if it weren't for this website and all your help. I really appreciate it.
Here is the class with the bottom menu and email intent:
public class BlackLabel extends brands {
private RecyclerView recyclerView;
//private String modelArrayList;
//private Context ctx;
public static ArrayList<Model> modelArrayList;
private CustomAdapter customAdapter;
//private Button btnnext;
// supossing to have an image called ic_play inside my drawables.
public String[] brandlist = new String[]{
"Black Label 340ml NRB (85023)",
"Black Label 330ml Cans (85736)",
"Black label 500ml Cans (85023)",
"Black Label 440ml NRB (86798)",
"Black Label 330ml RB (85556)",
"Black Label 750ml RB (85021)",
"Black Label 340ml NRB 12 Pack (87009)",
"Black Label 500ml Cans 12 Pack (85022)"};
public int[] pallet_size = {
84,
127,
81,
80,
120,
70,
132,
90};
public int[] myimage = {
R.drawable.black_label,
R.drawable.brutal_fruit,
R.drawable.castle_lager,
R.drawable.flying_fish,
R.drawable.castle_lite,
R.drawable.hansa,
R.drawable.lion_lager,
R.drawable.milk_stout};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order_by_brand);
setTitle("Black Label");
recyclerView = (RecyclerView) findViewById(R.id.recycler);
modelArrayList = getModel();
customAdapter = new CustomAdapter(this);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}
private ArrayList<Model> getModel() {
final ArrayList<Model> list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
final Model model = new Model();
model.setNumber(0);
model.setNumber2(0);
model.setImage(myimage[i]);
model.setBrand(brandlist[i]);
model.setPallet_size(pallet_size[i]);
list.add(model);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavView_Bar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(0);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
Intent intent1 = new Intent(BlackLabel.this, MainActivity.class);
startActivity(intent1);
break;
case R.id.ic_clear:
Intent intent2 = new Intent(BlackLabel.this, BlackLabel.class);
startActivity(intent2);
break;
case R.id.ic_email:
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:who#where.co.za"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Please place order for....");
intent.putExtra(Intent.EXTRA_TEXT, "Here I want some text from the adapter.");
startActivity(intent);
}
return false;
}
});
}
return list;
}}
And here is my Custom Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private LayoutInflater inflater;
private Context ctx;
public CustomAdapter(Context ctx) {
inflater = LayoutInflater.from(ctx);
this.ctx = ctx;
}
#Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, int position) {
holder.tvBrand.setText((CharSequence) modelArrayList.get(position).getBrand());
holder.tvImage.setImageResource(Integer.parseInt(String.valueOf(modelArrayList.get(position).getImage())));
holder.tvCases.setText(String.valueOf(modelArrayList.get(position).getNumber()));
holder.tvPallet_size.setText(String.valueOf(modelArrayList.get(position).getPallet_size()));
holder.tvCases.setText(String.valueOf(modelArrayList.get(position).getNumber2()));
holder.tvPallets.setText(String.valueOf(modelArrayList.get(position).getNumber()));
holder.tvCases.setText(String.valueOf(modelArrayList.get(position).getNumber2()));
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected Button btn_cases_plus, btn_cases_minus, btn_pallets_plus, btn_pallets_minus;
protected ImageView tvImage;
private TextView tvBrand, tvCases,tvPallets, tvPallet_size;
public MyViewHolder(View itemView) {
super(itemView);
tvBrand = (TextView) itemView.findViewById(R.id.brand_name);
tvImage = (ImageView) itemView.findViewById(R.id.beer_logo);
tvCases = (TextView) itemView.findViewById(R.id.cases_text_view);
tvPallet_size = (TextView) itemView.findViewById(R.id.pallets_size);
tvPallets = (TextView) itemView.findViewById(R.id.pallets_text_view);
btn_cases_plus = (Button) itemView.findViewById(R.id.casePlus1);
btn_cases_minus = (Button) itemView.findViewById(R.id.caseMinus1);
btn_pallets_plus = (Button) itemView.findViewById(R.id.palletsPlus1);
btn_pallets_minus = (Button) itemView.findViewById(R.id.palletsMinus1);
btn_cases_plus.setTag(R.integer.btn_cases_plus_view, itemView);
btn_cases_minus.setTag(R.integer.btn_cases_minus_view, itemView);
btn_cases_plus.setOnClickListener(this);
btn_cases_minus.setOnClickListener(this);
btn_pallets_plus.setTag(R.integer.btn_pallets_plus_view, itemView);
btn_pallets_minus.setTag(R.integer.btn_pallets_minus_view, itemView);
btn_pallets_plus.setOnClickListener(this);
btn_pallets_minus.setOnClickListener(this);
}
// onClick Listener for view
#Override
public void onClick(View v) {
if (v.getId() == btn_cases_plus.getId()){
View tempview = (View) btn_cases_plus.getTag(R.integer.btn_cases_plus_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
int number = Integer.parseInt(tvCases.getText().toString()) + 1;
tvCases.setText(String.valueOf(number));
modelArrayList.get(getAdapterPosition()).setNumber(number);
} else if(v.getId() == btn_cases_minus.getId()) {
View tempview = (View) btn_cases_minus.getTag(R.integer.btn_cases_minus_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
int number = Integer.parseInt(tvCases.getText().toString()) - 1;
if (number == 0 || number <0) {
Toast.makeText(ctx,"You cannot order less than one case", Toast.LENGTH_SHORT).show();
tvCases.setText(String.valueOf(0));
return;
}
tvCases.setText(String.valueOf(number));
modelArrayList.get(getAdapterPosition()).setNumber(number);
} else if(v.getId() == btn_pallets_plus.getId()) {
View tempview = (View) btn_pallets_plus.getTag(R.integer.btn_pallets_plus_view);
TextView tvPallets = (TextView) tempview.findViewById(R.id.pallets_text_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
TextView tvPallet_size = (TextView) tempview.findViewById(R.id.pallets_size);
int number = Integer.parseInt(tvPallets.getText().toString()) + 1;
tvPallets.setText(String.valueOf(number));
int number2 = Integer.parseInt(tvPallets.getText().toString()) * Integer.parseInt(tvPallet_size.getText().toString());
tvCases.setText(String.valueOf(number2));
modelArrayList.get(getAdapterPosition()).setNumber(number);
modelArrayList.get(getAdapterPosition()).setNumber2(number2);
} else if(v.getId() == btn_pallets_minus.getId()) {
View tempview = (View) btn_pallets_minus.getTag(R.integer.btn_pallets_minus_view);
TextView tvPallets = (TextView) tempview.findViewById(R.id.pallets_text_view);
TextView tvCases = (TextView) tempview.findViewById(R.id.cases_text_view);
TextView tvPallet_size = (TextView) tempview.findViewById(R.id.pallets_size);
int number = Integer.parseInt(tvPallets.getText().toString()) - 1;
tvPallets.setText(String.valueOf(number));
int number2 = Integer.parseInt(tvPallets.getText().toString()) * Integer.parseInt(tvPallet_size.getText().toString());
tvCases.setText(String.valueOf(number2));
if (number == 0 || number <0) {
Toast.makeText(ctx,"You cannot order less than one pallet", Toast.LENGTH_SHORT).show();
tvCases.setText(String.valueOf(0));
tvPallets.setText(String.valueOf(0));
}
modelArrayList.get(getAdapterPosition()).setNumber(number);
modelArrayList.get(getAdapterPosition()).setNumber2(number2);
}
}
}
}
Here is your code
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:who#where.co.za"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Please place order for....");
intent.putExtra(Intent.EXTRA_TEXT, "Here I want some text from the adapter.");
startActivity(intent);
Try to make next thing. Firstly, I don't really know why you didn't finish loop after this part of code but ok let's work with it.
private ArrayList<Model> getModel() {
final ArrayList<Model> list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
final Model model = new Model();
model.setNumber(0);
model.setNumber2(0);
model.setImage(myimage[i]);
model.setBrand(brandlist[i]);
model.setPallet_size(pallet_size[i]);
list.add(model);
So here in every iteration of loop you got model object which you setting properties. So you could get data just from the model like model.getBrand(). I don't know what is "cases"(R.id.cases_text_view) in you app but i think it's set here
model.setNumber(0);
model.setNumber2(0);
So just get this number like
model.getNumber(); model.getNumber2(0);
So what is in the end:
You should make 3 "get" methods for your model class returning "String" type
getBrand()
getNumber()
getNumber2()
Then just add next code:
Intent intent = new Intent(Intent.ACTION_SENDTO);
String extraData = model.getBrand() + getNumber() getNumber2();
intent.setData(Uri.parse("mailto:who#where.co.za"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Please place order for....");
intent.putExtra(Intent.EXTRA_TEXT, extraData);
startActivity(intent);
Hope it would help you! ask if anything.
If you want to pass those two values of views to the main activity
1. Create a method with 2 parameters in your activity
2. Set click listener on your list and onClick just call that method of your recycle view with view parameters.Inside your onClick method write
((your_activity_name)context).methodName(parameters here);
Hope this will help you
Thanks!!!
I have an ArrayAdapter which shows some posts using a fragment. In this fragment I have some buttons. So all of the posts shown have these buttons.
The problem is, when I click a button of a post to setText to a field of this post; instead of changing text of post that I clicked, it changes text of newly scrolled item.
For example if I scroll down the ListView a new item comes. Then regardless of which post I clicked it changes text of this new post.
How can I prevent this to happen? I take current post using
getItem(position)
By scroolling I mean new element of the list are loaded and shown.
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.comment_small,parent,false);
TextView tvOwner = (TextView) v.findViewById(R.id.tvCommentSmallOwner);
TextView tvCreationDate = (TextView) v.findViewById(R.id.tvCommentSmallCreationDate);
TextView tvCreationDateValue = (TextView) v.findViewById(R.id.tvCommentSmallCreationDate);
TextView tvContent = (TextView) v.findViewById(R.id.tvCommentSmallContent);
tvVoteCount = (TextView) v.findViewById(R.id.tvCommentVoteCount);
c = getItem(position);
tvOwner.setText(context.getResources().getString(R.string.generic_by) + " " + c.getOwnerId());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String s =c.getPostDate();
System.out.println(s);
tvCreationDateValue.setText(s);
tvContent.setText(c.getContent());
btnDownVote = (ImageButton) v.findViewById(R.id.btnCommentDownVote);
btnUpVote = (ImageButton) v.findViewById(R.id.btnCommentUpVote);
tvVoteCount.setText("" + c.getNetCount());
btnUpVote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c=getItem(position);
ServerRequests sr = new ServerRequests(getContext());
MemberLocalStore memberLocalStore = new MemberLocalStore(getContext());
Member m = memberLocalStore.getLoggedInMember();
sr.voteComment(c, true, m.getId(), new Consumer<String>() {
#Override
public void accept(String vote) {
tvVoteCount.setText("" + vote);
}
});
}
});
btnDownVote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c=getItem(position);
ServerRequests sr = new ServerRequests(getContext());
MemberLocalStore memberLocalStore = new MemberLocalStore(getContext());
Member m = memberLocalStore.getLoggedInMember();
sr.voteComment(c, false, m.getId(), new Consumer<String>() {
#Override
public void accept(String vote) {
tvVoteCount.setText("" + vote);
}
});
}
});
return v;
}
I want to vote (like,dislike) some posts but when I click upvote button that marked as 1, overall vote of the post that marked as 2 changes.
First time here and pretty new to Android. I have an issue with my background color in my "events page".
The background of the time is supposed to alternate between dark brown and lighter brown when a new time is displayed, but for some reason, it works sometimes and doesn't work other times.
When the app displays it incorrectly, it either will stay on the same shade of brown when the time changes or it will change the shade of brown when it should stay the same. I am not sure what is causing it.
The data comes from a json file hosted on a server. The data is loaded in an AsyncTask class and the app will wait for the data to be downloaded before the user reaches the events page. A message will display saying "Please wait for the data to be downloaded" if the user clicks events.
Here is an example of what one of the entries looks like:
{
"title": "Some_Title",
"description": "Some_Description\n",
"times": [
{
"startTime": "2014-09-20 09:30:00",
"endTime": "2014-09-20 10:30:00"
},
{
"startTime": "2014-09-20 11:00:00",
"endTime": "2014-09-20 12:00:00"
},
{
"startTime": "2014-09-20 13:00:00",
"endTime": "2014-09-20 14:00:00"
}
],
"locationTitle": "Some_Location",
"locationLat": ##.######,
"locationLng": -###.######,
"typeX": 0,
"typeY": true,
"typeZ": false,
"typeA": false,
"typeB": false,
"typeC": false,
"SpreadsheetName": "Some_Name\n(A_Location)"
},
The colors are handled in an Adapter class. Here is the code that handles the background color and a screenshot of the events page working as well as the Log:
public class EventScheduleAdapter extends BaseAdapter {
private final ArrayList<Event> events;
private final Context context;
private final ArrayList<Integer> holders;
public EventScheduleAdapter(Context context, boolean[] types, Calendar day) {
this.context = context;
this.events = EventList.getInstance().getFilteredEvents(day, types);
holders = new ArrayList<Integer>();
}
#Override
public int getCount() {
return events.size();
}
#Override
public Object getItem(int i) {
return events.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
Event event = events.get(position);
View vi = convertView;
ViewHolder holder;
//ImageView image = new ImageView(this.context);
//FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
//params.setMargins(20, 20, 20, 20);
if (convertView == null) {
vi = View.inflate(context, R.layout.event_list_item, null);
holder = new ViewHolder();
holder.time = (TextView) vi.findViewById(R.id.timeNumber);
holder.am = (TextView) vi.findViewById(R.id.timeAM);
holder.title = (TextView) vi.findViewById(R.id.title);
holder.location = (TextView) vi.findViewById(R.id.location);
//holder.description = (TextView) vi.findViewById(R.id.description);
holder.color = (LinearLayout) vi.findViewById(R.id.color);
holder.timeBackground = (RelativeLayout) vi.findViewById(R.id.time);
//holder.image = (ImageView) vi.findViewById(R.id.tag_A);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if(event.getStartTime() != null && (position == 0 || !EventList.isSameTime(event.getStartTime(), events.get(position - 1).getStartTime()))) {
holder.time.setText(String.format("%tl:%tM", event.getStartTime(), event.getStartTime()));
holder.am.setText(String.format("%Tp", event.getStartTime()));
} else {
holder.time.setText("");
holder.am.setText("");
}
Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/main.ttf");
holder.title.setText(event.getTitle());
holder.title.setTypeface(font);
holder.location.setText(event.getLocationTitle());
holder.location.setTypeface(font);
//holder.description.setText(event.getDescription());
//holder.description.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/description.ttf"));
holder.color.removeAllViews();
if(event.isTypeA()) {
holder.color.addView(newColorView(R.drawable.tag_A));
} if(event.isTypeB()) {
holder.color.addView(newColorView(R.drawable.tag_B));
} if(event.isTypeC()) {
holder.color.addView(newColorView(R.drawable.tag_C));
} if(event.isTypeD()) {
holder.color.addView(newColorView(R.drawable.tag_D));
} if(event.isTypeE()) {
holder.color.addView(newColorView(R.drawable.tag_E));
}
if (position != 0) {
Log.i("EventScheduleAdapter", "position " + position + "event # position: " + event.getTitle());
if (!EventList.isSameTime(event.getStartTime(), events.get(position - 1).getStartTime())) {
Log.i("EventScheduleAdapter", "Same time is FALSE");
if(holders.get(position - 1) == R.color.background_event_dark) {
Log.i("EventScheduleAdapter", "Different Color LIGHT");
holder.timeColor = R.color.background_event_light;
holders.add(holder.timeColor);
Log.i("EventScheduleAdapter", "position Color" + holders.get(position));
} else {
Log.i("EventScheduleAdapter", "Different Color DARK");
holder.timeColor = R.color.background_event_dark;
holders.add(holder.timeColor);
Log.i("EventScheduleAdapter", "position Color" + holders.get(position));
}
} else {
Log.i("EventScheduleAdapter", "Same time is TRUE");
holder.timeColor = holders.get(position - 1);
// holder.
//holder.timeColor = holder.get(position-1)
if (holder.timeColor == R.color.background_event_dark)
Log.i("EventScheduleAdapter", "SAME COLOR IS DARK");
if (holder.timeColor == R.color.background_event_light)
Log.i("EventScheduleAdapter", "SAME COLOR IS LIGHT");
holders.add(holder.timeColor);
Log.i("EventScheduleAdapter", "position Color" + holders.get(position));
}
} else {
Log.i("EventScheduleAdapter", "Position is 0");
holder.timeColor = R.color.background_event_dark;
holders.add(holder.timeColor);
}
holder.timeBackground.setBackgroundColor(context.getResources().getColor(holder.timeColor));
return vi;
}
/* Circle newColorView(int color) {
Circle layout = new Circle(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 50);
params.setMargins(5, 5, 5, 5);
layout.setLayoutParams(params);
layout.setColor(color);
return layout;
} */
ImageView newColorView(int drawable) {
ImageView layout = new ImageView(context); // put drawable in here
LinearLayout.LayoutParams params;
if (drawable == R.drawable.tag_cp) {
params = new LinearLayout.LayoutParams(78, 50);
}
else if (drawable == R.drawable.tag_slo) {
params = new LinearLayout.LayoutParams(100, 50);
}
else {
params = new LinearLayout.LayoutParams(50, 50);
}
params.setMargins(5, 5, 5, 5);
layout.setLayoutParams(params);
layout.setImageResource(drawable);
return layout;
}
class ViewHolder {
int timeColor;
RelativeLayout timeBackground;
TextView time;
TextView am;
TextView title;
TextView location;
//TextView description;
LinearLayout color;
}
}
I can't post images since I am a new member :( But I will as soon as I can
You keep adding to your holders arrays with each item you create. So if you are asked to draw item0 3 times and item1 3 times, you end up having 6 entries in the array. Consider using a sparse array or a int[].
And for example when you are asked to create the view for position X, you do:
holders[X] = myColorId;
I have a listview which inflates a layout with views in that layout. My Adapter successfully adds each item to its appropriate position when first created. However when the listview is scrolled, the items in the listview behaves oddly by sometimes losing its postion in the listview and sometimes not, I am unsure as what causes the behavior exactly. I did notice that whenever I overscroll the listview, the behavior happens again. To better explain the behavior, once the listview is scrolled or overscrolled, or even scrolled at a very "fast" rate, the listview scrolls past the last item as if another item was below it. Once I try to scroll back to the last item, the listview allows me to scroll only to the last item in the listview (as if the last item is the only item in the listview) then it does not allow me to scroll at all. Here is my adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder = new ViewHolder();
positionHolder = position;
Log.i("Position", "" + position);
if(convertView == null) {
try {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.post_layout, parent, false);
postLayout = convertView;
viewHolder.addToCalVF = (ViewFlipper)postLayout.findViewById(R.id.addToCalendarVF);
viewHolder.addToCalVF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((ViewFlipper)view).showNext();
Log.i("VIEWFLIPPERVF", viewHolder.addToCalVF.toString());
}
});
viewHolder.unameTV = (TextView) postLayout.findViewById(R.id.postUnameTv);
viewHolder.unameTV.setText(viewContent.get(index));
viewHolder.unameTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Starting new intent
Intent in = new Intent(getActivity(),
Profile.class);
// sending pid to next activity
String username =((TextView)view).getText().toString();
in.putExtra("username", username);
Log.i("Username", "" + username);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
viewHolder.fillSpace = (TextView)postLayout.findViewById(R.id.posthelpSpace);
viewHolder.fillSpace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View relayout = lv.getChildAt(position);
viewHolder.unameTV = (TextView) relayout.findViewById(R.id.postUnameTv);
String username = viewHolder.unameTV.getText().toString();
Intent in = new Intent(getActivity(),
Profile.class);
// sending pid to next activity
in.putExtra("username", username);
Log.i("Username", "" + username);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
viewHolder.image = (ImageView) postLayout.findViewById(R.id.postProfPic);
DisplayImageOptions options = initiateDisplayImageOptions();
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View relayout = lv.getChildAt(position);
viewHolder.unameTV = (TextView) relayout.findViewById(R.id.postUnameTv);
String username = viewHolder.unameTV.getText().toString();
Intent in = new Intent(getActivity(),
Profile.class);
// sending pid to next activity
in.putExtra("username", username);
Log.i("Username", "" + username);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
ImageLoader imageloader = ImageLoader.getInstance();
initImageLoader(getActivity());
imageloader.displayImage(viewContent.get(index + 1), viewHolder.image, options);
viewHolder.eventTitle = (TextView) postLayout.findViewById(R.id.postTitleTV);
viewHolder.eventTitle.setText(viewContent.get(index + 3));
testText = viewHolder.eventTitle;
viewHolder.eventImage = (ImageView) postLayout.findViewById(R.id.eventImage);
imageloader.displayImage(viewContent.get(index + 4), viewHolder.eventImage, options);
viewHolder.likesTV = (TextView) postLayout.findViewById(R.id.likesTV);
viewHolder.likesTV.setText("" + viewContent.get(index + 5));
viewHolder.planToAttendTV = (TextView) postLayout.findViewById(R.id.planToAttendTV);
viewHolder.planToAttendTV.setText(viewContent.get(index + 6));
viewHolder.addressTV = (TextView) postLayout.findViewById(R.id.postLocationTV);
viewHolder.addressTV.setText("" + viewContent.get(index + 7));
viewHolder.addressTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
viewHolder.addToCalendarButton = (TextView) postLayout.findViewById(R.id.addToCalendarButton);
viewHolder.addToCalendarButton.setText(viewContent.get(index + 2));
viewHolder.addToCalendarButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar startCal = new GregorianCalendar();
startCal.setTime(new Date());
startCal.set(STARTYEARS.get(position), STARTMONTHS.get(position), STARTDAYS.get(position), STARTHOURS.get(position), STARTMINS.get(position));
Calendar endCal = new GregorianCalendar();
endCal.setTime(new Date());
endCal.set(ENDYEARS.get(position), ENDMONTHS.get(position), ENDDAYS.get(position), ENDHOURS.get(position), ENDMINS.get(position));
String id = Double.toString(EventUtils.assignName());
View relayout = lv.getChildAt(position);
viewHolder.eventTitle = (TextView) relayout.findViewById(R.id.postTitleTV);
title = viewHolder.eventTitle.getText().toString();
addEvent(id, title, startCal.getTimeInMillis(), endCal.getTimeInMillis(), position);
viewHolder.addToCalVF = (ViewFlipper) relayout.findViewById(R.id.addToCalendarVF);
viewHolder.addToCalVF.showNext();
Log.i("VIEWFLIPPER", viewHolder.addToCalVF.toString());
}
});
viewHolder.addToCalConfirm = (TextView) postLayout.findViewById(R.id.addToCalendarConfirmedButton);
viewHolder.addToCalConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View relayout = lv.getChildAt(position);
viewHolder.addToCalVF = (ViewFlipper) relayout.findViewById(R.id.addToCalendarVF);
viewHolder.addToCalVF.showNext();
viewHolder.eventTitle = (TextView) relayout.findViewById(R.id.postTitleTV);
title = viewHolder.eventTitle.getText().toString();
DeleteCalendarEntry(EVENTIDS.get(position), title);
}
});
viewHolder.postImageVF = (ViewFlipper) postLayout.findViewById(R.id.postBackgroundHolderVF);
index = index + 8;
}
catch (IndexOutOfBoundsException ie)
{
ie.printStackTrace();
}
}
else
{
viewHolder = (ViewHolder) postLayout.getTag();
}
return postLayout;
}
I do have a getCount and getItem method in the adapter that appropriately returns the correct data. I saw that there are many problems that can/will happen when trying to implement a listview in android. How do I have a stable, reliable listview adapter that I can count on the function the same way each time (what do I have to add so that this problem can stop)?