Android/Java - Defining variables at different "places" - java

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

Like this you can access your array in the onClickListener, in case thats what you wanted to achieve
String[] myString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// "TPBDB stuff"
TPBDB = openOrCreateDatabase("TPBDB1", MODE_PRIVATE, null);
Cursor cur = TPBDB.rawQuery("SELECT * from Vogel", null);
String mycur = cur.toString();
int count = cur.getCount();
myString = new String[count]; // init array here
...
}
you just have to declare a field "above" oncreate, you dont have to initialize it at the same time.

Related

Problem in checking CheckBoxes, why only the last edit text gets Strikethrough on?

This the code for CheckListDetail.java
public class ChecklistDetail extends AppCompatActivity {
Toolbar toolbar;
LinearLayout linearLayout;
ActivityChecklistDetailBinding binding;
ChecklistViewBinding checklistViewBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChecklistDetailBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.btnAddItemDetail.setVisibility(View.GONE);
toolbar = findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
// Here int must be used to get the id, if long used, it doesn't work and always return id=0
String status = intent.getStringExtra("status");
String content = intent.getStringExtra("content");
String[] statusSplit = status.split("\n");
String[] contentSplit = content.split("\n");
int i = 0;
for (i = 0; i < contentSplit.length; i++) {
// This will copy the variable i into j.
final int j = i;
boolean state;
if (statusSplit[i].equals("1"))
state = true;
else
state = false;
checklistViewBinding = ChecklistViewBinding.inflate(getLayoutInflater());
binding.linearLayout.addView(checklistViewBinding.getRoot());
checklistViewBinding.etChecklistItem.setText(contentSplit[i]);
checklistViewBinding.checkBox.setChecked(state);
checklistViewBinding.imgDelete.setVisibility(View.INVISIBLE);
SpannableString spannableString = new SpannableString(checklistViewBinding.etChecklistItem.getText().toString());
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spannableString.setSpan(strikethroughSpan, 0, checklistViewBinding.etChecklistItem.getText().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (checklistViewBinding.checkBox.isChecked())
checklistViewBinding.etChecklistItem.setText(spannableString);
else
checklistViewBinding.etChecklistItem.setText(contentSplit[i]);
int finalI = i;
int finalI1 = i;
checklistViewBinding.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
SpannableString spannableString = new SpannableString(checklistViewBinding.etChecklistItem.getText().toString());
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spannableString.setSpan(strikethroughSpan, 0, checklistViewBinding.etChecklistItem.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (b) {
checklistViewBinding.etChecklistItem.setText(spannableString);
} else {
checklistViewBinding.etChecklistItem.setText(contentSplit[finalI]);
}
}
});
}
}
}
I get a layout like this image.
If I check the first item which is (a) but (c) gets modified which is get a Strikethrough. No matter if I check (a), (b) or (c), but only (c) gets a Strikethrough. (a) and (b) don't get Strikethrough. Also if I check (a) after that the the third item which is (c) change to (a) or if I check (b) the third item which is (c) change to (b).
Any ideas?

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!

Listview using Endless adapter

I have DB table with 10,000 rows which I want to display in the listview. I want to display first 20 and when the user scrolls down to the last item the next 20 should be loaded (and so on.). it really takes a lot of time to load all the datas in the listview so thats why i want it to load 20 datas first..
inside onCreate() Method the code is:
dbHelper = new WordDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
then on the displayListView() method the code is like this:
#SuppressWarnings("deprecation")
private void displayListView() {
final Cursor cursor = dbHelper.fetchAllWords();
// The desired columns to be bound
String[] columns = new String[] {
WordDbAdapter.KEY_WORD,
WordDbAdapter.KEY_ROWID,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.Word,
R.id.imgStar,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.word_info,
cursor,
columns,
to
);
ListView listView = (ListView) findViewById(R.id.Diclist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if(cursor != null){
if(lastInScreen == totalItemCount && isLoadingMore == false){
isLoadingMore = true;
loadedPage ++;
new LoadWords().execute();
}
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the word name from this row in the database.
String wordSelected =
cursor.getString(cursor.getColumnIndexOrThrow("word"));
String wordSyllabication =
cursor.getString(cursor.getColumnIndexOrThrow("syllabication"));
String wordPartofSpeech =
cursor.getString(cursor.getColumnIndexOrThrow("partofspeech"));
String wordMeaning =
cursor.getString(cursor.getColumnIndexOrThrow("meaning"));
String wordSpeak =
cursor.getString(cursor.getColumnIndexOrThrow("speakword"));
EditText TextDic = (EditText) findViewById(R.id.TextDic);
TextDic.setText(wordSelected);
speakMeaning = wordMeaning;
speakSyllabication = wordSyllabication;
speakPartOfSpeech = wordPartofSpeech;
speakWord = wordSpeak;
speakGetWord = wordSelected;
//Toast.makeText(getApplicationContext(),
// wordSyllabication + "\n" + wordPartofSpeech + "\n" + wordMeaning , Toast.LENGTH_SHORT).show();
}
});
EditText TextDic = (EditText) findViewById(R.id.TextDic);
TextDic.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
speakWord = "";
speakMeaning = "";
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchWordsByWord(constraint.toString());
}
});
}
then my AsyncTask is like this:
private class LoadWords extends AsyncTask<String, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(DictionaryActivity.this);
Cursor cursor = dbHelper.fetchAllWords();
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading books...");
this.dialog.show();
}
public void execute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(String... arg0) {
try{
cursor = dbHelper.fetchAllWords();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(final Void unused){
if(cursor != null){
if(dataAdapter == null){
startManagingCursor(cursor);
String[] columns = new String[] {
WordDbAdapter.KEY_WORD,
WordDbAdapter.KEY_ROWID,
};
int[] to = new int[] {
R.id.Word,
R.id.imgStar,
};
getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
dataAdapter = new SimpleCursorAdapter(DictionaryActivity.this, R.layout.word_info, cursor, columns, to);
ListView listView = (ListView) findViewById(R.id.Diclist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}else{
dataAdapter.notifyDataSetChanged();
}
}
if(dialog != null && dialog.isShowing()){
dialog.dismiss();
}
isLoadingMore = false;
}
private AbsListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
The adapter doesn't load everything at once, and that should not be the reason you're seeing poor performance. ListView and SimpleCursorAdapter are fully capable of scrolling a list of only 10,000 items. The adapter only loads items as the user scrolls through the list. From the code that you've posted, I would say that your performance issues come from
dbHelper.deleteAllWords();
dbHelper.insertSomeWords();
If you post the code for these methods and dbHelper.fetchAllWords(), perhaps we can offer more help. Additionally, you can solve user interface problems by executing these long running tasks on a background thread (check out AsyncTask) and using a ProgressDialog to inform the user what is going on.
Take a look at Endless Adapter from the great Mark Murphy. It makes it really easy. You'll have your dataset that contains just the items you're displaying. In the adapter you can then tell it to grab the next set from your database and add it to the dataset.

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

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