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)?
Related
I am working on a checkbox listview. What I have done so far is populated the list from local db, get all the checked item's databse id using the setOnCheckedChangeListener and store it in a separate table in my local db. This is how my code looks:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
dbHelper = new DBHelper(con);
database = dbHelper.getWritableDatabase();
switch (getItemViewType(position)){
case DYNAMIC_OBJECTIVE:
convertView = layoutInflater.inflate(R.layout.objective_list_view, null);
break;
case STATIC_OBJECTIVE:
convertView = layoutInflater.inflate(R.layout.other_objective_list_view, null);
break;
}
switch (getItemViewType(position)){
case DYNAMIC_OBJECTIVE:
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.objectiveCheckBox);
checkBox.setText(((Objectives)list.get(position)).getObjectiveTitle());
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
selectedObjectivesMap.put(((Objectives)list.get(position)).getObjectiveID(), "YES");
}else{
selectedObjectivesMap.put(((Objectives)list.get(position)).getObjectiveID(), "NO");
}
}
});
break;
case STATIC_OBJECTIVE:
TextView checkBoxOther = (TextView) convertView.findViewById(R.id.objectiveOtherCheckBox);
final TextView objectiveOtherET = (TextView) convertView.findViewById(R.id.objectiveOtherEditText);
checkBoxOther.setText((String)list.get(position));
//ll = (LinearLayout)convertView.findViewById(R.id.linearLayoutOther);
//viewNew = layoutInflater.inflate(R.layout.other_objective_row, null);
ImageButton imageButton = (ImageButton) convertView.findViewById(R.id.addOtherObjectiveTextBox);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), "Clicked123", Toast.LENGTH_SHORT).show();
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.otherobjectivedialog);
final EditText enterObjET = (EditText) dialog.findViewById(R.id.enterObjEditText);
Button closeEnterObjBtn = (Button) dialog.findViewById(R.id.closeEnterObjDialog);
Button objConfirmBtn = (Button) dialog.findViewById(R.id.enterObjConfirmBtn);
closeEnterObjBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
objConfirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredObj = enterObjET.getText().toString();
if(enteredObj.equals("")){
Toast.makeText(v.getContext(), "Please write a objective", Toast.LENGTH_LONG).show();
}else {
objectiveOtherET.setText(objectiveOtherET.getText().toString()+ " \n" + enteredObj);
otherObjList.add(enteredObj);
dialog.dismiss();
}
}
});
dialog.show();
/* LinearLayout linearLayoutNew = new LinearLayout(con);
linearLayoutNew.setOrientation(LinearLayout.VERTICAL);
et = new EditText(con);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setHint("Set some objective");
linearLayoutNew.addView(et);
ll.addView(linearLayoutNew);*/
}
});
break;
}
}
return convertView;
}
and this is how I'm populating my list:
ArrayList<Object> objectiveList = new ArrayList<>();
Cursor crs = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_OBJECTIVE +"", null);
while(crs.moveToNext())
{
String title = crs.getString(crs.getColumnIndex("title"));
int objectiveID = crs.getInt(crs.getColumnIndex("id"));
objectiveList.add(new Objectives(objectiveID, title));
}
crs.close();
objectiveList.add("Others");
listView.setAdapter(new ObjectivesAdapter(getActivity(), objectiveList));
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
PROBLEM:
This all works perfect but now I want to edit the same information. All I want is the existing checkbox id's (that were checked and store in my db) should be checked when I come back to this view. I have queried the data and I have the IDs but I don't know how to check the checkboxes based on their IDs.
Cursor crsCheckObj = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_PLAN_OBJECTIVE_MAP +" WHERE "
+ ItemsTable.COLUMN_PLAN_OBJECTIVE_MAP_PLANID +"='"+ Info.getInstance().getPlanVisitID() +"'", null);
if(crsCheckObj.getCount() > 0){
while (crsCheckObj.moveToNext()){
//Here IDs should match in order to check the checkboxes
}
}
crsCheckObj.close();
For that you can simply use checkbox.setChecked(true)
if it do not work then try following:
checkbox.postDelayed(new Runnable() {
#Override
public void run() {
checkbox.setChecked(true);
}
},100);
First setTag() for your checkbox like this:
checkBox.setTag(((Objectives)list.get(position)).getObjectiveID());
then all you need to is something like this:
Cursor crsCheckObj = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_PLAN_OBJECTIVE_MAP +" WHERE "
+ ItemsTable.COLUMN_PLAN_OBJECTIVE_MAP_PLANID +"='"+ Info.getInstance().getPlanVisitID() +"'", null);
if(crsCheckObj.getCount() > 0){
while (crsCheckObj.moveToNext()){
if(((Integer) checkBox.getTag()) == crsCheckObj.getInt(crsCheckObj.getColumnIndex("objective_id"))){
checkBox.setChecked(true);
}
}
}
crsCheckObj.close();
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.
[Edited]
Something like this..
when pressed the item labels are added with comma if there is item more than two[and when pressed again deletes the item labels with comma
this is what ive done so far
Note SeatP is a textView and seat_n is selected item label from the list
List<Seats> seatsList;
GridView myGrid;
MyGridAdapter adapter;
TextView seatlabel,pricelabel;
ImageView im;
String st,seat_n,seatp;
myGrid = (GridView) findViewById(R.id.grid);
seatlabel = (TextView) findViewById(R.id.labelSeat);
pricelabel = (TextView) findViewById(R.id.labelPrice);
public void updateMessage(){
adapter = new MyGridAdapter(getApplicationContext(),R.layout.seat_item,seatsList);
myGrid.setAdapter(adapter);
myGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
st = seatsList.get(position).getStatus();
seat_n = seatsList.get(position).getSeat_no();
p = seatsList.get(position).getPrice();
Log.d("price: ", p + "");
//Log.d("status: ", seat_n + "");
im = (ImageView) view.findViewById(R.id.seat1);
if (st.equalsIgnoreCase("available")) {
im.setImageResource(R.drawable.seat);
myStatus = true;
seatsList.get(position).setStatus("select");
Log.d("status 1: ",myStatus+"");
if (seatp.length()>1){
seatp = seatp+"," + seat_n;
}else {
seatp = seatp+ seat_n;
}
pr = pr+p;
seatlabel.setText(seatp.trim());
pricelabel.setText(Integer.toString(pr));
}
if(st.equalsIgnoreCase("select")) {
// Toast.makeText(getApplicationContext(), "seat: " + seatsList.get(position).getStatus(), Toast.LENGTH_SHORT).show();
im.setImageResource(R.drawable.seat_avv);
seatsList.get(position).setStatus("available");
pr = pr-p;
pricelabel.setText(Integer.toString(pr));
seatp= seatlabel.getText().toString();
//Log.d("seatlabel: ",ab);
//seatp= seatp.replace(seat_n, "");
if(seatp.length()>=5){
seatp= seatp.replace(","+seat_n, "");
}else {
seatp= seatp.replace(seat_n+",", "");
}
Log.d("seatp Length: ",seatp.length()+"");
/*if(seatp.length()>2){
seatp= seatp.replace(", "+seat_n, "");
Log.d("seatp Length2: ",seatp.length()+"");
}else{
seatp= seatp.replace(seat_n+", ", "");
Log.d("Deleting: ",seat_n+"");
seatp = "";
}*/
Log.d("seatabzz: ",seatp);
seatlabel.setText(seatp.trim());
}
}
});
}
Here the logic is good for 2nd or more items But didn't worked for the first item
if i understand you well, you can use ArrayList
call addOrRemoveItem() on click at labels, passing the text you need to add
and when save or next or whatever is clicked call getAsCommaSeparator()
ArrayList<String> items = new ArrayList<>();
public void addOrRemoveItem(String item){
if(items.contains(item)){
items.remove(item);
}else{
items.add(item);
}
}
public String getAsCommaSeparator(){
return android.text.TextUtils.join(",",items);
}
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.
I am inflating the passenger_details_layout in main_passenger_details_layout.At run time i am setting the values in TextView . I am setting up pax_id that is invisible for every row that i am inflating in it.So on click of passenger_details_layout i want to call a new activity and pass the pax_id to the new activity.
Pax_id will be like 1,2,3 for every time for loop will run.So on click of 1 row i want to get the pax_id of first row that i have set.
Please help how could i do this Will be thank full to you.
Code to Infalate
ItinResponse data = obj.parseXMLData(fXmlFile);
List<SectorRecords> sectorList = data.getSectorRecordsDetails();
int items = 0;
List<PassengerDetails> listdata = data.getPaxDetails();
int i = 0;
for (PassengerDetails elements : listdata) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.passenger_details_layout, main, false);
firstName = (TextView) layout.findViewById(R.id.first_pax_name);
pax_id = (TextView) layout.findViewById(R.id.pax_id);
firstName.setText(elements.getFirstName() + " "
+ elements.getLastName());
pax_id.setText(elements.getPaxId());
main.addView(layout, i);
i++;
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)"+pax_id.getText(), Toast.LENGTH_LONG).show();
}
});
On every row is showing the last pax id
You have to do nothing what you are trying
Replace this
pax_id.setText(elements.getPaxId());
to
layout.setId(Integer.parseInt(elements.getPaxId()));
And in your Layout Click
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)"+layout.getId(), Toast.LENGTH_LONG).show();
}
});
Every time you will get the Unique ID that u want to set
All the best...!!!!
Use
TextView paxView = (TextView)v.findViewById(R.id.pax_id);
String pax_value = paxView.getText().toString();
On button click of every row do like this
Intent intent=new Intent(this,YOUR_NEXT_ACTIVIY.class);
intent.putExtra("paxid", pax_id.getText());
startActivity(intent);
ItinResponse data = obj.parseXMLData(fXmlFile);
List<SectorRecords> sectorList = data.getSectorRecordsDetails();
int items = 0;
List<PassengerDetails> listdata = data.getPaxDetails();
int i = 0;
for (PassengerDetails elements : listdata) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.passenger_details_layout, main, false);
firstName = (TextView) layout.findViewById(R.id.first_pax_name);
pax_id = (TextView) layout.findViewById(R.id.pax_id);
firstName.setText(elements.getFirstName() + " "
+ elements.getLastName());
pax_id.setText(elements.getPaxId());
layout.setTag(elements.getPaxId());
main.addView(layout, i);
i++;
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String paxId = v.getTag().toString();
// do some staff
}
});
}
// try this
ItinResponse data = obj.parseXMLData(fXmlFile);
List<SectorRecords> sectorList = data.getSectorRecordsDetails();
int items = 0;
List<PassengerDetails> listdata = data.getPaxDetails();
int i = 0;
for (PassengerDetails elements : listdata) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.passenger_details_layout, main, false);
firstName = (TextView) layout.findViewById(R.id.first_pax_name);
pax_id = (TextView) layout.findViewById(R.id.pax_id);
firstName.setText(elements.getFirstName() + " "
+ elements.getLastName());
pax_id.setText(elements.getPaxId());
layout.setTag(elements);
main.addView(layout, i);
i++;
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
PassengerDetails elements = (PassengerDetails) v.getTag();
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)"+elements.getPaxId(), Toast.LENGTH_LONG).show();
}
});
}