Searching and deleting rows in Custom ListView - java

I'm trying to create a ListView for a Friends list. It has a search functiton in which tthe user can search for a particular freind and then delete them as a friend, message them and so forth.
However, I'm having trouble removing them. I don't think I understand the positioning, or finding out the correct position on where the users freind is in the list.
I want to make sure that in all cases, the user is removed from the correct position. For instance, if the user uses the search function and only one user is returned. Then I don't want the user to be removed at position 0 (one user), I want it to be removed at the correct position so that when the user goes back to the full list. Position 0 in the list isn't accidentaly removed.
Could someone review the code? and show a slight indication as to where I am going wrong with this?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = getResources();
searchField = (EditText) findViewById(R.id.EditText01);
lv = (ListView) findViewById(android.R.id.list);
//button = (Button)findViewById(R.id.btnFriendList);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//button.setFocusable(false);
list = new ArrayList<Friend>();
nameBlock = res.getStringArray(R.array.names);
descBlock = res.getStringArray(R.array.descriptions);
names = new ArrayList<String>();
for(int i = 0; i < nameBlock.length; i++) {
names.add((String)nameBlock[i]);
}
descr = new ArrayList<String>();
for(int i = 0; i < descBlock.length; i++) {
descr.add((String)descBlock[i]);
}
images = new ArrayList<Integer>();
for(int i = 0; i < imageBlock.length; i++) {
images.add((Integer)imageBlock[i]);
}
//imageBlock = res.getIntArray(R.array.images);
int size = nameBlock.length;
for(int i = 0 ; i < size; i++) {
Log.d("FREINDADD", "Freind Added" + i);
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
//friendList2.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
}
Log.i("Application", "Application started succesfully...");
adapter = new CustomAdapter(this);
setListAdapter(adapter);
Log.i("VIRTU", "Count" + adapter.getCount());
//adapter.getCount();
searchField.addTextChangedListener(new TextWatcher()
{
#Override public void afterTextChanged(Editable s) {}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override public void onTextChanged(CharSequence s, int start, int before, int count)
{
list.clear();
textlength = searchField.getText().length();
for (int i = 0; i < names.size(); i++)
{
if (textlength <= names.get(i).length())
{
if(names.get(i).toLowerCase().contains(searchField.getText().toString().toLowerCase().trim())) {
Log.i("VirtuFriendList", "List recyling in process... ");
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
}
}
}
AppendList(list);
}
});
}
public void AppendList(ArrayList<Friend> list) {
setListAdapter(new CustomAdapter(this));
}
class CustomAdapter extends BaseAdapter {
private Context context;
public CustomAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return list.size();
}
class ViewHolder {
TextView userName;
TextView userDesc;
ImageView userImage;
Button userButton;
ViewHolder(View view) {
userImage = (ImageView)view.findViewById(R.id.imageview);
userName = (TextView)view.findViewById(R.id.title);
userDesc = (TextView)view.findViewById(R.id.mutualTitle);
userButton = (Button)view.findViewById(R.id.btn);
}
}
ViewHolder holder;
View row;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if(row == null)
{
// If it is visible to the user, deploy the row(s) - allocated in local memory
LayoutInflater inflater = (LayoutInflater)context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
Log.d("VIRTU", "Row deployed...");
}
else
{
// Recycle the row if it is not visible to to the user - store in local memory
holder = (ViewHolder)row.getTag();
Log.d("VIRTU", "Row recycled...");
}
Friend temp = list.get(position);
// Set the resources for each component in the list
holder.userImage.setImageResource(temp.getImage());
holder.userName.setText(temp.getName());
holder.userDesc.setText(temp.getDesc());
((Button)row.findViewById(R.id.btn)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu pop = new PopupMenu(getApplicationContext(), v);
MenuInflater inflater = pop.getMenuInflater();
inflater.inflate(R.menu.firned_popup_action,pop.getMenu());
pop.show();
pop.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int choice = item.getItemId();
switch(choice) {
case R.id.message:
break;
case R.id.unfollow:
break;
case R.id.unfriend:
int position = (Integer)row.getTag();
list.remove(position);
names.remove(position);
images.remove(position);
descr.remove(position);
adapter = new CustomAdapter(context);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
case R.id.cancel:
}
return false;
}
});
}
});
return row;
}
}
}

I think as your structure stands, you will continue to have this problem. My suggestion would be to assign a FriendID (or something similar) to each friend, and when you are building your list, instead of just passing userImage, userName, userDesc and userButton, pass along friendID as well.
For example, I have five friends, and here is their information:
userImage userName userDesc userButton friendID
x Jordyn x x 0
x Sam x x 1
x Connor x x 2
x Paul x x 3
x Raphael x x 4
But my search for (pretending you can search by one letter) those with 'o' in their name returns,
userImage userName userDesc userButton friendID
x Jordyn x x 0
x Connor x x 2
That way, when you delete the 1th row, it actually removes friendID = 2 from your friend list instead of the 1th row from your original friend list, which would've been Sam, which was not your intention.
Hope that helps!
EDIT:
1: add a hidden TextView to your rows called FriendID in your layout file (let me know if you need help with that).
Now, ViewHolder will look like this:
class ViewHolder {
TextView userName;
TextView userDesc;
ImageView userImage;
Button userButton;
TextView friendID;
ViewHolder(View view) {
userImage = (ImageView)view.findViewById(R.id.imageview);
userName = (TextView)view.findViewById(R.id.title);
userDesc = (TextView)view.findViewById(R.id.mutualTitle);
userButton = (Button)view.findViewById(R.id.btn);
friendID = (TextView)view.findViewById(R.id.friendID);
}
}
2: add an arraylist for the friendIDs:
...
descr = new ArrayList<String>();
for(int i = 0; i < descBlock.length; i++) {
descr.add((String)descBlock[i]);
}
images = new ArrayList<Integer>();
for(int i = 0; i < imageBlock.length; i++) {
images.add((Integer)imageBlock[i]);
}
friendIDs = new ArrayList<Integer>();
for(int i = 0; i < friendIDsBlock.length; i++) {
images.add((Integer)friendIdsBlock[i]);
}
...
3: searchField.addTextChangedListener will now look like:
int size = nameBlock.length;
for(int i = 0 ; i < size; i++) {
Log.d("FREINDADD", "Freind Added" + i);
list.add(new Friend(i, names.get(i), descr.get(i), images.get(i)));
//friendList2.add(new Friend(i, names.get(i), descr.get(i), images.get(i), friendIds.get(i)));
}
Log.i("Application", "Application started succesfully...");
4: Now, when you unfriend someone, make sure to get the FriendID at the selected row as opposed to the row index. Then, remove the friend from the search list with the given FriendID as well as the friend from the general friend list with the given FriendID.
You'll have to forgive me, I don't have an IDE in front of me at the moment but I think that about covers it!

Related

How to select a single Edit text box from a gridview with base adapter?

I am using a GridView 6*6 and it consists of EditText for a total of 36 EditText.
I am passing a 2D array from the base class and the values are filled in the correct position. The boxes which are not filled are made invisible.
Now I need to find the first visible EditText box and make focus automatically, and after certain event I need to change the focus to next visible EditText?
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder;
viewHolder = new ViewHolder();
String comonchar = String.valueOf(hint_lilst.get(0));
if (convertView == null) {
convertView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.crossword_play_screen_items, null);
viewHolder.tv1 = (EditText) convertView.findViewById(R.id.CW_oneone);
viewHolder.gridView = convertView.findViewById(R.id.Cw_gridviewplay);
convertView.setTag(viewHolder);
viewHolder.tv1.setInputType(InputType.TYPE_NULL);
Log.d("macantiosh","child at "+viewGroup.getChildAt(21));
} else {
viewHolder = (ViewHolder)convertView.getTag();
// arrayList.get(position);
viewHolder.tv1.setText(arrayList.get(position));
}
// if (Objects.equals(arrayList.get(position), "0")) {
// viewHolder.tv1.setVisibility(View.INVISIBLE);
// viewHolder.tv1.setClickable(false);
// }
//
if (Objects.equals(arrayList.get(position), comonchar)) {
viewHolder.tv1.setText(arrayList.get(position));
viewHolder.tv1.setBackgroundResource(R.drawable.puzzlesucess);
viewHolder.tv1.setTextColor(Color.parseColor("#FFFFFF"));
}else if (Objects.equals(arrayList.get(position), "0")) {
viewHolder.tv1.setVisibility(View.INVISIBLE);
viewHolder.tv1.setClickable(false);
} else {
// for(int m = 0; m< filled_pos_llist.size();m++){
// if(Objects.equals(arrayList.get(position),focus_pos_wrds.get(filled_pos_llist.get(0)))){
viewHolder.tv1.setText("");
// viewHolder.tv1.setBackgroundResource(R.drawable.puzzlesucess);
//viewHolder.tv1.setTextColor(Color.parseColor("#FFFFFF"));
// viewHolder.tv1.requestFocus();
Log.d("popi", "list words" + arrayList.get(position));
// }
// }
}
if (viewHolder.tv1.getVisibility() ==View.VISIBLE){
filled_pos_llist.add(position);
}
Log.d("adgads","words in list pos "+viewGroup.getChildCount());
//GridView mGridView =viewGroup;
// final int size = viewGroup.getChildCount();
// Log.d("timber","child count in grid view "+size);
// for(int i = 0; i < size; i++) {
// ViewGroup gridChild = (ViewGroup) viewGroup.getChildAt(i);
// int childSize = gridChild.getChildCount();
// for(int k = 0; k < childSize; k++) {
// if( gridChild.getChildAt(k) instanceof EditText ) {
// gridChild.getChildAt(k).setVisibility(View.GONE);
// Log.d("khaggj","got pos list visible positionss ");
// }
// }
// }
// for (Map.Entry<Integer, String> entry : focus_pos_wrds.entrySet()) {
//
// viewHolder.tv1.requestFocus(1);
// viewHolder.tv1.setBackgroundResource(R.drawable.puzzlesucess);
// viewHolder.tv1.setTextColor(Color.parseColor("#FFFFFF"));
//
// Log.d("khaggj","got pos list "+entry.getKey());
// break;
//
//
// }
final ViewHolder finalViewHolder = viewHolder;
viewHolder.tv1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Log.d("djhgfj", "on focus change lisiner " + position);
finalViewHolder.id = position;
current = (EditText) view;
current.setBackgroundResource(R.drawable.focusedtxt);
click_pos = position;
Log.d("djhgfj", "on focus change lisiner " + finalViewHolder.id);
}
}
});
keyboard.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#SuppressLint("SetTextI18n")
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("clickk", "clicked item " + keyboard_words.get(i) + " n " );
EditText current_edittext = getCurrentEditText();
if (current_edittext != null) {
if (current_edittext.getText().length() == 0) {
current_edittext.setText(current.getText().toString() + keyboard_words.get(i));
}
if (current_edittext.getText().toString().equals(arrayList.get(click_pos))) {
Log.d("txtchange", " filled answer crrt ");
current_edittext.setBackgroundResource(R.drawable.puzzlesucess);
current_edittext.setTextColor(Color.parseColor("#FFFFFF"));
// if(Objects.equals(arrayList.get(position),focus_pos_wrds.get(filled_pos_llist.get(0)))){
// viewHolder.tv1.setText("");
// viewHolder.tv1.setBackgroundResource(R.drawable.puzzlesucess);
// viewHolder.tv1.setTextColor(Color.parseColor("#FFFFFF"));
// viewHolder.tv1.requestFocus();
// Log.d("popi", "list words" + arrayList.get(position));
// current = viewHolder.tv1;
// current.setBackgroundResource(R.drawable.focusedtxt);
// click_pos = posiztion;
// }
} else {
Animation shake = AnimationUtils.loadAnimation(context, R.anim.shake);
current_edittext.startAnimation(shake);
current_edittext.setText("");
}
}
Log.d("pendrive", "adapter clicked class " + keyboard_words.get(i) + " current " + click_pos);
}
});
// for (int i = 0; i < filled_pos_llist.size(); i++) {
//
// ViewGroup gridChild = (ViewGroup) viewGroup.getChildAt(i);
//
// if (gridChild.getChildAt(i) instanceof EditText && ((EditText) gridChild.getChildAt(i)).getText().length()>0){
//
// Log.d("thanaser", "visible individual positions ");
//
// }
//
// }
final EditText current_edittext = getCurrentEditText();
if (current_edittext!=null){
current_edittext.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (current_edittext.getText().toString().length()>0){
Log.d("hdjhiu","text changed ");
}
}
});
}
return convertView;
}
I would do it by going throw all GridLayout child Views:
public void setFocusOnEditText() {
GridLayout layout = findViewById(R.id.layout);
layout.getChildCount();
for (int i = 0; i < layout.getChildCount(); i++) {
View view = layout.getChildAt(i);
if (view instanceof EditText && view.getVisibility() == View.VISIBLE) {
view.requestFocus();
}
}
}
If you are using your custom BaseAdapter and if I'm not mistaken you could use:
if (convertView instanceof GridLayout) {
View editText = ((GridLayout) convertView).getChildAt(position);
if (editText instanceof EditText && editText.getVisibility() == View.VISIBLE) {
editText.requestFocus();
}
}

Android/Java - Defining variables at different "places"

Okay this title might sound strange but I don't really know how to explain it.
What I'm trying to do: query a database, use the #of results to define a string array length and use the results to fill a view. All of this works, theoretically, but when I try to move my code from onCreate "up", I get syntax errors I can't fix. It might make more sense to just read my comments in the code below!
public class A_customlist extends ListActivity {
Integer runme = 5;
int[] imgb = new int[runme];
{
for (int number = 0; number < imgb.length; number++) {
imgb[number] = R.drawable.spatz_adult;
}
;
};
SQLiteDatabase TPBDB;
String[] myString2 = new String[5];
// what I want to do: new String[count]
// basically do all the TPBDB stuff (see below) first, so I can access the
// count variable
// defining myString in onCreate makes it inaccessible in onListItemClick
String[] myString = new String[5];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// "TPBDB stuff"
TPBDB = openOrCreateDatabase("TPBDB1", MODE_PRIVATE, null);
Cursor cur = TPBDB.rawQuery("SELECT * from Vogel", null);
String mycur = cur.toString();
int count = cur.getCount();
cur.moveToFirst();
// String[] myString = new String[count+1]; // 4 entries, runme = 5!
for (Integer j = 0; j < count; j++) {
myString[j] = Long.toString(cur.getLong(cur.getColumnIndex("uid")));
myString2[j] = cur.getString(cur.getColumnIndex("datum"));
cur.moveToNext();
}
;
TPBDB.close();
// --- "TPBDB stuff"
getListView().setDividerHeight(2);
getListView().setAdapter(
new BindDataAdapter(this, imgb, myString, myString2));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(myString[position] + " is clicked.");
builder.setPositiveButton("OK", null);
builder.show();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.activity_list, menu);
// return true;
// }
}
Like this you can access your array in the onClickListener, in case thats what you wanted to achieve
String[] myString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// "TPBDB stuff"
TPBDB = openOrCreateDatabase("TPBDB1", MODE_PRIVATE, null);
Cursor cur = TPBDB.rawQuery("SELECT * from Vogel", null);
String mycur = cur.toString();
int count = cur.getCount();
myString = new String[count]; // init array here
...
}
you just have to declare a field "above" oncreate, you dont have to initialize it at the same time.

Get the ID of checkbox from custom adapter in android?

I have a Custom ArrayList as follows.
public class sendivitesadapter extends ArrayAdapter<Item>{
private Context context;
private ArrayList<Item> items;
private qrusers qrusers;
private LayoutInflater vi;
public sendivitesadapter(Context context,ArrayList<Item> items) {
super(context, 0,items);
this.context= context;
this.qrusers =(qrusers) context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
#Override
public Item getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
sendItem ei = (sendItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
final TextView title = (TextView)v.findViewById(R.id.contactname);
final TextView subtitle = (TextView)v.findViewById(R.id.companyname);
final CheckBox checkBox=(CheckBox)v.findViewById(R.id.checboxlist);
if (title != null)
title.setText(ei.contactname);
if(subtitle != null)
subtitle.setText(ei.companyname);
}
}
return v;
}
and it looks like following image.
My java file is as follows.
#Override
protected void onPostExecute(String result) {
JSONArray jarray;
try {
jarray= new JSONArray(result);
name= new String[jarray.length()];
company=new String[jarray.length()];
for (int i=0;i<jarray.length();i++){
JSONObject jobj = jarray.getJSONObject(i);
name[i]= jobj.getString("Name");
company[i]=jobj.getString("Company");
items.add(new sendItem(name[i], company[i], checkBox));
adapter = new sendivitesadapter(qrusers.this,items);
listView.setAdapter(adapter);
Now I get the names from webservice which I am diplaying it in a listview as shown above.
With every name I get a USerID. So my question is whenever the user checks the checkbox in any sequence and click on add user I want the UserID of the checked checkboxes in array. How can I achieve this?
Sounds like it's a good candidate for View.setTag(). You could set the tag on each CheckBox to the id of the user [when you create it, or assign the Name and Company values]. Then in an OnClick or OnChecked type event, you can call view.getTag() to retrieve the id of the currently checked box.
You need to use OnCheckedChangeListener to get the cheched CheckBox ID. This SO will help you- How to handle onCheckedChangeListener for a RadioGroup in a custom ListView adapter . You need to modify the onCheckedChangeListener according to your need.
In your adapter set the position in check box like
checkBox.setTag(position);
And as i think you have to add checked user on click of Add User button. So on click of that button write following code.
public void onClick(View v) {
// TODO Auto-generated method stub
String categoryArray = "";
String[] categoryId;
if(v == AddUser){
int count = 0;
for(int i = 0; i < listViewRightSlideMenu.getChildCount(); i ++){
RelativeLayout relativeLayout = (RelativeLayout)listViewRightSlideMenu.getChildAt(i);
CheckBox ch = (CheckBox) relativeLayout.findViewById(R.id.checkBoxCategory); //use same id of check box which you used in adapter
if(ch.isChecked()){
count++;
categoryArray = categoryArray+ch.getTag()+",";
}
}
if(categoryArray.length() > 0) {
categoryArray = categoryArray.substring(0, categoryArray.length() - 1);
String[] array = categoryArray.split(",");
categoryId = new String[array.length];
for(int i = 0; i< array.length; i++) {
categoryId[i] = listCategory.get(Integer.valueOf(array[i])).getId();
}
for(int i = 0; i < categoryId.length; i++){
String a = categoryId[i];
System.out.println("category id is: "+a);
}
System.out.println("array position: "+categoryId);
}
}

First data in the listview should be checked by default

I have a requirement that when I am entering zip code and pressing the enter key on the emulator/tablet i am getting list of operator names in the ListView. Inside Listview I am using checkedtextview to populate the data using my custom array adapter.
The listview should be checked at a time one operator name only. Whenever the data is populated to the listview the first operator name should be checked by default.
Is there any way to find out the solution.
I am using the custom array adapter like this
private class OperatorListAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> selectOperatorStatusMap = new HashMap<Integer, Boolean>();
public OperatorListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
selectOperatorStatusMap.put(0, true);
for (int i = 1; i < objects.size(); i++) {
selectOperatorStatusMap.put(i, false);
}
}
public void toggleChecked(int position) {
if (selectOperatorStatusMap.get(position)) {
selectOperatorStatusMap.put(position, false);
} else {
selectOperatorStatusMap.put(position, true);
}
notifyDataSetChanged();
}
public void unChecked(int position) {
for (int i = 0; i < selectOperatorStatusMap.size(); i++) {
if(i!=position){
checkedTextView.setChecked(false);
checkedTextView.setCheckMarkDrawable(R.drawable.uncheck);
}
}
}
public List<Integer> getCheckedItemPositions() {
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for (int i = 0; i < selectOperatorStatusMap.size(); i++) {
if (selectOperatorStatusMap.get(i)) {
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems() {
List<String> checkedItems = new ArrayList<String>();
for (int i = 0; i < selectOperatorStatusMap.size(); i++) {
if (selectOperatorStatusMap.get(i)) {
(checkedItems).add(operatorList.get(i));
}
}
return checkedItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getActivity().getLayoutInflater();
row = inflater.inflate(R.layout.provider_list, parent, false);
}
checkedTextView = (CheckedTextView) row.findViewById(R.id.list_text);
checkedTextView.setText(operatorList.get(0));
Log.i(TAG, "OperatorListAdapter:"+operatorList.get(0));
Boolean checked = selectOperatorStatusMap.get(position);
if (checked != null) {
checkedTextView.setChecked(true);
}
return row;
}
}
Yes. in getView instead of
if (checked != null) {
checkedTextView.setChecked(true);
}
Use:
if (position == 0) {
checkedTextView.setChecked(true);
}
else{
checkedTextView.setChecked(false)
}

Sorting a ListView with ArrayAdapter<String>

I have a custom ListView, each list item has four TextViews showing bank name, amount, date and time. This data is stored in a database. The idea is that on the Activity there is a quick action dialog which opens on clicking the sort button. The Dialog has three options as "Sort by bank name" ascending order, "Sort by Date" newest first and "Sort by amount" larger amount in the top of the list. I don't have any idea of how to proceed with the sorting task to be written in onItemClick(int pos). Can anyone please help me on this?
public class TransactionMenu extends Activity implements OnItemClickListener, OnActionItemClickListener {
String[] TransId ;
String[] mBankName;
String[] mAmount;
String[] mDate;
String[] mTime;
Button SortButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_screen);
SortButton = (Button)findViewById(R.id.sortKey);
//Bank Name action item
ActionItem bName = new ActionItem();
bName.setTitle("Bank Name");
bName.setIcon(getResources().getDrawable(R.drawable.bank_256));
//Amount action item
ActionItem amt = new ActionItem();
amt.setTitle("Amount");
amt.setIcon(getResources().getDrawable(R.drawable.cash));
//date action item
ActionItem date = new ActionItem();
date.setTitle("Date");
date.setIcon(getResources().getDrawable(R.drawable.calender));
//create quickaction
final QuickAction quickAction = new QuickAction(this);
quickAction.addActionItem(bName);
quickAction.addActionItem(amt);
quickAction.addActionItem(date);
quickAction.setOnActionItemClickListener(this);
SortButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
//quickAction.setAnimStyle(QuickAction.ANIM_REFLECT);
}
});
DBAdapter lDBAdapter = new DBAdapter(this);
lDBAdapter.open();
/* getTransDetails() returns all the detials stored in the transaction table*/
Cursor mCursor =lDBAdapter.getAllTransDetails();
System.out.println("cur..........."+mCursor);
lDBAdapter.close();
if (mCursor != null) {
int size = mCursor.getCount();
if (mCursor.moveToFirst()) {
TransId = new String[size];
mAmount = new String[size];
mBankName = new String[size];
mDate = new String[size];
mTime = new String[size];
for (int i = 0; i < size; i++, mCursor.moveToNext()) {
TransId[i] = mCursor.getString(0);
mAmount[i] = mCursor.getString(1);
mBankName[i] = mCursor.getString(3);
mDate[i] = mCursor.getString(2);
mTime[i] = mCursor.getString(4);
}
}
}
for (int i = 0; i < mCursor.getCount(); i++) {
System.out.println("TransId is+++++++++++++++ "+TransId[i]);
System.out.println("amount is+++++++++++++++ "+mAmount[i]);
System.out.println("bankName is+++++++++++++++ "+mBankName[i]);
System.out.println("date is+++++++++++++++ "+mDate[i]);
System.out.println("time is+++++++++++++++ "+mTime[i]);
}
ListView myListView = (ListView) findViewById(R.id.transactionListView);
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
myListView.setAdapter(myAdapterObj);
myListView.setOnItemClickListener((OnItemClickListener) this);
}
private class MyBaseAdapter extends ArrayAdapter<String> {
public MyBaseAdapter(Context context, int textViewResourceId, String[] transId) {
super(context, textViewResourceId, transId);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView label = (TextView)row.findViewById(R.id.textview1);
label.setText("Amount: "+mAmount[position]);
TextView label1 = (TextView) row.findViewById(R.id.textview2);
label1.setText("Bank Name: "+mBankName[position]);
TextView label2 = (TextView) row.findViewById(R.id.textview3);
label2.setText("Date: "+mDate[position]);
TextView label3 = (TextView) row.findViewById(R.id.textview4);
label3.setText("Time: "+mTime[position]);
return row;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("arg2 is++++++++++++++"+arg2);
int lRowId = Integer.parseInt(TransId[arg2]);
}
public void onItemClick(int pos) {
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
if (pos == 0) {
Toast.makeText(TransactionMenu.this, "Bank name item selected", Toast.LENGTH_SHORT).show();
}
else if (pos ==1) {
Toast.makeText(TransactionMenu.this, "amount item selected", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TransactionMenu.this, "Date item selected", Toast.LENGTH_SHORT).show();
}
}
}
I will give you the way i would do this, not the best probably but it will work fine.
Fisrt of all as user7777777777 said it's better to keep related infos into the same object so i'd define BankInfo class as shown below:
private class BankInfo{
String TransId ;
String mBankName;
String mAmount;
String mDate;
String mTime;
public BankInfo(String TransId,String mBankName,String mAmount,String mDate,String mTime)
{
//fields init
}
}
once you have this you will define an Array of this object BankInfo[] trans. In the adapter you can use this array to bind values into views.
then to manage to implement the sorting function the thing i would do is to put a static variable into the BankInfo class and override the CompareTo() method to use that field:
static int AMMOUNT = 0;
static int DATE = 1;
static int NAME = 2;
static public int sort_by;
public int compareTo(BankInfo info){
switch (sorty_by){
case(AMMOUNT):
return //compare by ammount
case(DATE):
return //compare by date
case(NAME):
return //compare by name
}
}
with this inside of BankInfo you will have only to add your array to a TreeSet<BankInfo> and all your item will be sortet using the compareTo() method.
Inside the adapter put this method to sort elements in the adapter
public void sort_datas(int sort_by);
{
//set the type of sort you want
BankInfo.sortBy = sort_by;
//build a Sorted treeSet by the BankInfo array
TreeSet<BankInfo> sorted_info = new TreeSet<BankInfo>();
list.addAll(Arrays.asList(trans));
//replace the BankInfo array with the new sorted one
trans = (BankInfo[])sorted_info.toArray();
//notify to the adapter that the data set changed
notifyDataSetChanged();
}
You can use the following code. You need to maintain the bank info in a BankInfo object. Create an ArrayList of BankInfo objects and then you can use this code. Its not a good practice to keep related info into separate arrays.
Collections.sort(mBankInfoArrayList, new Comparator<BankInfo>() {
int compare(BankInfo obj1, BankInfo obj2) {
return obj1.getBankName().compareToIgnoreCase(obj2.getBankName());
}
});

Categories