Removing Listview row on Button Click - android

I have a Listview that gets fed questions and their corresponding choices as such:
The following constructor gets all the necessary information to feed the Listview. All string values are in Arraylists.
public BaseQuestionAdapter(Activity a, ArrayList<String> b, ArrayList<String> c, ArrayList<String> d, ArrayList<String> e) {
activity = a;
this.questionTitleArray = b;
this.choicesArray = c;
this.questionIdArray = d;
this.userIdArray = e;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Each row will hold a single question title and a variable number of choices. Dynamically created buttons will instantiate the choices and on each question title position the buttons will start generating. Like so, the following is the getView method in the BaseAdapter:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
vi = inflater.inflate(R.layout.question_layout, null);
LinearLayout questionContainer = (LinearLayout) vi.findViewById(R.id.question_container);
LinearLayout choicesContainer = (LinearLayout) vi.findViewById(R.id.choices_container);
ViewGroup answersContainerParent = (ViewGroup) choicesContainer.getParent();
if (answersContainerParent != null)
answersContainerParent.removeView(choicesContainer);
JSONArray choicesJSONArray = new JSONArray(choicesArray);
try {
String bhb = choicesJSONArray.get(position).toString();
jsnArray = new JSONArray(bhb);
} catch (JSONException e) {
e.printStackTrace();
}
for (int answersArrayIterator = 0; answersArrayIterator < jsnArray.length(); answersArrayIterator++) {
try {
final Button choiceButton = new Button(activity);
choiceButton.setId(buttonId);
String questionId = questionIdArray.get(position).toString();
choiceButton.setTag(questionId);
choiceButton.setTag(position);
ViewGroup layout = (ViewGroup) choiceButton.getParent();
if (layout != null)
layout.removeView(choiceButton);
choiceButton.setText(jsnArray.get(answersArrayIterator).toString());
choiceButton.setTextSize(16);
choiceButton.setBackgroundResource(R.drawable.question_button_template_style);
choiceButton.setGravity(Gravity.CENTER);
choiceButton.setWidth(270);
choiceButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String choiceString = choiceButton.getText().toString();
Object questionId = choiceButton.getTag();
setDataToBeSent(userId, questionId, choiceString);
Integer index = (Integer) v.getTag();
System.out.println("SATURN ASCENDS: " + index);
choicesArray.remove(index);
notifyDataSetChanged();
new HttpAsyncTask2().execute();
return false;
}
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 10);
choiceButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
choiceButton.setLayoutParams(params);
buttonId++;
choicesContainer.addView(choiceButton);
} catch (JSONException e) {
e.printStackTrace();
}
}
TextView questionTitleET = (TextView) vi.findViewById(R.id.question_title);
String questionTitle = questionTitleArray.get(position).toString();
questionTitleET.setText(questionTitle);
ViewGroup questionTitleETParent = (ViewGroup) questionTitleET.getParent();
if (questionTitleETParent != null)
questionTitleETParent.removeView(questionTitleET);
questionContainer.addView(questionTitleET);
questionContainer.addView(choicesContainer);
return vi;
}
What I'm trying to achieve is to remove the parent Listview row whenever a button is LonClicked. I'm trying to achieve this by setting an OnLongClickListener on every button created. Like so:
choiceButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Integer index = (Integer) v.getTag();
System.out.println("SATURN ASCENDS: " + index);
choicesArray.remove(index);
notifyDataSetChanged();
return false;
}
});
Problem is that I don't know what to reference precisely in order for that to happen. Don't know whether its the choicesArray or any of the other resources I'm receiving. Currently when I long click on a button nothing happens. Any clue as to where I'm going wrong? Thank you.

As Luksprog said on the comment, you need to remove the items from the container which is referenced in the getCount(). However I would also like to offer an improvement. Instead of using four different lists of Strings, use an Object which holds each of those string.
Eg.
public class MyClass {
public String questionTitle;
public String choice;
public String questionId;
public String userId;
}
After you have this class you can use a single list, which contains your object. This way you won't be confused as to which list items should be removed in order for the list to change.

Related

BaseAdapter On Scroll Refresh Data in ListView

I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down
My BaseAdaper Code
class CoustomAdptr extends BaseAdapter{
String[] dates;
Integer[] inventory;
Integer totalrooms;
public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
this.dates = dates;
this.inventory = inventory;
this.totalrooms = totalrooms;
}
#Override
public int getCount() {
return dates.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
if(inventory[i] == 0){
editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
} else if(inventory[i] < totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.invetory));
editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
} else if(inventory[i] == totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
}
editText.setText(String.valueOf(inventory[i]));
textView.setText(dates[i]);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String name = editText.getText().toString();
//String name1 = dates[i];
//String name2 = getArguments().getString("room_id");
updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
//updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
updateButton.setText("Updated");
updateButton.setEnabled(false);
Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is How Im Passing Data to My Adapter
JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
dates[i] = jsonObject.getString("date");
inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);
Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly
After clicking a button, save it's state in a boolean array or somewhere else. And inside getView method, check if this button was previously clicked or not then setup your view accordingly.
It would be better if you create a model class for rows.

ArrayAdapter strange behaviour with id when items's height exceed Listview height

I'm facing a strange behaviour using an ArrayAdapter.
When the number of listview item exceed the height of the listView (say after item 8), the next item get the id 0 instead the id 9.
In my opinion this type of issue was explained here with the convertView, but i use it in the same way (i think).
The following code is my ArrayAdapter.
public class StepsAdapter extends ArrayAdapter<String> {
Context context;
List<String> steps;
public StepsAdapter(Context context, int resourceId, List<String> steps) {
super(context, resourceId, steps);
this.context = context;
}
private class ViewHolder {
EditText stepValue;
ImageView removeStep;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final String step = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_step, null);
holder = new ViewHolder();
holder.stepValue = (EditText) convertView.findViewById(R.id.stepEdit);
holder.removeStep = (ImageView) convertView.findViewById(R.id.removeStep);
holder.stepValue.setText(step);
holder.removeStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"* Remove id step " + position, Toast.LENGTH_LONG).show();
steps.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
Then my main activity where i get existing data and put it in my listView, the add button and the save button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_game);
mContext = getApplicationContext();
steps = new ArrayList<String>();
stepsAdapter = new StepsAdapter(mContext,R.layout.row_step,steps);
Gson gson = new GsonBuilder().create();
game = gson.fromJson(gameJson, Games.class);
/*
* Settings values
*/
gameNameValue.setText(game.getName());
gameBackgroundPreview.setBackgroundColor(game.getColor());
colorSelected = game.getColor();
for(int i = 0; i < game.getSteps().size() ; i++){
//steps.add(game.getSteps().get(i).toString());
//notifyDataSetChanged();
stepsAdapter.add(game.getSteps().get(i).toString());
}
final ListView listSteps = (ListView) findViewById(R.id.listViewSteps);
listSteps.setAdapter(stepsAdapter);
gameNameValue.setText(gameName);
addSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stepsId = steps.size();
Toast.makeText(getApplicationContext(), "addSteps : " + stepsId, Toast.LENGTH_LONG).show();
stepsAdapter.insert("newstep", stepsId);
}
});
buttonSaveGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String valueEditGameName = gameNameValue.getText().toString();
int valueColorBackaground = colorSelected;
String picture = "testPic";
for(int i=0; i < listSteps.getChildCount(); i++) {
LinearLayout rowLayout = (LinearLayout) listSteps.getChildAt(i);
//Log.e(TAG, ">> :) layout >>" + listSteps.getChildAt(i).getClass().getName());
EditText editRow = (EditText) rowLayout.getChildAt(0);
stepsValues.add(editRow.getText().toString());
//Log.e(TAG, ">> :) inside layout >>" + editRow.getText().toString());
}
if(valueEditGameName.trim().length() > 0 && picture.trim().length() >0 ){
Games game = new Games(valueEditGameName,valueColorBackaground,picture,stepsValues);
String goToSave = game.createJson();
Log.e(TAG, ">>Saved>>" + goToSave);
final CkdFile file = new CkdFile();
String saved = file.writeToSDFile(game.getName(), goToSave);
Toast.makeText(mContext, saved, Toast.LENGTH_LONG).show();
Intent backToMain = new Intent(mContext,MainActivity.class);
startActivity(backToMain);
} else {
Toast.makeText(mContext, "Fill all texts", Toast.LENGTH_LONG).show();
}
}
});
}
I try to add items in 2 different ways :
add item through : List steps
add item through : StepsAdapter stepsAdapter
Both give me same behaviour.
If someone has a clue to help understanding what i'm doing wrong with my implementation of ListView/ArrayAdapter.
Thanks in advance !
EDIT 1 :
After pushing some logs everywere, it understand the strange behaviour :
My adapter have only 6 slots (the limit came from the size of the listview in layout), and when my arraylist have more than 6 items, the getView select items only between 0 and 5.
I'm searching now a way to get the position in ArrayList and not the position in arrayadapter.
I faced same issue recently. Add following overrides to Adapter:
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
I found a simple xml "trick" to avoid this behaviour : i set a biger height to listView.
<ListView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:layout_gravity="center_horizontal"
android:id="#+id/listViewSteps"
android:layout_margin="10dp">
</ListView>
It's not really resolve but a take it ...

ListItemClick not working in ListFragment with ParseQueryAdapter

My code involves showing data retrieved from a parse backend using a parsequeryadapter. Based on the text retrieved, my code displays some images in the listview which are basically buttons with custom backgrounds and some text.
The problem is that the onListItemClick method does not seem to be called at all. (It might work if it is called)
Construct of code is like so:
NavActivity contains a fragment which contains a child listfragment defined in the XML.
This is the getItemView method in my ParseQueryAdapter
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(context, R.layout.post_item, null);
}
super.getItemView(object, v, parent);
//find the elements here and set the value from the ParseObject returned
TextView1 = (TextView) v.findViewById(R.id.NumberTxtView);
Holder = (LinearLayout) v.findViewById(R.id.feloniesList);
if (object != null) {
Holder.removeAllViewsInLayout();
TextView1.setText(object.getString("comment"));
JSONArray jsonArray = object.getJSONArray("incident");
for (int i = 0; i < jsonArray.length(); i++) {
//Create a new button
Button button = new Button(getContext());
String btnText = null;
int resId = 0;
try {
//Get the string from the JSON Array
String item = jsonArray.getString(i);
button.setFocusable(false);
button.setText(item);
} catch (JSONException e) {
e.printStackTrace();
}
Holder.addView(button, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
return v;
}
ListItemClick method
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
feedObject = feedAdapter.getItem(position);
mListener.onListItemClicked(feedObject.getObjectId());
}
I read here that making other components as non focusable, will solve the problem, but it is not helping. Any help would be appreciated
I found the answer, it seems focusable is not only true for buttons / checkboxes, but also elements like HorizontalScrollViewer. I had my linearlayout in which I was adding the buttons, enclosed in a horizontalscrollviewer. After I removed said element, click functions are working fine.

Get tags from Radiobuttons in ListView Android

I have a custom listView built with ArrayAdapter. In ListView each item contents a TextView and a RadioGroup (with 4 RadioButton). I can choose one RadioButton to be selected for each list item. On the bottom of ListView i have a footer with button. What i want is to get all data when i click on button like this:
name1 - 1
name2 - 3
name3 - 2
name4 - 3
...
First column - Text from TextView
Second column - Tag of selected RadioButton
Atcivity with view:
public class MarksAdd extends ListActivity {
ArrayList<String> itemlist = new ArrayList<String>();
private Context context = null;
private ListView listView;
private Button BtnDone;
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.marks_add);
Intent intent = getIntent();
int day = intent.getIntExtra("day", 0);
int month = intent.getIntExtra("month", 0);
int year = intent.getIntExtra("year", 0);
String dayStr = String.valueOf(day);
String monthStr = String.valueOf(month);
String yearStr = String.valueOf(year);
if (day != 0) {
if(dayStr.length()==1){
dayStr = "0"+dayStr;
}
if(monthStr.length()==1){
monthStr = "0"+monthStr;
}
yearStr = yearStr.substring(2);
String date = dayStr+"."+monthStr+"."+yearStr;
Toast.makeText(this, date, Toast.LENGTH_SHORT).show();
}
final ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
listView = getListView();
LayoutInflater inflater = getLayoutInflater();
listView.addFooterView(inflater.inflate(R.layout.list_footer, null), null, false);
setListAdapter(adapter);
BtnDone = (Button) findViewById(R.id.markListBtn);
BtnDone.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//get Values ?????
}
});
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
dbHelper sql = new dbHelper(this);
SQLiteDatabase db = sql.getWritableDatabase();
Cursor cursor = db.query(
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("group", ""), new String[]{
"Id", "Name"},
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
"Name ASC" // The sort order
);
while (cursor.moveToNext()) {
// GET COLUMN INDICES + VALUES OF THOSE COLUMNS
int id = cursor.getInt(cursor.getColumnIndex("Id"));
String name = cursor.getString(cursor
.getColumnIndex("Name"));
list.add(get(name));
}
cursor.close();
// Initially select one of the items
return list;
}
private Model get(String question) {
return new Model(question);
}
}
ArrayAdapter:
public class InteractiveArrayAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.simple_list_item1_marks, list);
this.context = context;
this.list = list;
}
class ViewHolder {
TextView t = null;
RadioGroup group;
ViewHolder(View v) {
t = (TextView) v.findViewById(R.id.personName);
group = (RadioGroup) v.findViewById(R.id.myRgroup);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
LayoutInflater inflater = context.getLayoutInflater();
v = inflater.inflate(R.layout.simple_list_item1_marks, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
final View finalV = v;
holder.group
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
Model element = list.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.rb1:
element.current = Model.ANSWER_ONE_SELECTED;
break;
case R.id.rb2:
element.current = Model.ANSWER_TWO_SELECTED;
break;
case R.id.rb3:
element.current = Model.ANSWER_THREE_SELECTED;
break;
case R.id.rb4:
element.current = Model.ANSWER_FOUR_SELECTED;
break;
default:
element.current = Model.NONE; // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) v.getTag();
}
holder.group.setTag(position); // I passed the current position as a tag
holder.t.setText(list.get(position).question); // Set the question body
if (list.get(position).current != Model.NONE) {
RadioButton r = (RadioButton) holder.group.getChildAt(list
.get(position).current);
r.setChecked(true);
} else {
holder.group.clearCheck(); // This is required because although the Model could have the current
// position to NONE you could be dealing with a previous row where
// the user already picked an answer.
}
return v;
}
}
Model:
public class Model {
String question; // hold the question
int current = NONE; // hold the answer picked by the user, initial is NONE(see below)
public static final int NONE = 1000; // No answer selected
public static final int ANSWER_ONE_SELECTED = 0; // first answer selected
public static final int ANSWER_TWO_SELECTED = 1; // second answer selected
public static final int ANSWER_THREE_SELECTED = 2; // third answer selected
public static final int ANSWER_FOUR_SELECTED = 3; // forth answer selected
public Model(String question) {
this.question = question;
}
}
I was doing this according to that tutorial with some changes. Actualy i'm realy newbie in development, so im asking you to help me. Sorry if my question is not correct, my english is not realy good.
Well be very thankfull for any help here.
The first thought would be to iterate over the ListView and get the checked button in each row. This won't actually work because ListView does not contain all of its children all of the time.
Instead, you should store the checked item when the user actually makes a selection. Then when you press the button, you already have all the data stored and don't have to iterate over the ListView. Also, having the current selections saved this way will be useful if you scroll back up the list because you can set the current checked radio button for previous items in getView().
Let's assume the row layout has this in it:
<RadioGroup android:id="#+id/radio_group" ... >
<RadioButton android:id="#+id/radio_button_1" ... />
<RadioButton android:id="#+id/radio_button_2" ... />
<RadioButton android:id="#+id/radio_button_3" ... />
<RadioButton android:id="#+id/radio_button_4" ... />
</RadioGroup>
In your adapter's getView(), give the RadioGroup an OnCheckedChangedListener defined in the adapter itself (so you have one OnCheckedChangedListener instead of one per row). Tag the RadioGroup with the position of the list item so that you can differentiate it in the callback.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
Model model = getItem(position);
int checkedId = ... //figure out checked id from model
viewHolder.group.check(checkedId);
viewHolder.group.setTag(position);
viewHolder.group.setOnCheckedChangedListener(checkChangedListener);
...
}
private OnCheckedChangedListener checkChangedListener = new OnCheckedChangedListener() {
#Override
public void onCheckChanged(RadioGroup group, int checkId) {
Object tag = group.getTag();
if (!(tag instanceof Integer)) {
// you have a bug. Fix it!
return;
}
int position = (Integer) tag;
Model model = getItem(position);
switch(checkedId) {
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_ONE_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_TWO_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_THREE_SELECTED); break;
case R.id.radio_button_1:
model.setCurrent(Model.ANSWER_FOUR_SELECTED); break;
}
}
};
Now you just need to get your list of Models from the adapter.

Android BaseAdapter : position not really the position?

When my list view using a BaseAdapter goes off the screen, each row no longer maintains a consecutive position. I don't know how else to explain it other than this.
If my BA/LV shows 4 items on the screen, and I add a view that displays a TextView of each row, it shows 0,1,2,3 for the row numbers (which is correct). But as soon as I scroll the list down to the bottom 4 items (items 5-8) it then shows those as 4,5,0,1?? Why?
EDIT:
I did discover that if I change
rv = (RowView) convertView;
to
rv = new RowView(mContext,(cursor.getString(2)),
(cursor.getString(5)),
cursor.getString(cursor.getColumnIndex(DBHelper.KEY_IMAGEFILENAME)),
cursor.getString(cursor.getColumnIndex(DBHelper.KEY_CITY)),position);
it works, but then it is not re-using the code. So, I guess I am on the right track. I did try some convenience methods, but that did not help me too much because I needed to set those values before the Constructor fired off. Do I need to create a new method and fire that at the end? Such as addRow method? This also causes it to scroll VERY Slow.
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
//setContentView(R.layout.findlist);
//getListView().setEmptyView(findViewById(R.id.empty));
mDbHelper = new DBHelper(this);
mDbHelper.open();
cursor = mDbHelper.fetchAllLocations();
startManagingCursor(cursor);
mAdapter = new myListAdapter(this);
setListAdapter(mAdapter);
}
public class myListAdapter extends BaseAdapter {
public String testing;
public myListAdapter(Context c) {
mContext = c;
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return cursor.getCount();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
cursor.moveToPosition(position);
RowView rv;
if (convertView == null) {
rv = new RowView(mContext,(cursor.getString(2)),
(cursor.getString(5)),
cursor.getString(cursor.getColumnIndex(DBHelper.KEY_IMAGEFILENAME)),
cursor.getString(cursor.getColumnIndex(DBHelper.KEY_CITY)),position);
} else {
rv = (RowView) convertView;
try {
// I KNOW THIS SECTION IS NOT RIGHT, BUT I HAVE BEEN MESSING IN HERE
rv.setAddress(cursor.getString(2));
rv.setCity(cursor.getString(5));
rv.setFocusable(true);
rv.setClickable(true); }
catch (Exception e) {
rv = (RowView) convertView;
rv.setAddress(cursor.getString(2));
rv.setCity(cursor.getString(5));
rv.setFocusable(true);
rv.setClickable(true);
Toast mToast;
mToast = Toast.makeText(FindList.this, "Error :" + e.toString() ,
Toast.LENGTH_LONG);
mToast.show();
}
}
return rv;
}
public void addItems() {
//String[] from = new String[] { DBHelper.KEY_BUSINESSNAME, DBHelper.KEY_ADDRESS, DBHelper.KEY_CITY, DBHelper.KEY_GPSLONG, DBHelper.KEY_GPSLAT, DBHelper.KEY_IMAGEFILENAME + ""};
// create array of values of widgits
//to = new int[] { R.id.businessname, R.id.address, R.id.city, R.id.gpslong, R.id.gpslat, R.id.preview};
// Now create an array adapter and set it to display using our row from notes_row.xml
}
}
private class RowView extends LinearLayout {
private TextView mAddress;
private TextView mCity;
public ImageView mArrow;
public ImageView mPicture;
public String mPathName;
public String mDateTime;
public RowView(Context context, String title, String words, String pathName, String city, int position) {
super(context);
this.setOrientation(HORIZONTAL);
this.setVerticalGravity(16); //CENTER_VERTICAL
// Here we build the child views in code. They could also have
// been specified in an XML file.
//DISPLAY DELETE BUTTON
Button mButton = new Button(context);
mButton.setFocusable(false);
mButton.setId(position);
mButton.setBackgroundResource(R.drawable.delete3);
addView(mButton, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TextView mTitle;
mTitle = new TextView(context);
mTitle.setText(Integer.toString(position));
addView(mTitle, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.setOrientation(HORIZONTAL);
try {
Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(DBHelper.KEY_IMAGEFILENAME))),100, 100, true);
mPicture = new ImageView(context);
mPicture.setImageBitmap(bm);
} catch (Exception e) {
mPicture = new ImageView(context);
mPicture.setImageResource(R.drawable.noimage);
}
addView(mPicture, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mArrow = new ImageView(context);
mArrow.setBackgroundResource(R.drawable.arrowleft3);
addView(mArrow, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
currentPosition = position;
Button button = (Button)findViewById(position);
button.setOnClickListener(mCorkyListener);
}
When using the convertView, you are given a view which has been previously used but which is not displayed anymore. You should take care of resetting ALL its attributes with the value of the current item. Otherwise, all the values you have set in the RowView constructor will be kept with the value you gave to this view the first time you created it.
To better understand ListViews, you have to understand that it only uses a limited set of RowViews, just the number that is enough to fill the display and a few more that will be filled with your data just before having to display them.

Categories

Resources