How to find index in ArrayList<Class> (Android) - android

I use eclipse android
I need to index or object find in ArrayList
public class myclass
{
int id;
int count;
String value;
}
mainactivity
{
ArrayList<myclass> list = new ArrayList<myclass>();
myclass mc = new myclass();
mc.id=1;
mc.count=20;
mc.value="my value 1"
list.add(mc);
//add 100 record in list
//how can i this
int index = list.find(value="search value");
//or this
myclass founded = list.find(value="search value");
//or this
myclass founded2 = list.where(a => a.value="search value").first; //yes this is linq and lambda, but i cant linq in android
}
if I use for loop, I can find index but maybe arraylist has 1billion over record and I search 1000 values in arraylist
I dont want to use 1000 times for-loop in arraylist.
how can I this basicly

You can use indexOf()
int index = list.indexOf(object)

So if you want to find 1000 values inside your 1billion ArrayList record it is better not to use ArrayList here.
More preferable way for doing that is using HashMap<String, YourClass>.
Where first parameter is your id and second is element of your class.
You can easily found then element of your class by id. Approximately O(1).
If it is no matter how your values will be stored in ArrayList you can implements comparable interface in your class and support your collection in sorted way. So if your collection is sorted you can find your element with binary search.
You should use this version of binary search
Collections.binarySearch(List<? extends T> list, T object, Comparator<? super T> comparator)
So you can implement you custom compator to check if your object is equal to something that you are finding.

Related

Android Realm: Retrieve collection ids from realm Object

I have saved my User to the realm. When I query the user I get this object:
User{id=0, hairColor=Red, favoriteSongs=FavoriteSong#[16,17]}
When I want the list of favorite songs, realm makes it easy to get a list back:
mUser.getFavoriteSongs();
But I'd like to get an array of the user's favoriteSong ids. This will make it easy to pass in a bundle as an int[].
Is this possible in Realm?
I would propose you two options:
Create a helper responsible of iterate the list of Songs and return a list of ids.
class SongHelper {
public static List<Integer> getSongIds(List<Song> songs) {
List<Integer> songIds = new ArrayList<>();
for( Song song : songs )
songIds.add( song.getId() );
return songIds;
}
}
Override the getFavoriteSongs method and make it return List<Integer> instead of List<Song> or create an additional method for this in the User.
Option 1 is more elegant. You should always keep your model classes as clean as possible. In other words, just declare attributes, getter and setters without business logic.

How do I store multiple values in an array in Android?

For this example I have an array:
String[] books = new String[x];
I would like to store the id and title in each location:
books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"
I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:
btn.setText(regions[i].title)
Any suggestion on how to handle this would be great.
Do one thing, first create a bean class like BookBean.
Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option)
and then declare a ArrayList to store BookBean vale as of follow.
ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();
for(int i=0;i<=urSize;i++)
{
// create a object for BookBean
BookBean book =new BookBean();
book.setID("what ever");
book.setTitle("what ever");
bookArrayList.ass(book)
}
It is better to use Arraylist with custom class.
see this
class Book
{
String id,title;
/* Cunstructor to store data */
public Book(String id,String title)
{
this.id = id;
this.title = title;
}
}
//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");
btn.setText(bookList.get(i).title)
I think you have several options
Use a HashMap where you can use your id as key and value title
Define a class and keep id and title as attributes , define get and set methods.
Keep the objects of the class in a ArrayList

Adding items to Array List with specified objects

I am working in a translator kind of app and i need some help.
I have a class with getters and setters for my Array List objects. Each object has a phrase, a meaning, and usage.
so i have this to create my list:
ArrayList<PhraseCollection> IdiomsList = new ArrayList<PhraseCollection>();
now how do i add these objects to the list, each object containing the phrase, its meaning, and a use in a sentence?
For Example: The Layout would be something like this
Phrase
Kick the bucket
Meaning
When someone dies
Usage
My grandfather kicked the bucket
Thanks a lot
this is what i came up with that worked for me
private void loadIdioms() {
//creating new items in the list
Idiom i1 = new Idiom();
i1.setPhrase("Kick the bucket");
i1.setMeaning("When someone dies");
i1.setUsage("My old dog kicked the bucket");
idiomsList.add(i1);
}
ArrayList has a method call add() or add(ELEMENT,INDEX);
In order to add your objects you must first create them
PhraseCollection collection=new PhraseCollection();
then create the ArrayList by
ArrayList<PhraseCollection> list=new ArrayList<PhraseCollection>();
add them by :
list.add(collection);
Last if you want to render that in your ListView item, you must override the toString() in your PhraseCollection.
I suppose you would use the add(E) method (http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(E)).
Here is an example using your example provided.
public class Phrase {
public final String phrase, meaning, usage;
//TODO: implement getters?
public Phrase(String phrase, meaning, usage) {
this.phrase = phrase;
this.meaning = meaning;
this.usage = usage;
}
}
and use it like this:
// create the list
ArrayList<Phrase> idiomsList = new ArrayList<Phrase>();
// create the phrase to add
Phrase kick = new Phrase("kick the bucket", "When someone dies", "My grandfather kicked the bucket");
// add the phrase to the list
idiomsList.add(kick);

sorting custom object array on two fields

I'm sorting an array of custom objects (ListData[]) on two fields. I want it to be sorted by theme, and them by name. I thought i made a nice comparator in the custom object class and that i could use Arrays.sort(ld) to make my code working and sorting my array. But apparently im doing something wrong...
my custom object:
public class ListData implements Comparable<ListData>{
public int venueID;
public String name;
public String photoUrl;
public String tip;
public String theme;
#Override
public int compareTo(ListData ld0) {
return this.venueID- ld0.venueID;
}
public static Comparator<ListData> ListDataThemeAndNameComparator = new Comparator<ListData>() {
#Override
public int compare(ListData ld1, ListData ld2) {
String compareTheme1 = ld1.theme.toUpperCase();
String compareTheme2= ld2.theme.toUpperCase();
String compareName1 = ld1.name.toUpperCase();
String compareName2= ld2.name.toUpperCase();
//ascending
int comp = compareTheme1.compareTo(compareTheme2); // comp themes
if(comp==0){ // same theme
comp= compareName1.compareTo(compareName2); // compare names
}
return comp;
}
};
}
And in my main activity i have:
ListData ld[]= new ListData[jsonResponse.size()];
(some code filling my ListData array)
Arrays.sort(ld, ListData.ListDataThemeAndNameComparator); // compare by theme and then by name
Does anyone know what i'm doing wrong?
I edited my code But still it fails, now on a nullpointerexception on the compareTheme1 = ld1.theme.toUpperCase();. But i am sure my array is not empty, i logged it the line before sorting it and its filled with about 500 items.
Your ListData object should implements Comparable not Comparator interface.
EDIT:
To make things clear, you can sort an array by Array.sort(). To make custom sort, you can specify your comparator in Array.sort(), if you don't do that, array will be sorted in natural order which you can define by implementing Comparable interface. So you have two options how to custom sort:
by using custom comparator and specifying it in Array.sort()
by implementing Comparable interface to your items
I would suggest you to go with implementing Comparable. You save memory by not creating new comparator objects and Comparator is useful if you are comparing objects of different types which is not your case.

Bundle of array of arraylist

How can I put an array of arrayList into a Bundle?
ArrayList < myObjects >[] mElements;
Make YourObject implement the Parcelable interface, then use bundle.putParcelableArraylist(theParcelableArraylist).
Edit: whoops misread the question. Why do you want to save an array of arraylist? If its for persisting in an orientation change, maybe you want to use onRetainNonConfigurationInstance instead?
Edit 2: Ok, here goes. Create a new Wrapper class that implements Parcelable (note that myObjects also have to be parcelable). The writeToParcel method will look something like this:
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mElements.length);
for(ArrayList<MyObject> element : mElements) {
dest.writeParcelableArray(element.toArray(new MyObject[0]), flags);
}
}
And the constructor:
private Wrapper(Parcel in) {
int length = in.readInt();
//Declare list
for (int i = 0; i < length; i++) {
MyObject[] read = in.readParcelableArray(Wrapper.class.getClassLoader());
//add to list
}
}
Not possible using bundle, as bundle allows arraylist of primitives only...
Try to use parcleable or application level data or static variable (bad practice).
If your objects support serialization, marked with the Serializable interface, then you should be able to use bundle.putSerializable.
ArrayList supports Serializable , but I'm not sure about a plain array.
I just use putSerializable(myarraylistofstuff) and then I get back with a cast using get(), you just need to silence the unchecked warning. I suspect (correct me if wrong) you can pass any object faking it as Serializable, as long you stay in the same process it will pass the object reference. This approach obviously does not work when passing data to another application.
EDIT: Currently android passes the reference only between fragment, I've tried to pass an arbitrary object to an Activity, it worked but the object was different, same test using arguments of Fragment showed same Object instead.
Anyway it deserializes and serializes fine my Object, if you have a lot of objects it's better to use Parcel instead

Categories

Resources