I'm trying to group of several ArrayLists for a music player. The current list generates the artists for every song instead of just the one artist. Hopefully this should explain it better:
My current code for one of my fragments is this:
public class ArtistsFragment extends Fragment {
private ArrayList<Artist> artistList;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_artists, container, false);
GridView gvArtists = (GridView) view.findViewById(R.id.gvArtists);
//instantiate list
artistList = new ArrayList<>();
//get artists from device
getArtistList();
// Group ArrayList..
artistList = new ArrayList<>(new HashSet<>(artistList));
//sort alphabetically by title
Collections.sort(artistList, new Comparator<Artist>() {
public int compare(Artist a, Artist b) {
return a.getArtist().compareTo(b.getArtist());
}
}
);
//create and set adapter
ArtistAdapter artistAdt = new ArtistAdapter(getActivity(), artistList);
gvArtists.setAdapter(artistAdt);
return view;
}
void getArtistList() {
//retrieve artist info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int idColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Albums.ARTIST);
int artColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media.ARTIST_ID);
//add artists to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisArt = musicCursor.getString(artColumn);
artistList.add(new Artist(thisId, thisArtist, thisArt));
}
while (musicCursor.moveToNext());
musicCursor.close();
}
}
}
Artist.class
class Artist {
private final long id;
private final String artist;
private final String art;
public Artist(long artistID, String theartist, String artistArt) {
id = artistID;
artist = theartist;
art = artistArt;
}
public long getID() {
return id;
}
public String getArtist() {
return artist;
}
public String getArt() {
return art;
}
}
I've looked at Map, I've looked at Set and now i'm just confused...
So, how do I group my ArrayList to remove the duplicates of different artists to then eventually use the OnPicked to change the ArrayList to those grouped songs within that group/category?
Am I even on the right lines or is there a completely different method to sorting Genres/Artists/Albums Etc.?
if clearing your duplicates is your sole problem, then this is how to clear all duplicates on your List (convert it to a Set and back):
Set<Artist> set = new HashSet<Artist>(artistList);
artistList = new ArrayList<Artist>(set);
//then sort it...
or one-line
artistList = new ArrayList<Artist>(new HashSet<Artist>(artistList));
You should also override the equals() and hashCode() methods based on the fields that make an entry to your list unique.
Related
I'm using Room Persistance library with all Android Architucture Components. In the app I have 3 databases, but the problem is with only one. In my MainActivity I have a RecyclerView that show data (dates) from DatesDatabase. When clicking on each element, a new activity opens and shows all the data that refers to particular date. The query in DAO is:
#Query("SELECT * FROM Sorted WHERE date = :date")
LiveData<List<Sorted>> getSortedWhereDateIs(String date);
Problem is that when I restart the app I still can see the dates, that have been added earlier, but there is no data that refers to this date.
Before restarting:
screenshot1
screenshot2
After restarting:
screenshot1
screenshot2
Code to DatesDatabase:
#Database(entities = {Dates.class}, version = 2, exportSchema = false)
public abstract class DatesDatabase extends RoomDatabase {
private static DatesDatabase instance;
public abstract DatesDao datesDao();
public static synchronized DatesDatabase getInstance(Context context){
if (instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(),
DatesDatabase.class, "dates_database").fallbackToDestructiveMigration()
.build();
}
return instance;
}
}
Code to database, that doesn't save data:
#Database(entities = {Sorted.class}, version = 3, exportSchema = false)
public abstract class SortedDatabase extends RoomDatabase {
private static SortedDatabase instanceSorted;
public abstract SortedDao sortedDao();
public static synchronized SortedDatabase getSortedInstance(Context context) {
if (instanceSorted == null) {
instanceSorted = Room.databaseBuilder(context.getApplicationContext(),
SortedDatabase.class, "unsorted_database").fallbackToDestructiveMigration().build();
}
return instanceSorted;
}
}
I tried to delete "fallbackToDestructiveMigration()", but I have a method "deleteAll", that shows error in this case:
viewModel.deleteAllDates();
viewModel.deleteAllUnsorted();
viewModel.deleteAllSorted();
Here is how I add data to SortedDatabase(that gets deleted):
if (choosedMethod.equals("Eat a frog")) {
for (int i = 0; i < eatAFrogList.size(); i++){
Unsorted unsorted = eatAFrogList.get(i);
String name = unsorted.getName();
String date = unsorted.getDate();
int timeBegin = unsorted.getTimeBegin();
boolean attach = unsorted.isAttach();
int category = unsorted.getCategory();
int duration = unsorted.getDuration();
String categoryChart = unsorted.getCategoryChart();
Sorted sorted = new Sorted(name, timeBegin, duration, category, attach, date,
categoryChart);
viewModel1.insertSorted(sorted);
}
I sort tasks of class Unsorted, stored in UnsortedDatabase, through algorithm and then add it to SortedDatabase.
My adapter to recyclerview that shows sorted data:
public class SortedAdapter extends RecyclerView.Adapter<SortedAdapter.SortedViewHolder> {
private List<Sorted> list = new ArrayList<>();
#NonNull
#Override
public SortedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks_layout , parent, false);
return new SortedAdapter.SortedViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull SortedViewHolder holder, int position) {
Sorted data = list.get(position);
holder.title.setText(data.getSortedName());
holder.date.setText(data.getSortedDate());
holder.category.setText(String.valueOf(data.getSortedCategory()));
holder.attach.setText(String.valueOf(data.isSortedAttach()));
holder.to.setText(String.valueOf(toTime(data.getSortedDuration() + data.getSortedTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getSortedTimeBegin())));
}
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return list.size();
}
class SortedViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;
SortedViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title);
date = itemView.findViewById(R.id.tv_date);
from = itemView.findViewById(R.id.tv_from2);
to = itemView.findViewById(R.id.tv_to2);
category = itemView.findViewById(R.id.tv_category);
attach = itemView.findViewById(R.id.tv_attach);
}
}
}
And, finally, activity, where data is shown:
public class ShowSortedActivity extends AppCompatActivity {
SortedViewModel viewModel;
AppPreferenceManager preferenceManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferenceManager = new AppPreferenceManager(this);
if (preferenceManager.getDarkModeState()){
setTheme(R.style.Dark);
}
else{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_show_sorted);
final SortedAdapter adapter = new SortedAdapter();
RecyclerView showSorted = findViewById(R.id.show_sorted);
showSorted.setLayoutManager(new LinearLayoutManager(this));
showSorted.setHasFixedSize(true);
showSorted.setAdapter(adapter);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle("Sorted");
Intent intent = getIntent();
String currentDate = intent.getStringExtra("value");
viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(SortedViewModel.class);
try {
viewModel.getSortedWhereDateIs(currentDate).observe(this, new Observer<List<Sorted>>() {
#Override
public void onChanged(List<Sorted> sorteds) {
adapter.setSortedData(sorteds);
}
});
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Maybe the data isn't deleted, but there is a problem with displaying it? I could't find my mistake... Thanks for any help.
I guess the problem was because of me creating two databases with the same name "unsorted_database". It seems to work now.
![](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;
}
I have an 4 array list which i used in my custom adapter class. I want it to be in descending form depending on their ratings. i used collection.sort(ratings.Collection.reverseOrder()); it works fine it is arranging the ratings in descending form depending on their ratings but the other array list retain the same. i want them to be specify depending on their position.
i am using this code.
Collections.sort(mRatings,Collections.reverseOrder());
adapterz = new SummaryAdapter(MapsActivity.this, mNames,
mAddress, mRatings, mDistance);
recyclerView.setAdapter(adapterz);
adapterz.notifyDataSetChanged();
I have edited my answer to purposely clear anyone. im sorry im not much familiar in java. so hmm you suggested ill work on with comparable i tried it but it doesnt work well how am i going to deal with it? this is where i add data in my array list. btw i am using google nearby places and this is i add place details to the respective array list.
in my GetNearbyPlace class
else if (MapsActivity.x == "pStore") {
for (int i = 0; i < nearbyPlaceList.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlaceList.get(i);
placeName = googlePlace.get("place_name");
vicinity = googlePlace.get("vicinity");
String rating = googlePlace.get("rating");
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String snippet = "Address: " + vicinity + "\n" +
// "Phone Number: " + formatted_phone_number + "\n" +
// "Website: " + url + "\n" +
"Place Rating: " + rating + "\n";
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName);
markerOptions.snippet(snippet);
markerOptions.icon
(BitmapDescriptorFactory.fromResource(R.drawable.ic_pstore));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
MapsActivity.mNames.add( googlePlace.get("place_name"));
MapsActivity.mAddress.add(googlePlace.get("vicinity"));
int x = 0;
try {
x = Integer.parseInt(googlePlace.get("rating"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
float results[] = new float[10];
Location.distanceBetween(MapsActivity.latitude,
MapsActivity.longitude,lat,lng,results);
int rate= 0;
try {
rate = new Integer(googlePlace.get("rating"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
MapsActivity.mRatings.add(rate);
MapsActivity.mDistance.add(results[0]);
and in my MainActivity
I declare arraylist as global
public static ArrayList<String> mNames = new ArrayList<>();
public static ArrayList<String> mAddress = new ArrayList<>();
public static ArrayList<Integer> mRatings = new ArrayList<>();
public static ArrayList<Float> mDistance = new ArrayList<>();
//and then added it in to the adapter
Collections.sort(mDistance);
adapterz = new SummaryAdapter(MapsActivity.this, mNames,
mAddress, mRatings, mDistance);
recyclerView.setAdapter(adapterz);
adapterz.notifyDataSetChanged();
//My adapter
public class SummaryAdapter extends
RecyclerView.Adapter<SummaryAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
//vars
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mAddress = new ArrayList<>();
private ArrayList<Integer> mRatings = new ArrayList<>();
private ArrayList<Float> mDistance = new ArrayList<>();
private Context mContext;
public SummaryAdapter(Context context, ArrayList<String> name, ArrayList<String> address , ArrayList<Integer> ratings , ArrayList<Float> distance ) {
this.mNames = name;
this.mAddress = address;
this.mRatings = ratings;
this.mDistance = distance;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.summaryadapter, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.name.setText(mNames.get(position));
holder.address.setText(mAddress.get(position));
holder.distance.setText("Distance: "+mDistance.get(position)+"meters");
Toast.makeText(mContext,mImage.toString(),Toast.LENGTH_LONG).show();
float w = 0;
try {
w = new Float(mRatings.get(position));
} catch (NumberFormatException e) {
e.printStackTrace();
}
holder.rtnbar.setRating(w);
}
#Override
public int getItemCount() {
return mNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name,address,distance;
RatingBar rtnbar;
ImageView img;
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
address = itemView.findViewById(R.id.addresslist);
name = itemView.findViewById(R.id.namelist);
distance = itemView.findViewById(R.id.distancelist);
img=itemView.findViewById(R.id.imagelist);
rtnbar=itemView.findViewById(R.id.ratinglist);
}
}
}
Question, how am i going to switch my array list items in to a custom class where in ill put on my array list like names,rating etc.
Take one class define all the variable like rating,name ,etc and that class pass into list and that list pass into adapter..
after that if your rating value as long then perfrom decending order sorting like below ..
Collections.sort(indexResponsesList, new Comparator<UserData>() {
#Override
public int compare(UserData userData, UserData t1) {
Long idea1 = new Long(userData.getCreatedAt());// here pass rating value.
Long idea2 = new Long(t1.getCreatedAt());// here pass rating value.
return idea2.compareTo(idea1);
}
});
if (indexItemAdapter != null)
indexItemAdapter.notifyDataSetChanged();
anb if integer then replace Long data type as integer.
Create a class like this:
public class Person implements Comparable<Person> {
private String mName;
private String mAddress;
private int mRating;
private int mDistance;
Person(String name, String address, int rating, int distance) {
this.mName = name;
this.mAddress = address;
this.mRating = rating;
this.mDistance = distance;
}
#Override
public int compareTo(Person p) {
return -Integer.valueOf(mRating).compareTo(p.mRating);
}
}
and store all your data in 1 array persons of Person objects.
Then you sort the array: Arrays.sort(persons); and use it in your adapter.
I have a custom class to data set User.java
public class User {
public int icon;
public String title;
public User(){
super();
}
public User(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
Also have a custom adapter UserAdapter.java
public class UserAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
User data[] = null;
public UserAdapter(Context context, int layoutResourceId, User[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.list_image);
holder.txtTitle = (TextView)row.findViewById(R.id.title);
row.setTag(holder);
}
else
{
holder = (UserHolder)row.getTag();
}
User User = data[position];
holder.txtTitle.setText(User.title);
holder.imgIcon.setImageResource(User.icon);
return row;
}
static class UserHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
I am trying to push data from webservice with the code
public User user_data[] = new User[500];
try {
JSONObject object_exc = response;
JSONArray jArray = object_exc.getJSONArray("exercise");
for (int i = 0; i < jArray.length(); i++) {
JSONObject object = jArray.getJSONObject(i);
user_data[i] = new User(R.drawable.nopic, object.getString("name"));
}
}catch (Exception e){
}
But it is returning null exception where as
User user_data[] = new User[]
{
new User(R.drawable.weather_cloudy, "Cloudy"),
new User(R.drawable.weather_showers, "Showers"),
new User(R.drawable.weather_snow, "Snow"),
new User(R.drawable.weather_storm, "Storm"),
new User(R.drawable.weather_sunny, "Sunny")
};
this is working fine. Please some one help
Try to use ArrayList instead of User[] array.
ArrayList<User> list = new ArrayList<User>();
To add a user to this list.
Just like:
list.add(new User(xxx, yyy));
IMHO there are a couple of problem in your code.
1 - Json file source
JSONArray jArray = object_exc.getJSONArray("exercise");
The constructor request a string that represent a json string. Obviously "exercise" is not a valid json. So you will never find "name" field..so the problem is here!!!
Improvements
2 - Using pure array structure
Maybe is better use an ArrayList is a better option for next manipulation data. (for example sorting!)
3 - object.getString(String abc)
I suggest you to use
object.optString("name", "no_name")
in this way you can put a default return value and avoid other problems. read this SO thread
JSON: the difference between getString() and optString()
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());
}
});