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());
Related
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.
I want to compare two ArrayList of objects and find the unmatching values from the second ArrayList based on the ids in the object.
For Example:
Person.java
private int id;
private String name;
private String place;
MainActivity.java:
ArrayList<Person> arrayList1 = new ArrayList<Person>();
arrayList1.add(new Person(1,"name","place"));
arrayList1.add(new Person(2,"name","place"));
arrayList1.add(new Person(3,"name","place"));
ArrayList<Person> arrayList2 = new ArrayList<Person>();
arrayList2.add(new Person(1,"name","place"));
arrayList2.add(new Person(3,"name","place"));
arrayList2.add(new Person(5,"name","place"));
arrayList2.add(new Person(6,"name","place"));
I want to compare the arrayList1, arrayList2 and need to find the unmatching values from the arrayList2.
I need the id values 5,6.
How can I do this?
You can use an inner loop, to check if the Person's id from arrayList2 corresponds to any Person id in the arrayList1. You'll need a flag to mark if some Person was found.
ArrayList<Integer> results = new ArrayList<>();
// Loop arrayList2 items
for (Person person2 : arrayList2) {
// Loop arrayList1 items
boolean found = false;
for (Person person1 : arrayList1) {
if (person2.id == person1.id) {
found = true;
}
}
if (!found) {
results.add(person2.id);
}
}
Look at the modifications to person class
public static class Person{
//setters and getters
#Override
public boolean equals(Object other) {
if (!(other instanceof Person)) {
return false;
}
Person that = (Person) other;
// Custom equality check here.
return this.getId() == that.getId();
}
}
Have overridden equals(Object other)
then simply do this
for (Person person : arrayList1) {
arrayList2.remove(person);
}
your answer is array list 2, it will only contain odd objects
You should iterate through the shortest ArrayList you have, so check which list is shorter and then iterate through all the indexes in that list against every index in the other list.
(This is assuming you don't have any duplicates in either list. If you do, you might want to return a list of all indexes found.)
arrayListChars=new ArrayList<>(); //[M,A,R,V,E,L]
arrayListAddChars=new ArrayList<>(); //[M,A,....coming values]
int count = 0;
for(int i=0;i
if(arrayListAddChars.get(i).equals(arrayListChars.get(i))){
count++;
}
else
{
break;
}
}
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.
Currently working on an app that takes results from a search, parses the JSON object returned, and then adds the resulting pieces into a few ArrayLists within a class created called VenueList.
Here is the method that receives the results from the service and parses the JSON:
private static List<String> getResultsFromJson(String json) {
ArrayList<String> resultList = new ArrayList<String>();
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
resultList.add(result.getString("text"));
}
}
catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
return resultList;
}
What results of this becomes a List variable call mResults (to clarify: mResults = getResultsFromJson(restResult);. That is then used, among other places, in the following loop that puts the results into an ArrayAdapter that is used for displaying them in a ListFragment:
for (String result : mResults) {
VenueList.addVenue(result, "HELLO WORLD");
adapter.add(result);
}
I also add the result to a class called VenueList that manages the results and makes them accessible for multiple views. It essentially just holds multiple ArrayLists that hold different types of details for each venue returned in the search. The method I use to add a venue to VenueList is below (and you can see it used in the for loop above):
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
I want the addVenue method to be able to take multiple arguments and update the VenueList class. Yet, when I call the addVenue method in the for loop, I can only pass it String result (from the parameters of the loop) and can't figure out how to pass it a second argument (which should also come from the JSON parsed by getResultsFromJson) so I've used "HELLO WORLD" as a placeholder for now.
I realize getResultsFromJson only has one list returned. I need to be able to take multiple elements from the JSON object that I parse, and then add them to VenueList in the right order.
So my questions are:
1) Given the getResultsFromJson method and the for loop, how can I use the addVenue() method as designed? How do I parse multiple elements from the JSON, and then add them to the VenueList at the same time? I plan on adding more arguments to it later on, but I assume if I can make it work with two, I can make it work with four or five.
2) If that's not possible, how should the getResultsFromJson, the for loop, and the addVenue method be redesigned to work properly together?
Please let me know if you need more detail or code - happy to provide. Thank you!
EDIT - Full VenueList class:
public class VenueList {
private static ArrayList<String> venueNames;
private static ArrayList<String> venueGeos;
public VenueList() {
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
}
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
public static String getVenueName(int position) {
return venueNames.get(position);
}
public static String getVenueGeo(int position) {
return venueGeos.get(position);
}
public static void clearList() {
venueNames.clear();
venueGeos.clear();
}
}
Clarification: I will have additional ArrayLists for each element of data that I want to store about a venue (phone number, address, etc etc)
1) I don't think methods getResultsFromJson(String json) and addVenue(String name, String geo) fit your needs.
2) I would consider rewriting method getResultsFromJson(String json) to something like this:
private static SortedMap<Integer, List<String>> getResultsFromJson(String json) {
Map<Integer, String> resultMap = new TreeMap<Integer, String>();
//...
return resultMap;
}
where the number of keys of your map should be equal to the number of objects you're extracting info, and each one of them will properly have their own list of items just in the right order you extract them.
With this approach you can certainly change your logic to something like this:
// grab your retuned map and get an entrySet, the just iterate trough it
SortedMap<Integer, String> result = returnedMap.entrySet();
for (Entry<Integer, String> result : entrySet) {
Integer key = result.getKey(); // use it if you need it
List<String> yourDesiredItems = result.getValue(); // explicitly shown to know how to get it
VenueList.addVenue(yourDesiredItems);
}
public static void addVenue(List<String> yourDesiredItems) {
// refactor here to iterate the items trough the list and save properly
//....
}
EDIT -- as you wish to avoid the go-between map i'm assuming you need nothing to return from the method
First i'm providing you with a solution to your requirements, then i'll provide you with some tips cause i see some things that could smplify your design.
To save VenueList things directly from getResultsFromJSON do something like this:
private static void getResultsFromJson(String json) {
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
//FOR EXAMPLE HERE IS WHERE YOU NEED TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then...
VenueList.addVenue(name, geo, ..., etc);
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
}
This implies that your addVenue method should know receive all params needed; as you can see this is just a way (that you can consider a workaround to your needs), however as i don't know all requirements that lead you to code this model, i will point to a few things you might consider:
1. If there's a reason for VenueList class to use everything static, consider doing this:
static{
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
//....
}
private VenueList(){
}
This way you won't need to get an instance every time and also will avoid null pointer exceptions when doing VenueList.addVenue(...) without previous instantiation.
2. Instead of having an ArrayList for every characteristic in VenueList class consider defining a model object for a Venue like this:
public class Venue{
String name;
String geo;
//... etc
public Venue(){
}
// ... getters & setters
}
then if you need that VenueList class you will just have a list o Venue objects (List<Venue>), this means that instead of calling the method addVenue, you will first create a brand new instance of Venue class and will call the setter method of each characteristic, as an example of the refactored for loop from the workaround i provided you you'd be using something like this:
List<Venue> myListOfVenues = new ArrayList<Venue>();
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
// THIS WOULD REMAIN THE SAME TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then instead of calling VenueList.addVenue(name, geo, ..., etc)...
Venue v = new Venue();
v.setName(name);
v.setGeo(geo);
// ...etc
myListOfVenues.add(v);
}
// Once you're done, set that List to VenueList class
VenueList.setVenueList(myListOfVenues);
So VenueList class would now have a single property List<Venue> venueList; and would suffer minor tweeks on methods getVenueName, etc... and everything would be more readable... i hope this helps you to get another approach to solve your problem, if i still don't make my point let me know and i'll try to help you out...
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);