Arraylist of String arrays not appending? - java

I have created 3 arraylist which have a array of another type:
ArrayList<String[]> arrayListString = new ArrayList<String[]>();
ArrayList<int[]> arrayListInt = new ArrayList<int[]>();
ArrayList<double[]> arrayListDouble = new ArrayList<double[]>();
I am getting information from an api call, which I make from calling the below function. All I need to do is to append the arraylist so it can be redrawn with new item and the previous items to implement infinite scrolling. But now, when I make a second api call, I get the new items, I can even store them in new String arrays but I just can't append them to the arraylist. I have no idea why this is happening. The arraylist always contains the first api call string array and never gets updated. Can you please tell me where I am going wrong??
public void productListingApiCall(int i) {
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(base_url).setLogLevel(RestAdapter.LogLevel.FULL).build();
final ProductListingApi productListingApi =
restAdapter.create(ProductListingApi.class);
productListingApi.getFeed(file, operation_condition, search_string_condition, minprice_condition, maxprice_condition, mincusratings_condition,
maxcusratings_condition, discount_condition, catids_condition, brands_condition, affids_condition, start_row_condition, "5",
orderby_condition, sortby_condition, new Callback<ProductListingPojo>() {
#Override
public void success(ProductListingPojo productListingPojo, Response response) {
final ProductListingPojo product = productListingPojo;
new Thread(new Runnable() {
#Override
public void run() {
String[] t = Arrays.copyOf(product.getTitle(),
product.getTitle().length);
int[] p = Arrays.copyOf(product.getSellingprice(),
product.getSellingprice().length);
int[] m = Arrays.copyOf(product.getMrp(),
product.getMrp().length);
int[] d = Arrays.copyOf(product.getDiscountpercent(),
product.getDiscountpercent().length);
String[] i = Arrays.copyOf(product.getProductimageSmall1(),
product.getProductimageSmall1().length);
String[] title = new String[5];
String[] image = new String[5];
int[] price = new int[5];
int[] mrp = new int[5];
int[] discount = new int[5];
title = t;
price = p;
mrp = m;
discount = d;
image = i;
arrayListString.add(title);
arrayListString.add(image);
arrayListInt.add(price);
arrayListInt.add(mrp);
arrayListInt.add(discount);
Log.e("t", Arrays.toString(t));
Log.e("pp", Arrays.toString(p));
Log.e("m", Arrays.toString(m));
Log.e("d", Arrays.toString(d));
Log.e("i", Arrays.toString(i));
Log.e("ttt", Arrays.toString(title));
Log.e("pppp", Arrays.toString(price));
Log.e("mmm", Arrays.toString(mrp));
Log.e("ddd", Arrays.toString(discount));
Log.e("iii", Arrays.toString(image));
Log.e("tttttt", Arrays.toString(arrayListString.get(0)));
Log.e("ppppppp", Arrays.toString(arrayListInt.get(0)));
Log.e("mmmmmm", Arrays.toString(arrayListInt.get(1)));
Log.e("dddddd", Arrays.toString(arrayListInt.get(2)));
Log.e("iiiiii", Arrays.toString(arrayListString.get(1)));
}
}).run();
setAdapter();
}
#Override
public void failure(RetrofitError error) {
tv_title_header.setText(error.getMessage());
Log.e("error", error.getMessage());
}
});
}

With this code
Log.e("tttttt", Arrays.toString(arrayListString.get(0)));
Log.e("ppppppp", Arrays.toString(arrayListInt.get(0)));
Log.e("mmmmmm", Arrays.toString(arrayListInt.get(1)));
Log.e("dddddd", Arrays.toString(arrayListInt.get(2)));
Log.e("iiiiii", Arrays.toString(arrayListString.get(1)));
you are always looking at the first values which were added to the arrayLists. I suspect that the second time, if you would do
Log.e("tttttt", Arrays.toString(arrayListString.get(2)));
you will get the titles belonging to the 2nd api call. So you have to keep a counter somewhere which tells you if it is the 1st, 2nd, 3rd, ... call to the API.
However, I suggest you store the data received from the API in a different way. Using Lists is good, but you can make lists of every class you like, including your own. So if you create a DataApi class like this:
public class ApiData {
public String[] title, image;
int[] price, mrp, discount;
}
and replace the array lists you currently have with
private List<ApiData> arrayListData = new ArrayList<ApiData>();
then, you can store the data in it like this:
#Override
public void run() {
ApiData data = new ApiData();
data.title = Arrays.copyOf(product.getTitle(), product.getTitle().length);
...
arrayListData.add(data);
When you need the titles of the first api call, you just use arrayListData.get(0).title.
(for bonus points, encapsulate the public fields in the ApiData class).

Related

How do I import a populated ready-made ArrayList from another class in java?

I'm working with a large set of imported data and retrieving certain parts of it in the main method with 2 classes(WeatherStation, WeatherReading).The data is temperature readings at loads of weather stations(station id, name, lat, lon, year, time, temp etc) I made a third class (SoloSiteIds) whose sole purpose was to return a whole and complete ArrayList of the site ids with no duplication. But I cannot import the ArrayList from the other class into my main method. My SoloSiteIds class looks like this:
public class SoloSiteIds {
static ArrayList <Integer> siteIds = new ArrayList <Integer>();
public SoloSiteIds() {
}
public SoloSiteIds( ArrayList <Integer> siteIds) {
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ",
String siteid = elements[0]; // convert all the site id's at index 0 to integers
int id = Integer.parseInt(siteid);
if(!siteIds.contains(id)) {
siteIds.add(id);
}
this.siteIds=siteIds;
}
}
}
public static ArrayList<Integer> getSiteIds() {
return siteIds;
}
public ArrayList<Integer> setSiteIds(ArrayList<Integer> siteIds) {
return this.siteIds = siteIds;
}
}
The main method where I am trying to import the ArrayList "siteIds" looks like this:
WeatherStation thisStation = new WeatherStation (id, name, lat, lon);
WeatherReading thisReading = new WeatherReading(year, month, date, hour, windSpeed, temp);
SoloSiteIds siteList= new SoloSiteIds();
String[] weatherData = WeatherData.getData();{ // get the weather data
for (int i = 1; i < weatherData.length; i++) {
String line = weatherData[i];
String[] elements = line.split(","); // Split the data at ","
String siteid = elements[0]; // convert all the site id's at index 0 to integers
id = Integer.parseInt(siteid);
thisStation.setId(id);
thisStation.setName(elements[1]);
//parse the different elements into different data types
String stringLat = elements[2];
lat= Double.parseDouble(stringLat);
lat = thisStation.setLat(lat);
lat=thisStation.setLat(lat);
String stringLon = elements[3];
lon= Double.parseDouble(stringLon);
lat = thisStation.setLon(lon);
lat=thisStation.setLon(lon);
String stringTemp=elements[9];
temp=Double.parseDouble(stringTemp);
temp=thisReading.setTemp(temp);
Only the top part is relevant. I have tried lots of different variation of .set and .get using "thisList" instance and a new ArrayList like
ArrayList<Integer> siteIds = thisList.setSiteIds();
ArrayList<Integer> siteIds= SoloSiteIds.getSiteIds();
thisList=Siteids.setSiteIds();
thisList=SingleSoloSites.setSiteIds();
etc etc. This might look stupid but im just showing Ive tried numerous things and i am stuck
Thanks
I believe your problem is that you are initializing siteIds as an empty Arry list but you are not setting the data in a static way (the set Method is not static).
As far as I am aware of your situation, I belive that the SoloSiteIds class is unnescessary. I would solve your problem with an ArrayList declared in your main class and initialize with a getSoleIds() method also declared in your main class.
The getSoleIds() Method should contain the code currently in the SoleSiteIds initializer.

ArrayList<String[]> won't add more than one item

I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData;
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData = new ArrayList<String[]>();
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!
you clear out foodData every time you call createFood remove this line:
foodData = new ArrayList();
and move the initialization to a static level , like this:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
Every time you call createFood(String[] foodArray) you create a new List instead of just adding the incoming item to the existing list.
Create the ArrayList in a different place and remove the line from the createFood method and it should work fine.
Worked like a charm. Man I don't know how I missed that... I guess when you look at the same problem for too long you miss the obvious. Thanks guys!

How to get String[] from ArrayList<String[]>, I want to actually get String at index 0 from ArrayList<String[]>?

I have a Class
public class DataRatesString {
private String[] ab1 = {"Auto moto sdhv davjdn adadk", "Rs. 355"} ;
private String[] ab2 = {"sjg atoiu ", "Rs. 200"} ;
private String[] ab3 = {"go to UTOP atup auto", "Rs. 3279"} ;
private String[] ab4 = {"Hid to putho", "Rs. 2424"} ;
private String[] abo5 = {"pithoo to bittu", "Rs. 8457"} ;
private ArrayList<String[]> abCollection = new ArrayList<>();
public void setAbCollection() {
abCollection.add(ab1);
abCollection.add(ab2);
abCollection.add(ab3);
abCollection.add(ab4);
abCollection.add(ab5);
}
public ArrayList<String[]> getAbCollection(){
return abCollection;
}
}
I have another class from which I am calling the list
DataRatesString dataRatesString = new DataRatesString();
dataRatesString.setAbCollection();
ArrayList<String[]> ratesarray = dataRatesString.getAbCollection();
Now I want to get all the strings at position 0 of the Arraylist String[]
I have created a method in the same class but since I am new to java I am unable to figure out exactly how to do it.
This is the method that I tried to make
private List<String> getRatesItemNamelist(){
String[] arraylist;
ArrayList<String> list = new ArrayList<>();
arraylist = new String[ratesarray.size()];
for (int i = 0; i < ratesarray.size(); i++) {
arraylist = ratesarray.get(i);
}
list.add(0, arraylist[arraylist.length]);
return list;
}
This is not working.
Try this:
private List<String> getRatesItemNamelist(){
List<String> list = new ArrayList<>();
for (String[] rates : ratesarray) {
list.add(rates[0]);
}
return list;
}
Here in the for loop, rates[0] will get the first String from the String[] array for each element in ratesarray ArrayList.
So the getRatesItemNamelist() function will return a list of String at index 0 from ArrayList ratesarray.
If i understood properly, you want all arraylist data at position 0. but i don't think you can achieve. even you want you have to add string in multiple arraylist and each string add in at 0 position respectively.
why not try to make code simpler something like this
List<String> data = new ArrayList();
data.add("demo1");
data.add("demo2");
.......
Fetching data at 0 position, you could do this
data.get(0);
Fetch all data, you could use for each loop
for(String s: data){
// here is you each position's data as string
}

split an array list into multiple lists in java

I have an array list which when populated has a key and a value I want to know if there is a way of splitting it on repeating keys for example my current data is like this:
[RoleID_123.0, UserHandel_tom, Password_12345.0, prevPassword_null, userCaption_thomas, Email_tom#tom.tom, RoleID_124.0, UserHandel_dave, Password_ghadf, prevPassword_sdfsd, userCaption_david, Email_dave#dave.dave, RoleID_125.0, UserHandel_trevor, Password_tre, prevPassword_null, userCaption_trev, Email_trev#trev.trev]
I want it to come out more like this:
[RoleID_123.0, UserHandel_tom, Password_12345.0, prevPassword_null, userCaption_thomas, Email_tom#tom.tom]
[RoleID_124.0, UserHandel_dave, Password_ghadf, prevPassword_sdfsd, userCaption_david, Email_dave#dave.dave]
[RoleID_125.0, UserHandel_trevor, Password_tre, prevPassword_null, userCaption_trev, Email_trev#trev.trev]
Is there a way to split it on say role id or am I going about this the wrong way?
You can try by using HashMap
private static class MyItemHashMap extends HashMap {
public Item add(Item item) {
get(item).add(item);
return item;
}
public List get(Item key) {
List list = (List) get(createItemKey((Item) key));
return list == null ? createItemEntry((Item) key) : list;
}
private List createItemEntry(Item item) {
List list = new ArrayList();
put(createItemKey(item), list);
return list;
}
private Object createItemKey(Item item) {
return item.getSplitterProperty();
}
}
public static void main(String[] args) {
MyItemHashMap itemMapped = new MyItemHashMap();
List items = Arrays.asList(new Object[]{new Item("A"), new Item("B"),
new Item("C")});
for (Iterator iter = items.iterator(); iter.hasNext();) {
Item item = (Item) iter.next();
itemMapped.add(item);
}
}
If it is an ArrayList, there is no built-in function to split data like this; you will have to do it manually. If you know the number of consecutive fields that make a single structure, this shouldn't be too hard; something like this:
// 6 because there are 6 fields
for (int i = 0; i < arrayList.size(); i = i + 6) {
List thisList = arrayList.subList(i, i + 5);
// ... Now do whatever you want with thisList - it contains one structure.
}
If the number of fields can change then you'll have to do something a little more dynamic and loop through looking for a RoleID field, for example.
I'd use a HashMap to seperate the data instead of one long ArrayList ( you shouldn't have stored the data like this in the first instance )
HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>>;
// For each list:
ArrayList<String> arr = new ArrayList<String>;
arr.add("each element");
hm.put("RoleID_123.0", arr);
This way you will end up with a three dimensional structure with a key ( "RoleID..." ) pointing to its child elements.
Try this
String[] str=new String[]{"RoleID_123.0", "UserHandel_tom", "Password_12345.0", "prevPassword_null", "userCaption_thomas", "Email_tom#tom.tom", "RoleID_124.0", "UserHandel_dave", "Password_ghadf", "prevPassword_sdfsd", "userCaption_david", "Email_dave#dave.dave", "RoleID_125.0", "UserHandel_trevor", "Password_tre", "prevPassword_null", "userCaption_trev", "Email_trev#trev.trev"};
List<String> list=new ArrayList<>(Arrays.asList(str));
List<String> subList=list.subList(0,5);
You can try something similar to this
If you feel like taking a Linq-ee Libraried approach, this is about as good as it gets, and it requires use of a couple delegate objects:
import static com.google.common.collect.Collections2.filter;
import static com.google.common.collect.Collections2.transform;
//...
final List<String> yourList = //...
final int RECORD_LENGTH = 6;
Collection<String> roleIdValues = filter(yourList, new Predicate<String>() {
public boolean apply(#Nullable String input) {
return input != null && input.startsWith("RoleID");
}
});
Collection<Collection<String>> splitRecords = transform(roleIdValues, new Function<String, Collection<String>>() {
#Nullable public Collection<String> apply(#Nullable String input) {
return yourList.subList(yourList.indexOf(input), RECORD_LENGTH);
}
});
If Oracle had delivered Java 8 on time you would be able to do this in a way more slick manor. Ironically the reason you cant was provided by the same people providing the guava library

Java, getter for array values (array dynamically defined)

I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}

Categories

Resources