How to add elements to multidimensional arrayList - android

If I create a class such as
public class record{
int index;
String name;
}
and then an ArrayList
ArrayList<.record> members = new ArrayList<.record>();
How do I add individual elements?
I thought there would be something like
members[x].index.add(someintegervalue);
members[x].name.add(somestringvalue);
and then a similar command to set new values if I wanted to change existing values.
Is there a simple way to do this?
Edit: This question has been answered, however it led to another problem. How to pass an ArrayList pointer to a function().

ArrayList<record> members = new ArrayList<record>();
//to add a member
member obMember = new member();
obMember.index = 0;
obMember.name="name";
members.add(obMember);
//to update get child of position cast it and update
member newMember = (menber)members.get(position);
newMember.name="newName";
member.set(location, newMember);

try like this
public class Record{
public int index;
public String name;
}
Record myRecord = new Record();
myRecord.index = someintegervalue;
myRecord.name = somestringvalue;
then add it to arraylist by
members.add(myRecord); or members.add(x , myRecord );
add adding it to x potion the you can get
Record record = members.get(x);

Related

ArrayList<HashMap<String,String>> Overwrite the items in list [duplicate]

I'm adding three different objects to an ArrayList, but the list contains three copies of the last object I added.
For example:
for (Foo f : list) {
System.out.println(f.getValue());
}
Expected:
0
1
2
Actual:
2
2
2
What mistake have I made?
Note: this is designed to be a canonical Q&A for the numerous similar issues that arise on this site.
This problem has two typical causes:
Static fields used by the objects you stored in the list
Accidentally adding the same object to the list
Static Fields
If the objects in your list store data in static fields, each object in your list will appear to be the same because they hold the same values. Consider the class below:
public class Foo {
private static int value;
// ^^^^^^------------ - Here's the problem!
public Foo(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In that example, there is only one int value which is shared between all instances of Foo because it is declared static. (See "Understanding Class Members" tutorial.)
If you add multiple Foo objects to a list using the code below, each instance will return 3 from a call to getValue():
for (int i = 0; i < 4; i++) {
list.add(new Foo(i));
}
The solution is simple - don't use the static keywords for fields in your class unless you actually want the values shared between every instance of that class.
Adding the Same Object
If you add a temporary variable to a list, you must create a new instance of the object you are adding, each time you loop. Consider the following erroneous code snippet:
List<Foo> list = new ArrayList<Foo>();
Foo tmp = new Foo();
for (int i = 0; i < 3; i++) {
tmp.setValue(i);
list.add(tmp);
}
Here, the tmp object was constructed outside the loop. As a result, the same object instance is being added to the list three times. The instance will hold the value 2, because that was the value passed during the last call to setValue().
To fix this, just move the object construction inside the loop:
List<Foo> list = new ArrayList<Foo>();
for (int i = 0; i < 3; i++) {
Foo tmp = new Foo(); // <-- fresh instance!
tmp.setValue(i);
list.add(tmp);
}
Your problem is with the type static which requires a new initialization every time a loop is iterated. If you are in a loop it is better to keep the concrete initialization inside the loop.
List<Object> objects = new ArrayList<>();
for (int i = 0; i < length_you_want; i++) {
SomeStaticClass myStaticObject = new SomeStaticClass();
myStaticObject.tag = i;
// Do stuff with myStaticObject
objects.add(myStaticClass);
}
Instead of:
List<Object> objects = new ArrayList<>();
SomeStaticClass myStaticObject = new SomeStaticClass();
for (int i = 0; i < length; i++) {
myStaticObject.tag = i;
// Do stuff with myStaticObject
objects.add(myStaticClass);
// This will duplicate the last item "length" times
}
Here tag is a variable in SomeStaticClass to check the validity of the above snippet; you can have some other implementation based on your use case.
Had the same trouble with the calendar instance.
Wrong code:
Calendar myCalendar = Calendar.getInstance();
for (int days = 0; days < daysPerWeek; days++) {
myCalendar.add(Calendar.DAY_OF_YEAR, 1);
// In the next line lies the error
Calendar newCal = myCalendar;
calendarList.add(newCal);
}
You have to create a NEW object of the calendar, which can be done with calendar.clone();
Calendar myCalendar = Calendar.getInstance();
for (int days = 0; days < daysPerWeek; days++) {
myCalendar.add(Calendar.DAY_OF_YEAR, 1);
// RIGHT WAY
Calendar newCal = (Calendar) myCalendar.clone();
calendarList.add(newCal);
}
Every time you add an object to an ArrayList, make sure you add a new object and not already used object. What is happening is that when you add the same 1 copy of object, that same object is added to different positions in an ArrayList. And when you make change to one, because the same copy is added over and over again, all the copies get affected.
For example,
Say you have an ArrayList like this:
ArrayList<Card> list = new ArrayList<Card>();
Card c = new Card();
Now if you add this Card c to list, it will be added no problem. It will be saved at location 0. But, when you save the same Card c in the list, it will be saved at location 1. So remember that you added same 1 object to two different locations in a list. Now if you make a change that Card object c, the objects in a list at location 0 and 1 will also reflect that change, because they are the same object.
One solution would be to make a constructor in Card class, that accepts another Card object. Then in that constructor, you can set the properties like this:
public Card(Card c){
this.property1 = c.getProperty1();
this.property2 = c.getProperty2();
... //add all the properties that you have in this class Card this way
}
And lets say you have the same 1 copy of Card, so at the time of adding a new object, you can do this:
list.add(new Card(nameOfTheCardObjectThatYouWantADifferentCopyOf));
It can also consequence of using the same reference instead of using a new one.
List<Foo> list = new ArrayList<Foo>();
setdata();
......
public void setdata(int i) {
Foo temp = new Foo();
tmp.setValue(i);
list.add(tmp);
}
Instead of:
List<Foo> list = new ArrayList<Foo>();
Foo temp = new Foo();
setdata();
......
public void setdata(int i) {
tmp.setValue(i);
list.add(tmp);
}

How to add value from Model class to ArrayList

I am trying to add into my ArrayList some value of 2 number sum. In Model class i have getters and setters, constructor and Method witch calculates two number sum, set and return the new result. I have no idea how to get the result and add the result into ArrayList
Model class:
public class SumOfTwoNumbers {
private String result;
private Context context;
public SumOfTwoNumbers (String result) {
this.result = result;
}
public SumOfTwoNumbers (int x, int y){
int res = x + y;
result = String.valueOf(res);
setResult(result);
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
In Activity I do something like this and i know that, it is wrong:
SumOfTwoNumbers sum = new SumOfTwoNumbers();
ArrayList<SumOfTwoNumbers> arrayList = new ArrayList<>();
arrayList.add(sum.getResult());
I would like to get result and add it to ArrayList.
Can someone tell me in what i have to think?
Hope i explaned well my problem.
Thanks in advance!
Your implementation seems wrong. As model class should always be plain java text. But here you are storing context also, which possibly cause memory leaks.
And, in arrayList part you add only those objects to arrayList for which you have made array list.
ArrayList<SomeClass> list = new ArrayList<>();
AnotherClass a = new AnotherClass();
list.add(a); // this is completely wrong;
SomeClass b= new SomeClass();
list.add(b); //this is perfectly fine
Hope you got your answer.
I'm having a hard time understanding your question, but I guess you're looking to create a list like this? (If your getResult method returns an Integer)
SumOfTwoNumbers sum = new SumOfTwoNumbers(1,4);
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(sum.getResult());

Sorting adapter on particular array

I have a collection of object assigned to an adapter set to a listview. I know how to sort an adapter value when it contains single object. My question is how do I sort the collection only on the data datatype. Below is my collection
you = new MyVideoAdapter(getActivity(),vDancers,video, vName, vDanceStyle, vOwner, dCountry, vPic, vCreated, fullname,
vLikes,vComments, vViews,vRepost, objectID, nLikes, nComments, nRepost, vUserID, postType);
//you.comp
listView.setAdapter(you);
I want to sort this adapter (you) by the vCreated which is an array of dates. Thanks in advance for any help.
For those looking for a solution, this is how I went about it (I don't know if its the best solution but it does work for my case).
1. Instead of populating the adapter with the individual arrays, I created an ArrayList and populated it with my arrays.I sorted it using compareTo().
public class Items implements Comparable<Items>{
private final Number vLikes; private final Number vComments; private final Number vRepost; private final Number vViews;
private final Date vCreated;
public Items(Number vLikes, Number vComments, Number vViews, Number vRepost, Date created) {
this.vCreated = vCreated;
this.fullname = fullname;
this.vLikes = vLikes;
this.vComments = vComments;
this.vViews = vViews;
this.vRepost = vRepost;
}
#Override
public int compareTo(Items o) {
if (getvCreated() == null || o.getvCreated() == null)
return 0;
return o.getvCreated().compareTo(getvCreated());
}
public Number getvLikes() {
return vLikes;
}
public Number getvComments() {
return vComments;
}
public Number getvViews() {
return vViews;
}
public Number getvRepost() {
return vRepost;
}
public Date getvCreated() {
return vCreated;
}
}
2. I then sort the arraylist using the date column and using Collections to apply the sorting.
List<Items> myList = new ArrayList<Items>();
Items item = new Items(a,b,c,d);//a, b, are my variables
myList.add(item);
3. I populated my adapter with the sorted arraylist.
Collections.sort(myList);
you = new MyAdapter(getActivity(), myList);
I hope this helps.

Store Image and Text in one datatype android

I would like to know a way to store an image and associated text in something like a List. I tried doing something like this
List<NameValuePair>cars = new ArrayList<NameValuePair>();
cars.add(new BasicNameValuePair("Hyundai Elantra",Integer.toString(R.drawable.hyundai_elantra)));
I know this is wrong but I'm posting it so you get an idea of what I'm trying to achieve.
It looks like the best thing for you would be to create a custom class called Car to store each car, and then create an ArrayList<Car> to store the data.
Here is what your Car class would look like:
public class Car
{
public String type;
public int imageID;
public Car(String t, int i)
{
type = t;
imageID = i;
}
public String toString()
{
return type + " " + String.valueOf(imageID);
}
}
Then you would declare the ArrayList, and add values:
ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car("Hyundai Elantra", R.drawable.hyundai_elantra));
carList.add(new Car("Lexus RX350", R.drawable.lexus_rx350));
Then, you could iterate through the list when you want to populate your UI:
for (Car c : carList){
String s = c.type;
int image = c.imageID;
//use the values.......
}
Note that you could use this ArrayList as the data source for a custom adapter for displaying the text and images in a ListView, if that's what you're looking to do.
you can create a class named NameValue with Textand Image and you can declare an array list as follows
List<NameValue >cars = new ArrayList<NameValue >();

Randomize different ArrayList to get a value

I searched for related questions but didn´t find a solution (at least i don´t know if i named it correctly)
So, i have two ArrayLists and i would like to randomize all of them to get a value:
public class ListBox {
public static ArrayList listOne(){
ArrayList<Lists> listOne = new ArrayList<>();
listOne.add(new Item("Text One"));
listOne.add(new Item("Text Two"));
return listOne;
}
public static ArrayList listTwo(){
ArrayList<Lists> listTwo = new ArrayList<>();
listTwo.add(new Item("Text Three"));
listTwo.add(new Item("Text Four"));
return listTwo;
}
}
in other activity:
public void buttonClick(View view){
ArrayList<Lists> algumasListas = ListBox.listOne();
...
}
This is where i shuffle it
public class ListMixer extends ListBox{
public ArrayList<Lists> listas = null;
public ListMixer(ArrayList<Lists> listas ) {
this.listas = listas;
}
protected String mixList(){
Double randomNumber = new Double(Math.random() * listas.size());
int randomNum = randomNumber.intValue();
Lista lista= listas.get(randomNum);
String listaString2 = String.valueOf(lista);
String message = ("This is your list: " + listas);
return message;
}
}
my desired output would be one of the four listItems.
Appreciate the help!
Merge arrays into single one of size N.
Choose a random number in range 0..N-1.
Choose an element by index.
The first bug I'm seeing in your code is that listOne() returns object listTwo when called, which doesn't exist. It probably shouldn't even compile, unless something funky is going on with global scope variables.
The following code should do what you want by merging the two lists into one and then returning a random object from them.
public Object randomFromList(List<Object> listOne, List<Object> listTwo){
List<Object> bigList = new ArrayList<Object>(listOne.size() + listTwo.size());
bigList.addAll(listOne);
bigList.addAll(listTwo);
return bigList.get(new Random().nextInt(bigList.size()));
}
For optimization, if you call this a lot, I would save the Random() object outside of the method to avoid instantiating it every time you make the call.

Categories

Resources