Sorting a ListView with ArrayAdapter<String> - java

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());
}
});

Related

How to preselected checkbox show when again arraylist open in android

First I am selecting some array item using checkbox and displaying it in second activity. After that I am again opening my first activity of ArrayList but my checkbox selection clears.
Below is my code
public class Occassion extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener {
ListView listView_occassion;
ArrayAdapter<String> adapterOccassion;
Button mButtonOccassionNext;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_occassion);
listView_occassion = (ListView) findViewById(R.id.occassion_listview);
mButtonOccassionNext = (Button) findViewById(R.id.btn_occassion_next);
listView_occassion.setOnItemClickListener(this);
String[] Occassion = getResources().getStringArray(R.array.occassion_array);
adapterOccassion = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, Occassion);
listView_occassion.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView_occassion.setAdapter(adapterOccassion);
mButtonOccassionNext.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),Filters.class);
startActivity(intent);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
SparseBooleanArray checked = listView_occassion.getCheckedItemPositions();
ArrayList<String> selectedItemsOccassion = new ArrayList<String>();
Utils.occassionArrayList.clear();
for (i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
// selectedItemsFlavour.add(adapterFlavour.getItem(position));
Utils.occassionArrayList.add(adapterOccassion.getItem(position));
}
}
}
Display second activity as result..
mtv_occassion_status = (TextView) findViewById(R.id.tv_occassion_status);
if(!Utils.occassionArrayList.isEmpty()){
String tempOccassion= String.valueOf(Utils.occassionArrayList);
mtv_occassion_status.setText(tempOccassion);
}
And my array list add in String.xml
<string-array name="occassion_array">
<item>Birthday</item>
<item>Wedding</item>
<item>Anniversary</item>
<item>Celebration</item>
<item>Get Well Soon</item>
<item>House warming</item>
<item>Valentines Day</item>
<item>Diwali</item>
<item>Friendship Day</item>
<item>X-Mas</item>
<item>New Year</item>
<item>Random</item>
</string-array>
Any help would be great for me.
create a class like:
class Occasion {
public String name;
public boolean status;
}
after that create a arraylist:
ArrayList<Occasion> dataList = new ArrayList<>();
and put your items with selection status into this arraylist like this:
String[] occassion = getResources().getStringArray(R.array.occassion_array);
for(int i=0; i < occassion.lenght(); i++){
String name = occasion[i];
Occasion obj = new Occasion();
obj.name = name;
obj.status = getItemStatus(name);
datalist.add(obj);
}
now pass this datalist to your adapter and set the check status on the basis of status parameter of Occasion class
private boolean getItemStatus(String name) {
String items = getSharedPreferences("pref", 0).getString("items", "");
if(items.contains(name){
return true;
}
return false;
}
and
#Override
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
String selectedItemName = dataList.get(i).name;
String items = getSharedPreferences("pref", 0).getString("items", "");
if(!dataList.get(i).status) {
if(items.equals("")) {
items = selectedItemName;
} else {
items = items +","+ selectedItemName;
}
} else {
items = items.replace(selectedItemName, "");
}
SharedPreferences.Editor editor = getSharedPreferences("pref", 0).edit();
editor.putString("items", items);
editor.apply();
dataList.get(i).status = !dataList.get(i).status;
adapter.notifyDataSetChanged();
}
now you have to change your adapter class only. In that class under getView() you have to check the status of each item and select the checkbox accordingly.
Hope this will help you out.
Check this .
for(int i = 0 ; i<adapterOccassion.size ;i++)
{
if(Utils.occassionArrayList.contains(adapterOccassion.getItem(i)))
{
// set checked
}
}

How to manipulate volley response in android?

I want to add two features into my listview :-
1)On Long click I want to delete the row.
2)And once the row is
deleted I want to change the document numbers so that it is always in
order.
For eg:- I have a list with doc_no IN1000,IN1001,IN1002 and I
delete the row with doc_no IN1001. What I would like to do is change
the doc_no of IN1002 to IN1001.So that it is always in a sequence.
So far I am successfully able to delete a row using parent.removeViewInLayout(view); but there is a problem if I scroll the listview I get the deleted row back.
This is my code for deleting the row :-
lv_bsall.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, final View view, int position, long id)
{
final int pos = position;
final Dialog delete_expense = new Dialog(ReportGenerator.this);
delete_expense.setContentView(R.layout.delete_payment);
delete_expense.setTitle("DO YOUY WANT TO DELETE Invoice");
Button yes = (Button) delete_expense.findViewById(R.id.yes);
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
parent.removeViewInLayout(view);
doc_no = ArrayUtils.removeElement(doc_no,doc_no[pos]);
balance =ArrayUtils.removeElement(balance,balance[pos]);
total =ArrayUtils.removeElement(total,total[pos]);
vat =ArrayUtils.removeElement(vat,vat[pos]);
profit=ArrayUtils.removeElement(profit,profit[pos]);
delete_expense.dismiss();
}
});
Button no = (Button) delete_expense.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delete_expense.dismiss();
}
});
delete_expense.show();
return true;
}
});
This is the method I call on response :-
public void showBS(String response) {
ParseBS_all pb = new ParseBS_all(response);
pb.parseBS();
doc_no =ParseBS_all.doc_no;
balance =ParseBS_all.balance;
total =ParseBS_all.total;
vat=ParseBS_all.vat;
profit=ParseBS_all.profit;
bl = new BS_allList(this, doc_no, balance, total, vat, profit);
lv_bsall.setAdapter(bl);
}
And this is code for my Adapter class for the list:-
public class BS_allList extends ArrayAdapter<String>
{
private String[] doc_no;
private String[] balance;
private String[] total;
private String[] vat;
private String[] profit;
private Activity context;
public BS_allList(Activity context, String[] doc_no, String[]balance, String[] total, String[] vat, String[] profit)
{
super(context, R.layout.bs_list_all, doc_no);
this.context =context;
this.doc_no= doc_no;
this.balance = balance;
this.total = total;
this.vat=vat;
this.profit = profit;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
tv_docNo.setText(doc_no[position]);
tv_balance.setText(balance[position]);
tv_tot.setText(total[position]);
tv_vat.setText(vat[position]);
tv_pf.setText(profit[position]);
return listViewItem;
}
}
I am new to programming so any Help or suggestion is most appreciated.Thank you.
I think using ArrayList should be helpful in your case. Please try this solution.It addresses both your requirements:-
public void onClick(View v)
{
ls_docno = new ArrayList<String>(Arrays.asList(doc_no));
ls_balance = new ArrayList<String>(Arrays.asList(balance));
ls_total =new ArrayList<String>(Arrays.asList(total));
ls_vat= new ArrayList<String>(Arrays.asList(vat));
ls_profit =new ArrayList<String>(Arrays.asList(profit));
ls_docno.remove(pos);
ls_balance.remove(pos);
ls_total.remove(pos);
ls_profit.remove(pos);
ls_vat.remove(pos);
Log.d("POSITION",String.valueOf(pos));
for (int i=pos; i< ls_docno.size(); i++)
{
if(i>0)
{
String doc= ls_docno.get(i-1);
String inv_no = doc.replaceAll("[^0-9]", "");
int new_invno = Integer.parseInt(inv_no);
new_invno++;
ls_docno.set(i,"IN"+new_invno);
}
}
doc_no = ls_docno.toArray(new String[ls_docno.size()]);
balance = ls_balance.toArray(new String[ls_balance.size()]);
total = ls_total.toArray(new String[ls_total.size()]);
profit = ls_profit.toArray(new String[ls_profit.size()]);
vat = ls_profit.toArray(new String[ls_vat.size()]);
bl = new BS_allList(ReportGenerator.this, doc_no, balance, total, vat, profit);
lv_bsall.setAdapter(bl);
delete_expense.dismiss();
}
Create a method in your adapter called deleteRow and pass position as am argument. Like this:
public void deleteRow(int position)
{
doc_no = ArrayUtils.removeElement(doc_no, doc_no[position]);
total = ArrayUtils.removeElement(total, total[position]);
balance = ArrayUtils.removeElement(balance, balance[position]);
vat = ArrayUtils.removeElement(vat, vat[position]);
profit = ArrayUtils.removeElement(profit, profit[position]);
notifyDataSetChanged();
}
call it in your LongClick :
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// Here 'bl' is the object of your 'BS_allList' adpater
bl.deleteRow(position);
parent.removeViewInLayout(view);
delete_expense.dismiss();
}
});

Searching and deleting rows in Custom ListView

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!

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);
}
}

Problem with Parcel // ArrayList

I am currently trying to pass an ArrayList of objects from one activity to another. After much searching, I saw that you could pass things as parcels. Here is what I ended up doing:
public class PartsList extends ArrayList<Part> implements Parcelable {
public PartsList(){
}
public PartsList(Parcel in){
}
#SuppressWarnings("unchecked")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public PartsList createFromParcel(Parcel in) {
return new PartsList(in);
}
public Object[] newArray(int arg0) {
return null;
}
};
private void readFromParcel(Parcel in) {
this.clear();
// read the list size
int size = in.readInt();
// order of the in.readString is fundamental
// it must be ordered as it is in the Part.java file
for (int i = 0; i < size; i++) {
Part p = new Part();
p.setDesc(in.readString());
p.setItemNmbr(in.readString());
p.setPrice(new BigDecimal(in.readString()));
this.add(p);
}
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel arg0, int arg1) {
int size = this.size();
arg0.writeInt(size);
for (int i = 0; i < size; i++) {
Part p = this.get(i);
arg0.writeString(p.getDesc());
arg0.writeString(p.getItemNmbr());
arg0.writeString(p.getPrice().toString());
}
}
}
And here is the part Object:
public class Part implements Parcelable{
private String desc;
private String itemNmbr;
private BigDecimal price;
public Part(){
}
public Part(String i, String d, BigDecimal p){
this.desc = d;
this.itemNmbr = i;
this.price = p;
}
It also has getters/setters of course.
This is where the list is created:
for (String i : tempList){
Matcher matcher = pattern.matcher(i);
while (matcher.find()){
// getting matches
String desc = matcher.group(6);
String item = matcher.group(9);
BigDecimal price = new BigDecimal(matcher.group(12).toString());
// adding the new part to the parts list
parts.add(new Part(item, desc, price));
}
}
Now, here is where it is received:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get extras (list)
Bundle b = getIntent().getExtras();
parts = b.getParcelable("parts");
// Part[] PARTS = (Part[]) parts.toArray();
final Part[] PARTS = new Part[] {
new Part("desc", "item id", new BigDecimal(0))
};
final String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra"
};
setListAdapter(new ArrayAdapter<Part>(this, R.layout.list_item, PARTS));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
If I don't use the parcel, and just use the array - it works fine. I commented out my test list and it worked fine, otherwise it crashed.
// parts.add(new Part("desc", "item id", new BigDecimal(0)));
// parts.add(new Part("desc2", "item id2", new BigDecimal(1)));
// parts.add(new Part("desc3", "item id3", new BigDecimal(2)));
// create a new bundle
Bundle b = new Bundle();
// put the list into a parcel
b.putParcelable("parts", parts);
Intent i = new Intent(SearchActivity.this, Results.class);
// put the bundle into the intent
i.putExtras(b);
startActivity(i);
Did I do something wrong with the implementation of the Parcel? I can't figure this out. If anyone could help me ASAP - that would be amazing.
In your implementation of Parcelable.Creator, this looks sketchy:
public Object[] newArray(int arg0) {
return null;
}
I believe it should be:
public Object[] newArray(int arg0) {
return new PartsList[arg0];
}
You also need to define your CREATOR object for Part if you're going to declare it to implement Parcelable (although I'm not sure why it needs to).

Categories