Android how to append custom listView using SharedPreferences - java

i want to update my ListView using SharedPreferences get from API response...
I did something like this:
First i inintial the Strings[]:
String First[] = {"aa"};
String Second[] = {"aa"};
String Third[] = {"aa"};
String Four[] = {"aa"};
Integer Five[] = {1};
I want to update this using the Shared Preferences
SharedPreferences settings;
settings = getSharedPreferences("Number_List", Context.MODE_PRIVATE);
String uFirst = settings.getString("uFirst", "NONE");
String uSecond = settings.getString("uSecond", "NONE");
String uThird = settings.getString("uThird", "NONE");
String uFour = settings.getString("uFour", "NONE");
int uFive= settings.getInt("uFive", 0);
First = Arrays.copyOf(First, First.length + 1);
Second= Arrays.copyOf(Second, Second.length + 1);
Third= Arrays.copyOf(Third, Third.length + 1);
Four= Arrays.copyOf(Four, Four.length + 1);
Five= Arrays.copyOf(Five, Five.length + 1);
First[First.length -1] = uFirst;
Second[Second.length -1] = uSecond;
Third[Third.length -1] = uThird;
Four[Four.length -1] = uFour;
Five[Five.length -1] = uFive;
adapter.notifyDataSetChanged();
And this code never refreshing the listview... Im totally without any ideas how to make it more automatically.. Every time when im adding another things in list eg. First[] = {"aaa","bbbb"}; it works properly...
Can someone take the time to help?
Adapter:
class listDataAdapter extends ArrayAdapter<String> {
Context context;
String rFirst[];
String rSecond[];
String rThird[];
String rFour[];
Integer Five[];
listDataAdapter(Context c, String rFirst[], String rSecond[], String rThird[], String rFour[], Integer Five[]) {
super(c, R.layout.listview_row_orders, R.id.data_zal_text, rFirst);
this.context = c;
this.rFirst = rFirst;
this.rSecond = rSecond;
this.rThird = rThird;
this.rFour = rFour;
this.Five = Five;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.listview_row_orders, parent, false);
TextView myFirst = row.findViewById(R.id.data_zal_text_data);
TextView mySecond = row.findViewById(R.id.data_rozl_text_data);
TextView myThird = row.findViewById(R.id.place_zal_text_data);
TextView myFour = row.findViewById(R.id.place_rozl_text_data);
ProgressBar myOrderProgress = row.findViewById(R.id.progress_order_status);
myFirst.setText(rFirst[position]);
mySecond.setText(rSecond[position]);
myThird.setText(rThird[position]);
myFour.setText(rFour[position]);
myOrderProgress.setProgress(Five[position]);
return row;
}
```

The problem is that you have updated the values in you activity, but in the adapter you still have the old values so notifyDataSetChanged will just work with the same values, you need to replace the old array values on the adapter with the new array values, you can create a simple helper method to do that in the adapter class for example
public void updateData(String[] firstArray) {
this.first = firstArray;
notifyDataSetChanged();
}

Related

creating a custom listview, but values contain "#" and what seems like a C pointer

![](https://scontent-dub4-1.xx.fbcdn.net/v/t1.15752-9/43125544_1705062639616259_4425322847673516032_n.jpg?_nc_cat=102&oh=641ab52118c35e228d9aba28076dbca8&oe=5C16DD7E)
this is my custom adapter class
public class CustomAdapter extends ArrayAdapter<Receipt> {
private Context mContext;
private ArrayList<Receipt> receiptList;
public CustomAdapter(Context context, ArrayList<Receipt> list) {
super(context, 0 , list);
mContext = context;
receiptList = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.custom_list_view,parent,false);
Receipt receipt = receiptList.get(position);
TextView name =listItem.findViewById(R.id.textView_name);
name.setText(receipt.getShopName());
TextView release =listItem.findViewById(R.id.textView_total);
release.setText(receipt.getShopTotal());
return listItem;
}
}
my receipt class
public class Receipt {
private String mShopName;
private String mShopTotal;
public Receipt(String mShopName, String mShopTotal) {
this.mShopName = mShopName;
this.mShopTotal = mShopTotal;
}
public String getShopName() {
return mShopName;
}
public String getShopTotal() {
return mShopTotal;
}
}
and here is my populateListView method
private ArrayList populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<Receipt> receiptList = new ArrayList<>();
while (data.moveToNext()) {
mFilteringDatabase.takeInRow(data.getString(1));
String displayedScreen = mFilteringDatabase.shopName();
String displayedTotal= (mFilteringDatabase.total());
receiptList.add(new Receipt(displayedScreen,displayedTotal));
}
mAdapter= new CustomAdapter(getContext(),receiptList);
return receiptList;
}
there seems to be some issue with the receipt class, as if i override the toString with a "return "test" " line, the error disappears, but only displays "test" of course
thanks in advance guys
edit, just to answer some of your questions, the reason i dont believe it is the scanner, is because when i just use string as the ArrayList type, and pass in only 1 value, the data comes in fine from the database, ie
, this is the code that fixes the issue but only for 1 of the 2 values (i.e. i can concat them and put them on the same line, but i want one right aligned and one left aligned so it wont work as a normal list view
private ArrayList populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> receiptList = new ArrayList<>();
while (data.moveToNext()) {
mFilteringDatabase.takeInRow(data.getString(1));
String displayedScreen = mFilteringDatabase.shopName();
receiptList.add(displayedScreen);
}
return receiptList;
}

Highlight search results in ListView whlie typing in EditText [duplicate]

I am trying to do a search such that all the "visible" search letters should be highlighted. I tried using spannable but that didn't do the trick, maybe I wasnt doing it right? based on this: Highlight searched text in ListView items
How do i get to highlight the visible text? here's my filter :
private LayoutInflater mInflater;
private ValueFilter valueFilter;
public MySimpleArrayAdapter(Activity context) {
this.context = context;
mInflater = LayoutInflater.from(context);
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected synchronized FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Integer> filterList = new ArrayList<>();
int iCnt = listItemsHolder.Names.size();
for (int i = 0; i < iCnt; i++) {
if(listItemsHolder.Types.get(i).toString().indexOf("HEADER_")>-1){
continue;
}
if (listItemsHolder.Names.get(i).matches(getRegEx(constraint))||(listItemsHolder.Names.get(i).toLowerCase().contains(constraint.toString().toLowerCase()))) {
if(filterList.contains(i))
continue;
filterList.add(i);
}
}
results.count = filterList.size();
results.values = filterList;
}else {
String prefixString = getRegEx(constraint);
mSearchText = prefixString;
results.count = listItemsHolder.Names.size();
ArrayList<Integer> tList = new ArrayList<>();
for(int i=0;i<results.count;i++){
tList.add(i);
}
results.values = tList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Integer> resultsList = (ArrayList<Integer>)results.values;
if(resultsList != null) {
m_filterList = resultsList;
}
notifyDataSetChanged();
}
}
public String getRegEx(CharSequence elements){
String result = "(?i).*";
for(String element : elements.toString().split("\\s")){
result += element + ".*";
}
result += ".*";
return result;
}
Thanks in advance!
Here's my getview
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder holder;
if(filtering && m_filterList != null && m_filterList.size() > position)
position = m_filterList.get(position);
if (rowView == null) {
holder = new ViewHolder();
mInflater = context.getLayoutInflater();
rowView = mInflater.inflate(R.layout.rowlayout, null);
// configure view holder
holder.text = (TextView) rowView.findViewById(R.id.label);
holder.text.setTextColor(Color.WHITE);
holder.text.setSingleLine();
holder.text.setTextSize(15);
holder.text.setEllipsize(TextUtils.TruncateAt.END);
holder.text.setPadding(2, 2, 6, 2);
Typeface label = Typeface.createFromAsset(holder.text.getContext().getAssets(),
"fonts/arial-bold.ttf");
holder.text.setTypeface(label);
holder.image = (ImageView) rowView.findViewById(R.id.icon);
holder.image.setPadding(6, 4, 0, 4);
holder.image.getLayoutParams().height = (int) getResources().getDimension(R.dimen.icon_width_height);
holder.image.getLayoutParams().width = (int) getResources().getDimension(R.dimen.icon_width_height);
rowView.setBackgroundResource(R.drawable.row_border);
rowView.setPadding(2, 2, 6, 2);
rowView.setTag(holder);
}else {
// fill data
holder = (ViewHolder) rowView.getTag();
}
String id = listItemsHolder.getid(position);
String name = listItemsHolder.getName(position);
holder.image.setVisibility(View.VISIBLE);
if (name != null) {
holder.text.setText(listItemsHolder.getName(position));
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) holder.text.getLayoutParams();
params.leftMargin = 20;
}else{
holder.text.setText(id);
}
String fullText = listItemsHolder.getName(position);
// highlight search text
if (mSearchText != null && !mSearchText.isEmpty()) {
int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
int endPos = startPos + mSearchText.length();
if (startPos != -1) {
Spannable spannable = new SpannableString(fullText);
ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.text.setText(spannable);
} else {
holder.text.setText(fullText);
}
} else {
holder.text.setText(fullText);
}
return rowView;
}
Let's assume you have create a custom adapter, then you can refer to the following code:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
TextView text;
if (convertView == null) {
view = mInflater.inflate(mResource, parent, false);
} else {
view = convertView;
}
try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(mFieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}
String item = getItem(position);
text.setText(item);
String fullText = getItem(position);
// highlight search text
if (mSearchText != null && !mSearchText.isEmpty()) {
int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
int endPos = startPos + mSearchText.length();
if (startPos != -1) {
Spannable spannable = new SpannableString(fullText);
ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
spannable.setSpan(highlightSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText(spannable);
} else {
text.setText(fullText);
}
} else {
text.setText(fullText);
}
return view;
}
The mSearchText will be updated at the following inside performFiltering of ArrayFilter class.
String prefixString = prefix.toString().toLowerCase();
mSearchText = prefixString;
You can find more details in my sample code here or my GitHub (with lastest update).
Here is the screenshot
In your filter method, store the string used to perform the filter:
// Filter Class
public void filter(String searchString) {
this.searchString = searchString;
...
// Filtering stuff as normal.
}
You must declare a member string to store it:
public class ListViewAdapter extends BaseAdapter {
...
String searchString = "";
...
And, in getView you highlight the search term:
public View getView(final int position, View view, ViewGroup parent) {
...
// Set the results into TextViews
WorldPopulation item = worldpopulationlist.get(position);
holder.rank.setText(item.getRank());
holder.country.setText(item.getCountry());
holder.population.setText(item.getPopulation());
// Find charText in wp
String country = item.getCountry().toLowerCase(Locale.getDefault());
if (country.contains(searchString)) {
Log.e("test", country + " contains: " + searchString);
int startPos = country.indexOf(searchString);
int endPos = startPos + searchString.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.country.getText()); // <- EDITED: Use the original string, as `country` has been converted to lowercase.
spanText.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.country.setText(spanText, TextView.BufferType.SPANNABLE);
}
...
}
Hope it helps.
Hi on your adapter class ,make a spanneble text and set it to your textview, the below code you can use for reference.
if ("text contains filter value".toLowerCase().contains("filter".toLowerCase())) {
Spannable spanText = Spannable.Factory.getInstance().newSpannable("text contains filter value".toLowerCase());
Matcher matcher = Pattern.compile("filter".toLowerCase())
.matcher("text contains filter value".toLowerCase());
while (matcher.find()) {
spanText.setSpan(new ForegroundColorSpan(Color.RED), matcher.start(),
matcher.start() + "filter".length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
yourTextView.setText(spanText);
}
This is only demo for highlight text, you can implement your self by calling
highlight(searchText, originalText) in filter,
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
text = (TextView) findViewById(R.id.textView1);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
text.setText(highlight(editText.getText().toString(), text.getText().toString()));
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public static CharSequence highlight(String search, String originalText) {
String normalizedText = Normalizer.normalize(originalText, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
int start = normalizedText.indexOf(search);
if (start <= 0) {
return originalText;
} else {
Spannable highlighted = new SpannableString(originalText);
while (start > 0) {
int spanStart = Math.min(start, originalText.length());
int spanEnd = Math.min(start + search.length(), originalText.length());
highlighted.setSpan(new BackgroundColorSpan(Color.YELLOW), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
start = normalizedText.indexOf(search, spanEnd);
}
return highlighted;
}
}
}
Put this code before setting text in getview
Spannable wordtoSpan = new SpannableString("Your_text_in_getviews");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, edtFilter
.getText().toString().length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txt_contact.setText(wordtoSpan);
It can be done in a bit simpler way:
Define custom adapter:
class HighlightAutoCompleteAdapter(context: Context, resource: Int, private val textResId: Int, items: List<String>) :
ArrayAdapter<String>(context, resource, textResId, items) {
private val inflater = LayoutInflater.from(context)
var queryText = ""
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: inflater.inflate(textResId, parent, false)
val textView: TextView = view.findViewById(android.R.id.text1) as TextView
val fullText = getItem(position) as String
// highlight search text
val highlight: Spannable = SpannableString(fullText)
if (queryText.isNotEmpty()) {
val startPos: Int = fullText.toLowerCase(Locale.US).indexOf(queryText.toLowerCase(Locale.US))
val endPos: Int = startPos + queryText.length
if (startPos != -1) {
highlight.setSpan(StyleSpan(BOLD),
startPos,
endPos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
textView.text = highlight
return view
}
}
Create the adapter and listen to text changes to keep the adapter updated:
val searchEditText: AutoCompleteTextView = view.findViewById(R.id.search_edit_text)
val arrayAdapter = HighlightAutoCompleteAdapter(requireContext(), 0, R.layout.search_complete_item, autoCompletionList)
searchEditText.setAdapter(arrayAdapter)
searchEditText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
arrayAdapter.queryText = s?.toString() ?: ""
}
override fun afterTextChanged(s: Editable?) {}
})

ListItems ArrayList ListView

Guys I'm trying to make the below code store multiple items in exampleArray but it's only grabbing the first SectionOutageListItem. Do I need to create another listItem Array to loop through it again?
SectionOutageListItem[] exampleArray = new SectionOutageListItem[outnums.size()];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i)),
new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
UPDATE:
I have a custom adapter which adds sections to a listview, the SectionOutageListItem determines how many rows are in that section. The outnums.get(i) creates multiple sections which should add the impact and status as rows for each section. It is only adding the first new SectionOutageListItem as a row and not the second one.
Custom List Adapter code
public class CustomOutageDetailListAdapter extends ArrayAdapter<SectionOutageListItem> {
private Activity context;
private SectionOutageListItem[] items;
//private final ArrayList<String> itemname;
public CustomOutageDetailListAdapter(Activity context, SectionOutageListItem[] items) {
super(context, R.layout.mylistoutagedetails, items);
this.items= items;
this.context = context;
}
#Override
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.mylistoutagedetails, null,true);
final SectionOutageListItem currentItem = items[position];
if (currentItem != null) {
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
TextView txtName = (TextView) rowView.findViewById(R.id.name);
if (txtTitle != null) {
txtTitle.setText(currentItem.item.toString());
}
if (txtName != null) {
txtName.setText(currentItem.name.toString());
}
}
return rowView;
};
As #Trobbins points out ,
You may need to change the code as follows,
SectionOutageListItem[][] exampleArray = new SectionOutageListItem[outnums.size()][2];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i][0] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i));
exampleArray[i][1] = new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
You can also go with a Map specifically LinkedHashMap if you want to maintain the insertion order or else HashMap

Set bind view in simple adapter?

I want to setup view binder in simple adapter to show photos from contacts, however I set two text view's with name and number with Hash Map, so third value is Image View where I want to put contact photo corresponding to contact ID.
Thank you in advance, Wolf.
Here is my code :
ArrayList<HashMap<String, String>> mapa = new ArrayList<HashMap<String, String>>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cur.getCount() > 0){
while(cur.moveToNext()){
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String photoUri = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
if(Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
final Cursor numCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
for(numCur.moveToFirst(); !numCur.isAfterLast(); numCur.moveToNext()){
brTel = numCur.getString(numCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ime = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
tmpIme = new String[] {ime};
for(int i = 0; i < tmpIme.length; i++){
HashMap<String, String> imeMapa = new HashMap<String, String>();
imeMapa.put("imeLista", ime);
imeMapa.put("checkBox", photoUri);
imeMapa.put("Mobilni", brTel);
mapa.add(imeMapa);
}
}
numCur.close();
}
} // While
}
SimpleAdapter sa = new SimpleAdapter(getApplicationContext(), mapa, R.layout.imenik, new String[] {"imeLista", "checkBox", "Mobilni"}, new int[] {R.id.tvImeImenik, R.id.cbOznaci, R.id.tvSamoProba});
sa.setViewBinder(simpleSlika);
lImenik.setAdapter(sa);
and my view binder is :
private final SimpleAdapter.ViewBinder simpleSlika = new SimpleAdapter.ViewBinder() {
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if (view instanceof ImageView && data instanceof Bitmap) {
ImageView v = (ImageView)view;
v.setImageBitmap((Bitmap)data);
// return true to signal that bind was successful
return true;
}
return false;
}
};
but it's not working.
Help please???
Yes its possible, you just create your own adapter (extends BaseAdapter), override getView method and there add bitmap to imageview.
public ContactAdapter(Activity a,ArrayList<Object> list)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View v=convertView;
if(convertView==null)
v = inflater.inflate(R.layout.contact, null);
ImageView image = (ImageView)v.findViewById(R.id.img);
}
Something like this. You have to extends this.
Check also : Lazy load of images in ListView

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