How to fix ArrayAdapter changing positions when listView scrolls? - java

I still not used a ViewHolder class, (I know about the performance of the list view, and will implement it as soon as possible) but I already try overwrite those two methods on array adapter (getViewTypeCount() and getItemViewType) but continue not working.
At my standpoint my array adapter onle handle with ONE type of view, so theoretically I didn't have to overwrite those methods, but i dont know what is happening, just when I scroll my listView the positions get disorganized.
My ArrayAdapter:
private Context context;
private ArrayList<Task> taskArrayList;
public TasksAdapter(#NonNull Context c, #NonNull ArrayList<Task> objects) {
super(c, R.layout.task_row, objects);
this.context = c;
this.taskArrayList = objects;
}
#Override
public int getViewTypeCount() {
return taskArrayList.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE );
Task task = taskArrayList.get(position);
View view = inflater.inflate(R.layout.task_row, parent, false);
if(TaskActivity.getIsClicked() && TaskActivity.getPositionClicked()-1 == position){
view.setBackgroundResource(R.color.backgroundSelectedItem);
}
TextView timeTextView = view.findViewById(R.id.timeTextView);
TextView taskNameView = view.findViewById(R.id.taskNameText);
TextView dateTextView = view.findViewById(R.id.dateTextView);
FloatingActionButton fab = view.findViewById(R.id.myFabTask);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM");
String dateString = sdf.format(task.getDate());
int hour = (int) task.getTime()/3600000;
int minutes = (int) (task.getTime() % 3600000) / 60000;
String stringHour = Integer.toString(hour);
String stringMinutes = Integer.toString(minutes);
if(stringHour.length() == 1){stringHour = "0"+stringHour;}
if(stringMinutes.length() == 1){stringMinutes = "0"+stringMinutes;}
String timeString = stringHour+":"+stringMinutes;
timeTextView.setText(timeString);
taskNameView.setText(task.getName());
dateTextView.setText(dateString);
return view;
}
My Main code where i call and use the adapter:
mTaskListView = findViewById(R.id.task_list_view);
refreshAdapter();
isClicked = false;
positionClicked = 0;
mTaskListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(positionClicked == (position+1) || positionClicked == 0){
if(!isClicked){
isClicked = true;
positionClicked = position+1;
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
changeLayoutVisibility(1);
Task task = adapter.getItem(position);
parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.backgroundSelectedItem));
}else {
isClicked = false;
positionClicked = 0; mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
changeLayoutVisibility(0);
parent.getChildAt(position).setBackgroundColor(Color.WHITE);
}
}
}
});
Function on Main activity:
private void refreshAdapter() {
adapter = null;
//Get the array with tasks
adapter = new TasksAdapter(this, mDBAdapter.getAllTask());
//Set the list view
mTaskListView.setAdapter(adapter);
}
My row of listView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/white"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/timeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:layout_marginTop="17dp"
android:layout_marginBottom="17dp"
android:text="00:00"
android:textColor="#color/controlColorNormal"
android:textSize="30sp" />
<TextView
android:id="#+id/taskNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/timeTextView"
android:layout_marginLeft="38dp"
android:layout_marginStart="38dp"
android:layout_toEndOf="#+id/timeTextView"
android:layout_toRightOf="#+id/timeTextView"
android:text="Nome da tarefa"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/dateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/taskNameText"
android:layout_alignStart="#+id/taskNameText"
android:layout_below="#+id/taskNameText"
android:text="Data adicionada"
android:textColor="#color/colorHint" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/myFabTask"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="16dp"
android:src="#mipmap/ic_action_send"
app:elevation="4dp"
app:fabSize="mini">
</android.support.design.widget.FloatingActionButton>
My List View:
<ListView
android:id="#+id/task_list_view"
android:layout_width="368dp"
android:layout_height="475dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:defaultFocusHighlightEnabled="true"
android:divider="#color/borderColor"
android:dividerHeight="1px"
android:gravity="center_horizontal|top"
android:theme="#style/MyPicker"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

You said that your adapter only handle with ONE type of view but:
When #Override getViewTypeCount() you return the size of taskArrayList, so the system understand that you have taskArrayList.size() type of view. In your case, it should be 1.
List item In getItemViewType() method, the value return must is the identify of view type, not the item's position. In your case also, it should return 0 as default.
Hope it help!

I just solve it by changing:
parent.
getChildAt(position).
setBackgroundColor(getResources().getColor(R.color.backgroundSelectedItem));
By:
view.setBackgroundResource(R.color.backgroundSelectedItem);

Don't do following operations in getView().
//get and format the date
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM");
String dateString = sdf.format(task.getDate());
//convert the milliseconds to minute and hour
int hour = (int) task.getTime()/3600000;
int minutes = (int) (task.getTime() % 3600000) / 60000;
String stringHour = Integer.toString(hour);
String stringMinutes = Integer.toString(minutes);
if(stringHour.length() == 1){stringHour = "0"+stringHour;}
if(stringMinutes.length() == 1){stringMinutes = "0"+stringMinutes;}
String timeString = stringHour+":"+stringMinutes;
Create new Function which return type is String and call that function in timeTextView.setText.
Make function Like this:
private String getTimeStirng(Object date){
//get and format the date
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM");
String dateString = sdf.format(date);
//convert the milliseconds to minute and hour
int hour = (int) task.getTime()/3600000;
int minutes = (int) (date % 3600000) / 60000;
String stringHour = Integer.toString(hour);
String stringMinutes = Integer.toString(minutes);
if(stringHour.length() == 1){stringHour = "0"+stringHour;}
if(stringMinutes.length() == 1){stringMinutes = "0"+stringMinutes;}
String timeString = stringHour+":"+stringMinutes;
return timeString;
}
Call it like: timeTextView.setText(getTimeString(task.getDate()));
Thanks.
Happy Coding.

Related

Custom View Calendar (TableLayout) is extremely slow

I have created a Calendar Custom View from scratch. The reason I don't use the CalendarView is that I want to customize it myself. I need a few functions that the CalendarView doesn't have. So I built a CustomView:
calendar.xml:
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:id="#+id/calender">
<TextView
android:id="#+id/calender_text_view_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="#id/calender_button_next_month"
app:layout_constraintBottom_toBottomOf="#id/calender_button_next_month"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:textColor="#color/colorPrimary"
android:textSize="20sp"
/>
<ImageButton
android:id="#+id/calender_button_next_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.8"
app:layout_constraintTop_toTopOf="parent"
android:src="#drawable/ic_navigate_next_colorprimary_36dp"
android:background="#android:color/transparent"
android:contentDescription="#null"/>
<ImageButton
android:id="#+id/calender_button_prev_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.2"
android:src="#drawable/ic_navigate_before_colorprimary_36dp"
android:background="#android:color/transparent"
android:contentDescription="#null"
/>
<TableLayout
android:id="#+id/calender_table_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/calender_text_view_month"
android:layout_marginTop="30dp"
android:divider="#drawable/recyclerview_divider"
android:showDividers="middle"
android:background="#drawable/table_stroke_color_primary"
/>
</merge>
Calendar.java: (Here I have deleted a few methods that are not important, like getDaysOfMonth. This is just a little bit of math)
public class Calender extends ConstraintLayout {
private TextView tvMonth;
private TableLayout calender;
private int year;
private int month;
private Calendar c;
private int selectedDay = -1;
private int selectedMonth = -1;
private int selectedYear = -1;
private Context context;
public Calender(Context context) {
this(context, null);
}
public Calender(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Calender(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
LayoutInflater l = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
l.inflate(R.layout.calender, this, true);
tvMonth = findViewById(R.id.calender_text_view_month);
calender = findViewById(R.id.calender_table_layout);
c = Calendar.getInstance();
month = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
makeCalender();
}
private void makeCalender() {
ArrayList<TableRow> rows = new ArrayList<>();
tvMonth.setText(String.format("%s %s", month, year));
calender.removeAllViews();
calender.addView(createCalenderHeader());
int dayOfWeek = getFirstDayOfCurrentMonth();
int daysOfMonth = getDaysOfMonth(month, year);
int daysPrevMonth = month > 0 ? getDaysOfMonth(month - 1, year) : getDaysOfMonth(11, year - 1);
int prevMonth = month > 0 ? month - 1 : 11;
int prevYear = month > 0 ? year : year - 1;
TableRow tr1 = new TableRow(context);
tr1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tr1.setShowDividers(TableRow.SHOW_DIVIDER_MIDDLE);
tr1.setDividerDrawable(ContextCompat.getDrawable(context, R.drawable.table_row_divider));
for (int day = 1; day <= dayOfWeek; day++) {
tr1.addView(createCalenderItemPrev(daysPrevMonth + day - dayOfWeek, prevMonth, prevYear));
}
for (int day = 1; day <= daysOfMonth; day++) {
if((dayOfWeek + day) <= 7) {
tr1.addView(createCalenderItem(day, month, year));
if(dayOfWeek + day == 7)
calender.addView(tr1);
continue;
}
if (rows.size() == 0 ||rows.get(rows.size() - 1).getChildCount() == 7) {
rows.add(new TableRow(context));
rows.get(rows.size() - 1).setShowDividers(TableRow.SHOW_DIVIDER_MIDDLE);
rows.get(rows.size() - 1).setDividerDrawable(ContextCompat.getDrawable(context, R.drawable.table_row_divider));
rows.get(rows.size() - 1).setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
}
rows.get(rows.size() - 1).addView(createCalenderItem(day, month, year));
}
c.set(year, month, daysOfMonth);
int lastDayOfMonth = c.get(Calendar.DAY_OF_WEEK);
if(lastDayOfMonth != 1) {
int nextMonth = month < 11 ? month + 1 : 0;
int nextYear = month < 11 ? year : year + 1;
for (int i = lastDayOfMonth; i <= 7; i++) {
rows.get(rows.size() - 1).addView(createCalenderItemPrev(i - lastDayOfMonth + 1, nextMonth, nextYear));
}
}
for(int i = 0; i < rows.size(); i++) {
calender.addView(rows.get(i));
}
}
private CalenderItem createCalenderItem(int day, int month, int year) {
CalenderItem item = new CalenderItem(context);
item.setDate(day, month, year);
item.setOnItemClickedListener(new CalenderItem.IItemClicked() {
#Override
public void itemClicked(int day, int month, int year) {
selectedDay = day;
selectedMonth = month;
selectedYear = year;
makeCalender();
}
});
return item;
}
private CalenderItem createCalenderItemPrev(int day, int month, int year) {
CalenderItem item = new CalenderItem(context);
item.setDate(day, month, year);
return item;
}
}
calendar_item.xml:
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:focusable="true"
>
<TextView
android:id="#+id/text_view_calender_item_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="4dp"
android:clickable="false"
android:textAlignment="center"
/>
<TextView
android:id="#+id/text_view_calender_item_routine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/text_view_calender_item_date"
android:layout_marginBottom="4dp"
app:layout_constraintBottom_toBottomOf="parent"
android:clickable="false"
android:textAlignment="center"
/>
</merge>
CalendarItem.java: (Again, I deleted the parts that are not important)
public class CalenderItem extends ConstraintLayout {
private final TextView tvDate;
private final TextView tvRoutine;
private IItemClicked listener = null;
public void setOnItemClickedListener(IItemClicked listener) {
this.listener = listener;
}
public CalenderItem(Context context) {
this(context, null);
}
public CalenderItem(Context context, #Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CalenderItem(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater l = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
l.inflate(R.layout.calender_item, this, true);
tvDate = findViewById(R.id.text_view_calender_item_date);
tvRoutine = findViewById(R.id.text_view_calender_item_routine);
setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1));
setBackgroundResource(R.drawable.background_calender_item);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null) {
listener.itemClicked(day, month, year);
}
}
});
}
public interface IItemClicked {
void itemClicked(int day, int month, int year);
}
}
This Calendar Custom View works. Every Item is where it should be. But the thing is that it takes extremely long to build, up to a second or two. Everytime I open the fragment with the calendar, the app freezes for one or two seconds. I can't explain why this is.
I can edit the implementation or some other code if you want. But I think that is everything what's important.
You can improve your custom CalendarView by using RecyclerView instead of TableView. And using RecyclerView will give you more ability to customize date cells (select/deselect, select range, etc.) , support scrolling, swipe, etc.
Or you can use this library, which provide highly customizable CalendarView
Okay, I will answer the question myself, because I managed to solve the issue. It is so slow, because is is rendering more then 30 CalenderItems everytime, which contain of a LinearLayout and two TextViews. I changed this to just one TextView with an "\n" to make it look like two TextViews. So I could also remove the Layout and just extend TextView Class. So now, it has to render more than 30 TextViews and Layouts less then before, which makes it way faster.

Speeding up big set of programmatically created buttons display

I have an activity which generates a scrollable list (let's say a column) of programmatically created buttons from a List which is the result of an sqlite table read and my problem is that as the List is growing (and so the number of buttons) the initial painting of the screen is becoming slow (at the moment is taking 3 seconds with 50 buttons to draw) so I'm looking for a solution to this.
At first I thought of using a thread (runnable, handler or whatever is best), let's say creating a new thread inside the For which iterates over the list but it's not working (or at least I'm not being able to make it to work) so my question is the next:
Starting from a List<> which is the most appropiate way to create a big set of scrollable buttons so users doesn't have such delay when accesing the screen.
Paginating could be an option, but I'd like to know about other possibilities first and leave that as a last resource.
Thanks, and below is my code.
public static void createButtons(LinearLayout llContainer,
List<TestType> TestTypes, List<Test> Tests,
int buttonFontSize) {
Context oContext = llContainer.getContext();
String strTheme = TMAppearance.getThemeFromPreferences(oContext);
testMe = ((ApplicationConfiguration)oContext.getApplicationContext());
int callerActivity = TestTypes!=null ? 2 : 1;
if (TestTypes!=null || Tests!=null) {
int lCols = strTheme.equals(testMe.theme_vivid) ? 1 : 2;
//int sourceElementIndex = 0;
int originListSize = calculateOriginalListSize(callerActivity, TestTypes, Tests);
int lRows = (int) Math.ceil((double)originListSize/lCols);
List<String> aStartColors = TMUtils_ThemeVivid.generateStartColorArray(lRows, oContext);
List<String> aEndColors = TMUtils_ThemeVivid.generateEndColorArray(lRows, oContext);
for (i = 0; i < lRows; i++) {
LinearLayout outerButtonLayout = generateOuterButtonLayout(oContext);
for (j = 0; j < lCols; j++) {
final Thread r = new Thread() {
public void run() {
LinearLayout innerButtonLayout = generateInnerButtonLayout(oContext);
outerButtonLayout.addView(innerButtonLayout, j);
if (sourceElementIndex<originListSize){
final TMButton oButton = new TMButton(oContext);
if (callerActivity==1) { //testMenu
setTestMenuButtonSettings(oButton, sourceElementIndex, Tests);
} else {
if (callerActivity==2) { //testTypeMenu
setTestTypeMenuButtonSettings(oButton, sourceElementIndex, TestTypes);
}
}
if (strTheme.equals(testMe.theme_vivid)){
oButton.fontSize = buttonFontSize;
oButton.gradientStartColor = aStartColors.get(i);
oButton.gradientEndColor = aEndColors.get(i);
}else{
if (strTheme.equals(testMe.theme_purple)){
oButton.gradientStartColor = testMe.btnStartColor_purple;
oButton.gradientEndColor = testMe.btnEndColor_purple;
}
}
configureButton(oButton, callerActivity);
oButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Context oContext = v.getContext();
TMButton oButton = (TMButton) v;
int callerActivity = Integer.valueOf(v.getTag().toString().split("#")[0]);
String sourceId = String.valueOf(v.getTag().toString().split("#")[1]);
if(event.getAction() == MotionEvent.ACTION_DOWN) { //pressed
setButtonPressed(oButton);
TMSound.playButtonSound(oContext);
} else if (event.getAction() == MotionEvent.ACTION_UP) { //released
setButtonReleased(oButton);
startTargetActivity(callerActivity, sourceId, oContext);
}
return true;
}
});
TMAppearance.doButtonAnimation(oContext, oButton, i);
innerButtonLayout.addView(oButton);
sourceElementIndex++;
}
}
};
r.run();
}
llContainer.addView(outerButtonLayout);
}
}
}
0X0nosugar is correct. A RecycleView will provide better performance, but many beginners have more difficulty implementing it and with only 50 buttons performance shouldn't really be an issue. And although I generally like to abide by the rule 'Use the best available solution' I think it is still appropriate to learn how to implement the ListView. So...
You will need to create a custom adapter:
public class MyListDataAdapter extends ArrayAdapter<MyListData> {
private static final String TAG = "MyListDataAdapter";
public MyListDataAdapter(Context context, ArrayList<MyListData> data) {
super(context, 0, data);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final MyListData data = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.edit_list_item, parent, false);
}
// Add a TextView if you need one
final TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
Button btnEditTicketHolder = (Button) convertView.findViewById(R.id.btnEdit);
btnEditTicketHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long userId = data.getUserId();
String fName = data.getFirstName();
Intent intent = new Intent(getContext(), EditActivity.class);
intent.putExtra("userId", userId);
intent.putExtra("fName", fName);
getContext().startActivity(intent);
}
});
String name = data.getFirstName();
tvName.setText(name);
return convertView;
}
}
Now you need your MyListData class to hold the data:
public class MyListData {
// Add more as you need
private long userId;
private String firstName;
public MyListData(){
}
public void setFirstName(String name){ this.firstName = name; }
public void setUserId(long id){ this.userId = id; }
public String getFirstName(){ return this.firstName; }
public long getUserId(){ return this.userId; }
}
Your custom ListView layout could look something like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
>
<TextView
android:id="#+id/tvName"
android:text="With Whom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
>
<Button
android:id="#+id/btnEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:text="Edit"
android:backgroundTint="#color/colorAccent"
android:focusable="false"
/>
</LinearLayout>
</RelativeLayout>
In your Activity (eg. in the onCreate() method) where the ListView you will need to populate the data for the ListView. This should not be done on the UI Thread
ArrayList<MyListData> arrayListData = new ArrayList<MyListData>();
MyListDataAdapter adapter = new MyListDataAdapter(this, arrayListData);
for (MyListData g : result) {
adapter.add(g);
}
mLstMy.setAdapter(adapter);
Also in the activity where the ListView is to be maintained set up some onClick event handlers if you need them:
(I find that one of the small advantages of the ListView is that the onClick event is easier it implement than in the RecycleView)
mMyLst = (ListView) findViewById(lstMy);
mMyLst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
MyListData data = (MyListData) parent.getItemAtPosition(position);
selectedName = data.getName();
Intent intent = new Intent(ShowListDataActivity.this, MainActivity.class);
startActivity(intent);
}
});
mMyLst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
MyListData data = (MyistData) adapterView.getItemAtPosition(i);
selectedName = data.getFirstName();
selectedTicketPosition = i;
// removeValue is my own method for removing an entry from the
// list MyListData and then call adapter.notifyDataSetChanged();
removeValue(i);
return true;
}
});

How get to all value of EditText in Custom ListView

Good day guys,
I successfully populated my custom-listview-layout in my activity,
but the problem is I can't get all the value of populated EditText in my listview, please help me what approach should I do,
thanks
Picture Adapter.java
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
final dataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate( R.layout.row_layout,parent, false);
handler = new dataHandler();
handler.pictures = (ImageView) row.findViewById(R.id.pictures);
handler.name = (TextView) row.findViewById(R.id.picturename);
handler.price= (EditText) row.findViewById(R.id.price);
handler.add = (Button) row.findViewById(R.id.btnplus);
handler.minus = (Button) row.findViewById(R.id.btnminus);
row.setTag(handler);
}else{
handler = (dataHandler) row.getTag();
}
PSP psp;
psp =(PSP) this.getItem(position);
Picasso.with(getContext()).load(psp.getPicture()).resize(200, 155).into(handler.pictures);
handler.name.setText(psp.getName());
handler.price.setText(psp.getPrice());
return row;
}
MainActivity.java
PictureAdapter adapter;
listView = (ListView) findViewById(R.id.ls);
adapter = new PictureAdapter(this,R.layout.row_layout);
listView.setAdapter(adapter);
try {
JSONArray users = response.getJSONArray("user");
for (int x = 0; x <= users.length()-1; x++) {
JSONObject user = users.getJSONObject(x);
PSP psp = new PSP(imageUri+user.getString("image")+".png",user.getString("username"),"0");
adapter.add(psp);
}
} catch (JSONException e) {
e.printStackTrace();
}
PSP.java
public class PSP
{
private String picture;
private String name;
private String price;
public String getPicture() {
return picture;
}
public PSP(String picture, String name, String price){
this.setPicture(picture);
this.setName(name);
this.setPrice(price);
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="80dp"
android:background="#000000">
<ImageView
android:id="#+id/pictures"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/picturename"
android:layout_width="115dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/pictures"
android:text="Kim Domingo"
android:gravity="center"
android:textColor="#FFFFFF"
/>
<Button
android:id="#+id/btnplus"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="+"
android:textSize="50px"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/picturename"
android:layout_toEndOf="#+id/picturename"
/>
<EditText
android:id="#+id/price"
android:layout_width="50dp"
android:layout_height="50dp"
android:focusable="false"
android:textColor="#FFFFFF"
android:inputType="number"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/btnplus"
android:layout_toEndOf="#+id/btnplus" />
<Button
android:id="#+id/btnminus"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="-"
android:textSize="50px"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/price"
android:layout_toEndOf="#+id/price" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#FFFFFF"
android:layout_below="#+id/pictures"
android:id="#+id/editText"></View>
I created same before like this
You can use the HashMap map = new HashMap<>(); for what item user click. I assume that you use two button click are available in adapter class if not then add it.
Step 1 First Declare the HashMap map = new HashMap<>(); in adapter.
Step 2 Then put value in HashMap map.put("key","value"); This code put in both plus and minus button click event.
Step 3 Call ShowHashMapValue(); method below to the map.put("key","value"); for see the HashMap values check logcat for that.
Compare this adapter code for understand easily if any problem just comment below.
ListAdapter.java
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
//price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
listViewHolder.tvPrices.getTag();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
ShowHashMapValue();
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
So so here is logic. You need to declare a boolean in PSP. by default set it to false.
Now when + button will be triggered you need to set that boolean check to true
then in your set price create this logic.
public String getPrice() {
if(check==true){
price++;
}
else{
price--;
}
return price;
}
If i correctly understand you then this surely will help you. Good Luck!

Android Custom BaseAdapter getView not called

So, I have scoured the interwebs and I cannot find a solution for this based on other people's experiences, so I am posting this issue. (Please note that this is my 1st android app experience and I am debugging / updating an existing app.)
When I implement my custom NotesListAdapter (extends BaseAdapter) on the ListView, mListNotesView (mListNotesView.setAdapter(this)), and load the data into the ArrayList mNoteList, the getView function is not being called. Also, I found that mListNotesView.setBackgroundResource is not chaning the background of the control, either. I have a similar implementation on a previous activity that works exactly correct. When I copied over the class and changed it to handle my ArrayList, it broke. I have getCount returning the ArrayList size(), which is not 0, and getItemId returns position. I have a feeling it may be my XML or my setup because it's acting like the ListView is not visible. I am perplexed. How do I get the ListView to show? Anything inside of the getView has not been reached so it may be buggy.
ViewTicketOrderActivity (Some parts ommitted for size)
public class ViewTicketOrderActivity extends Activity {
MySQLDatabase myDataBase;
Ticket mTicket;
public ArrayList<Notes> mNotes = new ArrayList<Notes>();
String mErrorString;
Button mAddUpdateButton;
Button mAcceptButton;
//Button mViewNotesButton;
NotesListAdapter mNotesListAdapter;
static final int ERROR_DIALOG = 0;
static final int SUCCESS_DIALOG = 1;
static final int COMPLETED_DIALOG = 2;
static final int RESTART_DIALOG = 3;
static final int LOADING = 0;
static final int LOAD_ERROR = 1;
static final int LOADED = 4;
static final String TICKET_EXTRA = "ticket_extra";
static final String TAG = "ViewTicketOrderActivity";
private static final boolean gDebugLog = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewticketorder);
Activity context = this;
String theTitle = "Sundance Ticket Order";
theTitle += (MySQLDatabase.TESTING == true) ? " (DEV SERVER)" : " (LIVE)";
setTitle(theTitle);
myDataBase = MySQLDatabase.getMySQLDatabase(this);
if (gDebugLog) {
DebugLogger.logString(TAG, ".onCreate");
}
mNotesListAdapter = new NotesListAdapter(context, R.id.note_list);
Log.d(this.toString(),this.mNotesListAdapter.toString());
}
private class NotesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Notes> mNoteList;
private ListView mListNotesView;
private Activity mActivity;
int mState = LOADING;
String mErrorMessage;
private NotesListAdapter(Activity context, int listViewID) {
mActivity = context;
mNoteList = new ArrayList<Notes>();
mInflater = LayoutInflater.from(context);
mListNotesView = (ListView)context.findViewById(listViewID);
mListNotesView.setBackgroundResource(R.color.emergency_red);
mListNotesView.setAdapter(this);
Log.d(mListNotesView.toString(), String.valueOf(mListNotesView.getCount()));
this.notifyDataSetChanged();
//mListNotesView.setVisibility(View.VISIBLE);
}
void setLoading()
{
mState = LOADING;
this.notifyDataSetChanged();
}
void setLoadError(String errorString)
{
mState = LOAD_ERROR;
mErrorMessage = errorString;
this.notifyDataSetChanged();
}
void setNoteList(ArrayList<Notes> inNotes)
{
mState = LOADED;
mNoteList.clear();
mNoteList.addAll(inNotes);
Log.d("SetNoteList", "TRUE " + inNotes);
//mNoteList = mNotes;
this.notifyDataSetChanged();
}
/**
* Use the array index as a unique id.
*
* #see android.widget.ListAdapter#getItemId(int)
*/
#Override
public long getItemId(int position) {
return position;
}
public int getCount(){
if (mState == LOADED) {
Log.d("getCount",String.valueOf(mNoteList.size()));
return mNoteList.size();
} else {
return 0;
}
}
/**
* Make a view to hold each row.
*
* #see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
Log.d("getView",this.toString());
if (mState == LOADED) {
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there
// is no need
// to reinflate it. We only inflate a new View when the
// convertView supplied
// by ListView is null.
Notes note = this.getItem(position);
if (convertView == null) {
/*if (ticket.emergency())
{
convertView = mInflater.inflate(R.layout.emergency_ticket_list_item_opt,
null);
}
else
{
convertView = mInflater.inflate(R.layout.ticket_list_item,
null);
}*/
convertView = mInflater.inflate(R.layout.noteslist_item,
null);
// Creates a ViewHolder and store references to the two
// children views
// we want to bind data to.
holder = new ViewHolder();
holder.noteText = (TextView) convertView
.findViewById(R.id.text_note);
holder.dateText = (TextView) convertView
.findViewById(R.id.text_note_date);
holder.createByText = (TextView) convertView
.findViewById(R.id.text_note_by);
holder.createByIDText = (TextView) convertView
.findViewById(R.id.text_note_by_id);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the
// TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.noteText.setText(note.note());
holder.dateText.setText(note.date());
holder.createByText.setText(note.createBy());
holder.createByIDText.setText(note.employeeID());
if(!mTicket.employeeID().equals(note.employeeID())){
convertView.setBackgroundResource(R.drawable.solid_purple);
}
} else if (mState == LOADING ) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.loading_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Loading tickets");
} else if (mState == LOAD_ERROR) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.load_error_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Error loading tickets");
String errorString = mErrorMessage != null ? mErrorMessage : "";
TextView errorText = (TextView)convertView.findViewById(R.id.errorText);
errorText.setText(errorString);
}
return convertView;
}
class ViewHolder {
TextView noteText;
TextView dateText;
TextView createByText;
TextView createByIDText;
}
//#Override
/*public int getCount() {
*//*if (mState == LOADED) {
*//*
Log.d("getCount mState " + mState,String.valueOf(mNoteList.size())+", "+String.valueOf(mNotes.size()));
return mNoteList.size();
*//*} else {
Log.d("getCount mState " + mState,"0");
return 0;
}*//*
}*/
#Override
public Notes getItem(int position) {
Log.d("getItem",mNoteList.get(position).toString());
return mNoteList.get(position);
}
#Override
public int getItemViewType (int position) {
int result = mState;
Log.d("getItemId",String.valueOf(position));
return result;
}
#Override
public int getViewTypeCount ()
{
return 4;
}
}
protected void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
mTicket = (Ticket)extras.getSerializable(TICKET_EXTRA);
}
else
{
mTicket = new Ticket();
}
if (mTicket.emergency())
{
setContentView(R.layout.view_emergency_ticketorder);
}
else
{
setContentView(R.layout.viewticketorder);
}
if (gDebugLog)
{
DebugLogger.logString(TAG, ".onResume mTicket " + mTicket);
}
TicketCheckService.clearNotificationForNewTicket(mTicket);
new GetTicketTask().execute();
new GetNotesTask().execute();
updateDisplayedTicket();
}
private void updateDisplayedTicket() {
mAddUpdateButton = (Button)findViewById(R.id.addUpdateButton);
mAcceptButton = (Button)findViewById(R.id.acceptButton);
//mViewNotesButton = (Button)findViewById(R.id.viewNotesButton);
String ticketStatus = myDataBase.getDescriptionStringForStatusString(mTicket.status());
if(ticketStatus == "Job Rejected") {
mAddUpdateButton.setText("Restart Job");
} else {
mAddUpdateButton.setText("Add Update");
}
if(ticketStatus == "Requested") {
mAcceptButton.setText("Accept");
} else if(ticketStatus != "Requested") {
mAcceptButton.setText("Back");
}
//mViewNotesButton.setText(R.string.viewNotes);
TextView idText = (TextView)findViewById(R.id.textTicketID);
idText.setText(mTicket.id());
//TextView descriptionText = (TextView)findViewById(R.id.textDescription);
//descriptionText.setText(mTicket.description());
TextView titleText = (TextView)findViewById(R.id.textTitle);
titleText.setText(mTicket.title());
TextView storeIDText = (TextView)findViewById(R.id.textStoreID);
storeIDText.setText(mTicket.store());
String formatPhone;
TextView storePhoneText = (TextView)findViewById(R.id.textStorePhone);
if(mTicket.phoneNo().isEmpty()){
formatPhone = "NO PHONE NO.";
} else {
storePhoneText = (TextView) findViewById(R.id.textStorePhone);
formatPhone = mTicket.phoneNo().replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)$2-$3");
storePhoneText.setOnClickListener(new CallClickListener(mTicket.phoneNo()));
}
storePhoneText.setText(formatPhone);
TextView categoryText = (TextView)findViewById(R.id.textCategory);
String categoryDescription = MySQLDatabase.getDescriptionStringForCategoryString(mTicket.category());
categoryText.setText(categoryDescription);
if(ticketStatus == "Completed Pending") {
showDialog(COMPLETED_DIALOG);
}
}
public void onClickAccept(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAcceptButton.getText() =="Accept") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new AcceptTicketTask().execute();
} else {
finish();
}
}
public void onClickAddUpdate(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAddUpdateButton.getText() =="Add Update") {
Intent i = new Intent(this, UpdateTicketActivity.class);
i.putExtra(UpdateTicketActivity.TICKET_EXTRA, mTicket);
startActivity(i);
} else if(mAddUpdateButton.getText() =="Restart Job") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new RestartTicketTask().execute();
}
}
private class AcceptTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "1", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString) {
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(SUCCESS_DIALOG);
mAcceptButton.setText("Back");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class RestartTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "7", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString)
{
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(RESTART_DIALOG);
mAcceptButton.setText("Done");
mAddUpdateButton.setText("Add Update");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class GetTicketTask extends AsyncTask<Void, Integer, Ticket>
{
String mError = null;
protected Ticket doInBackground(Void... parent) {
Ticket result = null;
try {
result = myDataBase.getTicketWithID(mTicket.id(), mTicket.employeeID());
} catch (IOException e) {
// TODO Auto-generated catch block
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Ticket result)
{
if (null != result) {
mTicket = result;
} else {
setLoadError(mError);
}
}
}
private class GetNotesTask extends AsyncTask<Void, Integer, ArrayList<Notes>> {
String mError = null;
protected ArrayList<Notes> doInBackground(Void... parent) {
ArrayList<Notes> result = new ArrayList<Notes>();
try {
result = myDataBase.getTicketNotes(mTicket.id());
} catch (IOException e) {
// TODO Auto-generated catch block
myDataBase.debugLog("Error caught" + e);
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(ArrayList<Notes> result) {
if (null != result) {
Log.d("Result", result.toString());
mNotes = result;
} else {
Log.d("SetNoteList","FALSE");
mNotesListAdapter.setLoadError(mError);
}
}
}
private void updateDisplayedNotes(){
ArrayList<Notes> newNotes = mNotes;
if(newNotes != null) {
mNotesListAdapter.setNoteList(newNotes);
}
}
/*private class updateDisplayedNotes extends AsyncTask<Void, Integer, ArrayList<Notes>> {
public ArrayList<Notes> newNotes = new ArrayList<Notes>();
public updateDisplayedNotes(){
super();
Log.d(this.toString(), "Updating");
}
protected ArrayList<Notes> doInBackground(Void... parent) {
Log.d(this.toString(), "Background Task");
for (Notes note : mNotes) {
Log.d(this.toString(),note.toString());
if(note != null) {
Log.d(this.toString(), "Note Added");
newNotes.add(note);
}
}
return newNotes;
}
protected void onPostExecute(ArrayList<Notes> newNotes)
{
if(newNotes != null) {
mNotes.clear();
mNotes.addAll(newNotes);
mNotesListAdapter.setNoteList(mNotes);
}
}
}*/
void setLoadError(String error) {
setContentView(R.layout.load_error_view);
TextView messageText = (TextView)findViewById(R.id.message);
messageText.setText("Error loading ticket");
String errorString = error != null ? error : "";
TextView errorText = (TextView)findViewById(R.id.errorText);
errorText.setText(errorString);
finish();
}
}
viewticketorder.xml (where note_list is)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context=".ViewTicketOrderActivity"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="#string/loadingTicket"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white_color"
android:textSize="20dp"
android:textIsSelectable="true"
android:background="#drawable/title_transparent_bg"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:text="#string/ticketID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textTicketID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:text="#string/storeID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textStoreID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textStorePhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:paddingTop="2dp"
android:text="#string/category"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white_color"
android:focusable="true"
android:textIsSelectable="true"/>
</LinearLayout>
<ListView
android:id="#+id/note_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:divider="#drawable/ticket_item_divider"
android:dividerHeight="1dp"
tools:ignore="NestedWeights"
android:choiceMode="singleChoice"
android:clickable="true"
android:background="#drawable/title_transparent_bg">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/acceptButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:onClick="onClickAccept" />
<Button
android:id="#+id/addUpdateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:onClick="onClickAddUpdate" />
</LinearLayout>
</LinearLayout>
notelist_item.xml (inflator)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text_note_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFFFF"
android:orientation="vertical"
>
<TextView
android:id="#+id/text_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/text_item_color"
android:textSize="#dimen/big_text_item_size" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight=".70"
>
<TextView
android:id="#+id/text_note_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
</LinearLayout>
</LinearLayout>
I'm going to recommend you reorganize your code. Here are some general tips:
1) Keep your views like ListView in the Activity class. Don't try to inflate the view in your adapter class. So in your activity's onCreate() after setContentView() you should have something like:
ListView listView = (ListView) findViewById(R.id.listView);
2) Next you need to get the data that will be shown in the listview and store it in a list. I didn't see in your code where the data comes from, but let's just say it comes from a database. You should create something like an ArrayList and store the data that you want to show in the ListView in the ArrayList
3) Next you need to create an adapter and pass the list of data into the adapter.
4) Once this has been done the ListView now has an adapter that will supply data to it. If you've done everything correctly then the system will eventually call getView() automatically and your code inside that should run and render the view.
Not an exact solution, but hopefully this explanation will help you figure it out.

Why does adding buttons to grid view causes text-view to change?

My android activity workout view displays a grid view. Each object of grid view either displays the name of an exercise and two buttons or it displays a exercise set and two buttons.This is what it looks like when I don't add buttons to each set.
Once I enable buttons to each set by commenting out deleteBtn.setVisibility(View.GONE); the activity displays this. changing the 3rd to last object to display an exercise instead of a set. (Scrolled down)
getLocation(int i) determines if an grid object is going to be an Exercise or set. location[0] determines the exercise and location1 if == 0 refers to exercise and location1 > 0 refers to an exercise set.
private int[] getLocation(int i) {
db = new DatabaseHelper(context);
int temp[] = {-1, -1};
int count = -1;
for (int we = 0; we < WE_TABLE.size(); we++) {
for (int s = 0; s < db.getSetCountByWEID(WE_TABLE.get(we).getID()) + 1; s++) {
count++;
if (count == i) {
//Log.e("Test","WE: " + we+ " S: " + s + " For: " + i);
temp[0] = we;
temp[1] = s;
db.closeDB();
return temp;
}
}
}
db.closeDB();
return temp;
}
public View getView(int position, View convertView, ViewGroup parent) {
int temp_p = position;
TextView tv;
View view = convertView;
if (view == null) {
totalObj++;
Obj = totalObj;
int[] location = getLocation(Obj - 1);
db = new DatabaseHelper(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_workout_view_gridview, null);
tv = new TextView(context);
tv.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.FILL_PARENT, GridView.LayoutParams.WRAP_CONTENT));
Button deleteBtn = (Button) view.findViewById(R.id.delete_btn);
Button addBtn = (Button) view.findViewById(R.id.add_btn);
tv = (TextView) view.findViewById(R.id.list_item_string);
String Exercises = (Obj + " " + location[0] + "," + location[1]);
Log.e("Test", "Location: " + location[0] + " , " + location[1] + " Number " + Obj);
if (location[1] == -1) {
} else if (location[1] == 0) {
WorkoutExercise WE = WE_TABLE.get(location[0]);
Exercises = WE.getExerciseName();
// addBtn.setVisibility(View.GONE);
//deleteBtn.setVisibility(View.GONE);
} else {
S_TABLE = db.getSets(WE_TABLE.get(location[0]).getID() + "");
Exercises = S_TABLE.get(location[1] - 1).getWeight() + "lbs " + S_TABLE.get(location[1] - 1).getReps() + " Reps";
addBtn.setVisibility(View.GONE);
//deleteBtn.setVisibility(View.GONE);
}
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
tv.setText(Exercises);
db.closeDB();
}
return view;
}
And My XML for each row is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="0dp"
android:text="Dele" />
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="0dp"
android:text="Add" />
</RelativeLayout>
I lowered the height to match the text and It is working properly, thanks to talex

Categories