Randomize different ArrayList to get a value - android

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.

Related

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.

Parsing JSON then adding multiple strings to an ArrayList

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...

How to add elements to multidimensional arrayList

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

Android, Null Pointer Exception to Data that isn't null

I'm writing an app for android that needs to parse data from an XML file. I've never come across an error like this that is so impossibly hard to track down. Or maybe my brain just stopped working. That happens. XML file is of the form:
<?xml version="1.0" encoding="iso-8859-1"?>
<memberRoster>
<agent>
<agentInfo1>...</agentInfo1>
<agentInfo2>...</agentInfo2>
...
</agent>
<agent>
...
</agent>
...
</memberRoster>
So far it's working well, except for some random bits of fun!
Every now and then it will throw a NullPointerException. I did some more digging and found out that there are THREE "agents" (out of 800) with "supposedly" null data. I checked the XML file and the data is there, there are no illegal characters, etc. It is the same three "agents" every time. The program parses other entries before and after these "null" "agents". Also of note is that not all "agentInfo" fields in the ArrayList come up null; example, one of the entries has 7 of the 8 entries as null, with the 8th one non-null, another has only one null with the last 7 non-null.
I'm parsing the data in to an ArrayList from the XML file, and like I mentioned before, it works flawlessly until it comes to those three specific entries in the XML file.
I'm sorry I can't give much more info than that, the data is sensitive to our members.
EDIT:
Sorry! I knew I was forgetting something! :)
Some code from my XMLHandler.java class:
public void characters(char[] ch, int start, int length)
if(this.in_mr_agentNrdsId) {
agent[0] = ch.toString();
}
else if(this.in_mr_agentFirstName) {
agent[1] = ch.toString();
}
else if(this.in_mr_agentLastName) {
agent[2] = ch.toString();
}
else if(this.in_mr_agentPhone) {
agent[3] = ch.toString();
}
else if(this.in_mr_agentEmail) {
agent[4] = ch.toString();
}
else if(this.in_mr_agentOfficeName) {
agent[5] = ch.toString();
}
else if(this.in_mr_agentOfficePhone) {
agent[6] = ch.toString();
}
else if(this.in_mr_agentType) {
agent[7] = ch.toString();
pds.setMemberRoster(agent);
agent = new String[8];
}
PDS is an object of type ParsedDataSet, which is just a simple class containing the ArrayList objects and a few getter and setter methods:
public class ParsedDataSet {
private ArrayList agentOpenHouses = new ArrayList();
private ArrayList calendarOfEvents = new ArrayList();
private ArrayList latestStatistics = new ArrayList();
private ArrayList memberRoster = new ArrayList();
public ArrayList<String[]> getAgentOpenHouses() {
return agentOpenHouses;
}
public ArrayList<String[]> getCalendarOfEvents() {
return calendarOfEvents;
}
public ArrayList<String[]> getLatestStatistics() {
return latestStatistics;
}
public ArrayList<String[]> getMemberRoster() {
return memberRoster;
}
public void setAgentOpenHouses(String[] agentOpenHousesItem) {
this.agentOpenHouses.add(agentOpenHousesItem);
}
public void setCalendarOfEvents(String[] calendarOfEventsItem) {
this.calendarOfEvents.add(calendarOfEventsItem);
}
public void setLatestStatistics(String[] latestStatisticsItem) {
this.latestStatistics.add(latestStatisticsItem);
}
public void setMemberRoster(String[] memberRosterItem) {
this.memberRoster.add(memberRosterItem);
}
} // end class ParsedDataSet
You could throw an if statement into your assignements and reassign any caught 'NULL' or empty strings into a zero value or just reassign as variable = "" in your code.
For example:
if (agentInfo1 == NULL) {
agentInfo1 = "" || agentInfo1 = 0; //Depending on what your variables are
}
Try putting try catch loop in code to find where the error is happening, then, pinpoint the exact part of code that is giving this error, there do null checks before proceeding. This is based on best practices of software development, rather than a fix for you.
Alternatively, you can makes sure on server side that there are no "null" values, maybe by giving dummy value like "EMPTY_STRING". This is especially relevant if your app is already shipped and you cant make any client code changes.

Categories

Resources