How to manipulate volley response in android? - java

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

Related

Recycerview changing the wrong items

here is my recyclerview adapter classs
public class WebsiteAdapter extends RecyclerView.Adapter<WebsiteAdapter.WebsiteHolder> {
private List<Website> websites = new ArrayList<>();
private WebsiteViewModel websiteViewModel;
WebsiteAdapter(WebsiteViewModel viewModel){
this.websiteViewModel = viewModel;
}
#NonNull
#Override
public WebsiteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.website_item, parent, false);
return new WebsiteHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final WebsiteHolder holder, final int position) {
final Website currentWebsite = websites.get(position);
final Boolean bookmarkStatus = currentWebsite.getFavourite();
final List<WebPage> webPages = websiteViewModel.getRepository().getAllWebPagesForWebsite(currentWebsite.getWebsite_id());
holder.textViewTitle.setText(currentWebsite.getWebsiteName());
if(currentWebsite.getDescription() != null){
holder.textViewDescription.setText(currentWebsite.getDescription());
holder.textViewDescription.setVisibility(View.VISIBLE);
}
if(webPages!=null && !webPages.isEmpty()) {
holder.secondaryAdapter.setWebPages(webPages);
holder.expandCollapse.setVisibility(View.VISIBLE);
}
if(bookmarkStatus){
holder.isBookmarked = true;
holder.bookmarkButton.setBackgroundResource(R.drawable.ic_bookmark_24px);
} else {
holder.isBookmarked = false;
holder.bookmarkButton.setBackgroundResource(R.drawable.ic_bookmark_border_24px);
}
holder.cardViewWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String websiteUrl = currentWebsite.getWebsite_url();
System.out.println("Description = " + currentWebsite.getDescription() + ", boomarked : " + currentWebsite.getFavourite());
List<WebPage> webPages = websiteViewModel.getRepository().getAllWebPagesForWebsite(currentWebsite.getWebsite_id());
for(WebPage webPage : webPages){
System.out.println("Web pages: ");
System.out.println(webPage.toString() + ", ");
}
launchWebsite(v.getContext(), websiteUrl);
}
});
holder.bookmarkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Website bookmarked before click : " + bookmarkStatus + ", Description is : " + currentWebsite.getDescription());
currentWebsite.setFavourite(!bookmarkStatus);
System.out.println("Website bookmark clicked, status has been set to : " + currentWebsite.getFavourite());
websiteViewModel.getRepository().websiteDao.updateWebsite(currentWebsite);
notifyItemChanged(position);
}
});
}
private void launchWebsite(Context context, String URL) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setStartAnimations(context, R.anim.push_off_screen_left, R.anim.push_onto_screen_from_right);
builder.setExitAnimations(context, R.anim.push_onto_screen_from_left, R.anim.push_off_screen_right);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context,Uri.parse(URL));
}
#Override
public int getItemCount() {
return websites.size();
}
public void setWebsites(List<Website> websites) {
this.websites = websites;
notifyDataSetChanged();
}
class WebsiteHolder extends RecyclerView.ViewHolder {
private TextView textViewTitle;
private TextView textViewDescription;
private CardView cardViewWebsite;
private boolean isBookmarked; // ALSO FAVOURITED
private boolean isExpanded = false;
private Button expandCollapse;
private Button bookmarkButton;
private SecondaryAdapter secondaryAdapter;
private RecyclerView childRecyclerView;
public WebsiteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.text_view_title);
textViewDescription = itemView.findViewById(R.id.text_view_description);
cardViewWebsite = itemView.findViewById(R.id.cardViewWebsite);
bookmarkButton = itemView.findViewById(R.id.bookmarkButton);
childRecyclerView = itemView.findViewById(R.id.childRecyclerview);
expandCollapse = itemView.findViewById(R.id.expandCollapse);
expandCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isExpanded) {
collapseView();
} else {
expandView();
}
}
});
childRecyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayoutManager.HORIZONTAL, false));
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(itemView.getContext(), R.anim.layout_animation_slide_in);
childRecyclerView.setLayoutAnimation(animation);
childRecyclerView.setHasFixedSize(true);
secondaryAdapter = new SecondaryAdapter();
childRecyclerView.setAdapter(secondaryAdapter);
}
private void collapseView() {
isExpanded = false;
childRecyclerView.setVisibility(View.GONE);
}
private void expandView() {
isExpanded = true;
childRecyclerView.setVisibility(View.VISIBLE);
}
}
}
The issue I am having is, when I press the bookmark button on item A: the expand button on a different item will appear when it should not. B: The secondaryRecyclerView gets set to some other website. How do I go about debugging this? Is there anything that jumps out as a culpit? I feel like I am setting somethings in the wrong place. Thanks very much
wrong item changes in recyclerview
Thanks to this post, I one, added in a bindView method, and 2: added ELSE statements to negate the if statements. Problems solved :) For now :)

java.lang.IndexOutOfBoundsException : When i try to remove item from list of recyclerview

When ever i try to delete last item from list it gives me IndexOutOfBound Error, its happen only with last item from list.
Here is my code
public class CartAdapter extends RecyclerView.Adapter<CartViewHolder> {
private List<Order> listData = new ArrayList<>();
private CartActivity cartActivity;
private int total;
public CartAdapter(List<Order> listData, CartActivity cartActivity) {
this.listData = listData;
this.cartActivity = cartActivity;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(cartActivity);
View itemView = inflater.inflate(R.layout.cart_layout, viewGroup, false);
return new CartViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CartViewHolder cartViewHolder, #SuppressLint("RecyclerView") final int i) {
cartViewHolder.counterButton.setNumber(listData.get(i).getQuantity());
cartViewHolder.counterButton.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
#Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
total = 0;
Order order = listData.get(i);
order.setQuantity(String.valueOf(newValue));
new Database(cartActivity).updateCart(order);
calculate();
}
});
cartViewHolder.txt_price.setText(listData.get(i).getPrice());
cartViewHolder.txt_cart_name.setText(listData.get(i).getFoodName());
cartViewHolder.removeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listData.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, listData.size());
Order order = listData.get(i);
new Database(cartActivity).clearItem(order);
calculate();
}
});
}
private void calculate(){
for (Order orders: listData){
total += Integer.parseInt(orders.getPrice()) * Integer.parseInt(orders.getQuantity());
Log.d("GDGDGD", String.valueOf(total));
}
int cgst = (total * 5)/100;
total += cgst;
Locale locale = new Locale("en","IN");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
cartActivity.txtTotalPrice.setText(fmt.format(total));
}
}
Above code is snippet from recyclerview, item fetched from the database and list made.
The issue is this line: Order order = listData.get(i);
You are removing the item first and then you are trying to get the order.
listData.remove(i); // remove item from listData: it will have zero items if earlier, listData had one item
...
Order order = listData.get(i); // get ith order: will crash if listData's size is 0
Placing listData.remove(i); at the end of the function will solve the issue.
Like this:
cartViewHolder.removeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notifyItemRemoved(i);
notifyItemRangeChanged(i, listData.size());
Order order = listData.get(i);
new Database(cartActivity).clearItem(order);
listData.remove(i);
calculate();
}
});
Edit:
There is one more issue in calculate(). You have to reassign the variable total to zero.
Like this:
private void calculate(){
total = 0;
for (Order orders: listData){
total += Integer.parseInt(orders.getPrice()) * Integer.parseInt(orders.getQuantity());
Log.d("GDGDGD", String.valueOf(total));
}
int cgst = (total * 5)/100;
total += cgst;
Locale locale = new Locale("en","IN");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
cartActivity.txtTotalPrice.setText(fmt.format(total));
}
And remove total = 0; assignment. Like this:
cartViewHolder.counterButton.setOnValueChangeListener(new ElegantNumberButton.OnValueChangeListener() {
#Override
public void onValueChange(ElegantNumberButton view, int oldValue, int newValue) {
Order order = listData.get(i);
order.setQuantity(String.valueOf(newValue));
new Database(cartActivity).updateCart(order);
calculate();
}
})

Conditional Spinner

I've one problem. I've created spinner, and everything app runs without crashing, but it won't change value of int price, neither setText doesn't work
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calculateBtn;
EditText userEcts;
TextView ectsPrice;
TextView summary;
Spinner courses;
String cors;
int price = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userEcts = (EditText) findViewById(R.id.ects_input);
summary = (TextView) findViewById(R.id.text_summary);
courses = (Spinner) findViewById(R.id.course_spinner);
calculateBtn = (Button) findViewById(R.id.calculate);
calculateBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calculate method.
calculate();
}
});
final String[] courseArray = new String[4];
{
courseArray[0] = "Preddiplomski studij Menadžment";
courseArray[1] = "Preddiplomski studij Promet";
courseArray[2] = "Preddiplomski Upravni studij";
courseArray[3] = "Specijalistički studij Menadžment";
}
ArrayAdapter courseAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, courseArray);
courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
courses.setAdapter(courseAdapter);
courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from Spinner and store in string conductorSize........
cors = parent.getItemAtPosition(pos).toString();
if (cors.equals(0)) {
ectsPrice.setText("200");
price = 200;
} else if (cors.equals(1)) {
ectsPrice.setText("250");
price = 250;
} else if (cors.equals(2)) {
ectsPrice.setText("300");
price = 300;
} else if (cors.equals(3)) {
ectsPrice.setText("350");
price = 350;
} else {
//Do nothing
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
public void calculate() {
//gets entered text from the EditText,and convert to integers.
if (!TextUtils.isEmpty(userEcts.getText().toString())) {
Double ects = Double.parseDouble(userEcts.getText().toString());
//do the calculation
Double calculatedPrice = ects * price;
//set the value to the TextView, to display on screen.
summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
} else {
Toast.makeText(this, "Niste unijeli broj bodova", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
calculate();
}
}
So, on selecting item on position 0, I want to setText to specific text, and change price. Can anyone help?
Use the position number to check the condition.
String[] courseArray = new String[4];
{
courseArray[0] = "Preddiplomski studij Menadžment";
courseArray[1] = "Preddiplomski studij Promet";
courseArray[2] = "Preddiplomski Upravni studij";
courseArray[3] = "Specijalistički studij Menadžment";
}
ArrayAdapter courseAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, courseArray);
courseAdapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
courses.setAdapter(courseAdapter);
courses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from Spinner and store in string conductorSize........
cors = parent.getItemAtPosition(pos).toString();
if (cors.equals(courseArray[0])) {
ectsPrice.setText("200");
price = 200;
} else if (cors.equals(courseArray[1])) {
ectsPrice.setText("250");
price = 250;
} else if (cors.equals(courseArray[2])) {
ectsPrice.setText("300");
price = 300;
} else if (cors.equals(courseArray[3])) {
ectsPrice.setText("350");
price = 350;
} else {
//Do nothing
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
Use a switch statment :
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
switch(pos){
case 0:
ectsPrice.setText("200");
price = 200;
break;
case 1:
ectsPrice.setText("250");
price = 250;
break;
case 2:
ectsPrice.setText("300");
price = 300;
break;
case 3:
ectsPrice.setText("350");
price = 350;
break;
}
}

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

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