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

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!

Related

Arraylist of String arrays not appending?

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

How to keep adding values to a List using a JButton and JTextArea without them being re-written

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String newCD = (cdInput.getText());
List <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");
cdList.add(""+newCD);
List<String> sorted = new ArrayList<String>(cdList);
Collections.sort(sorted);
bigBox.setText("");
bigBox.append("Original Order\n**************\n");
for (String o : cdList) {
bigBox.append(o);
bigBox.append("\n");
}
bigBox.append("\n\nSorted Order\n************\n");
for (String s : sorted) {
bigBox.append(s);
bigBox.append("\n");
}
}
With this code, I can add 1 value, but when I try to add another one, it erases the original and replaces it. What can I do to prevent this?
PS. I'm trying to make a List of CDs, and be able to add new ones and have them also sorted and put in thier original order
Based on your code, you have no centralised instance of List, which means, each time you activate the button, it has no concept of what was previously in the list.
Start by creating an instance variable of the cd List and only add new items to it as required.
Something more like...
private List<String> cdList = new ArrayList<>(25);
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String newCD = (cdInput.getText());
cdList.add(newCD);
List<String> sorted = new ArrayList<String>(cdList);
Collections.sort(sorted);
bigBox.append("Original Order\n**************\n");
for (String o : cdList) {
bigBox.append(o);
bigBox.append("\n");
}
bigBox.append("\n\nSorted Order\n************\n");
for (String s : sorted) {
bigBox.append(s);
bigBox.append("\n");
}
}

return an ArrayList method

This is a drive method for two other classes. which i posted here
https://codereview.stackexchange.com/questions/33148/book-program-with-arraylist
I need some help for the
private static ArrayList getAuthors(String authors) method. I am kind a beginner. so please help me finish this drive method. or give me some directions.
Instruction
some of the elements of the allAuthors array contain asterisks “*” between two authors names. The getAuthors method uses this asterisk as a delimiter between names to store them separately in the returned ArrayList of Strings.
import java.util.ArrayList;
public class LibraryDrive {
public static void main(String[] args) {
String[] titles = { "The Hobbit", "Acer Dumpling", "A Christmas Carol",
"Marley and Me", "Building Java Programs",
"Java, How to Program" };
String[] allAuthors = { "Tolkien, J.R.", "Doofus, Robert",
"Dickens, Charles", "Remember, SomeoneIdont",
"Reges, Stuart*Stepp, Marty", "Deitel, Paul*Deitel, Harvery" };
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
for (int i = 0; i < titles.length; i++) {
authors = getAuthors(allAuthors[i]);
Book b = new Book(titles[i], authors);
books.add(b);
authors.remove(0);
}
Library lib = new Library(books);
System.out.println(lib);
lib.sort();
System.out.println(lib);
}
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
// need help here.
return books;
}
}
try this
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
String[] splitStr = authors.split("\\*");
for (int i=0;i<splitStr.length;i++) {
books.add(splitStr[i]);
}
return books;
}
What I would suggest is to use String.split like here (but keep in mind that this method uses a regex as parameter):
private static ArrayList<String> getAuthors(String authors) {
ArrayList books = new ArrayList<String>();
String[] strgArray = authors.split("\\*");
books.addAll(Arrays.asList(strgArray));
return books;
}
or
private static ArrayList<String> getAuthors(String authors) {
String[] strgArray = authors.split("\\*");
ArrayList books = Arrays.asList(strgArray);
return books;
}
Try this one but actually i do not understant why you remove zero indexed element of ArrayList in for loop.
private static ArrayList<String> getAuthors(String authors) {
ArrayList<String> array = new ArrayList<String>();
String[] authorsArray = authors.split("\\*");
for(String names : authorsArray );
array.add(names);
return array;
}
Take a look at String#split method, this will help you to separate authors by asterisk. This method returns an array so you will need to check how many authors are in this array and then store each of them into the ArrayList.
Here's how you can go about doing it.
Split the authors string you're getting as the method param based on the asterisk symbol. (Using String.split(delim) method)
The resultant string[] array needs to be iterated over using a for loop and each iterated element should be added to your list. (Using List.add(elem) method)
Once done, return that list(you are already doin that).
Now that you know how to do it, you need to implement the code by yourself.

How can I convert a String to a String[] // Android development // Java

I am quite new to Java and am currently coding an Android application. In my "Shortcuts" class, I have this bit of code (more of course, but not useful to you, I don't think):
final String[] items = new String[]{ "Please select a category",scanner.getCategorys() };
#SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selection.setAdapter(adapter);
I have another class named "Scanner", which has this code:
String categorys = "test";
public String getCategorys() {
return categorys;
}
This does work, and in my Spinner, I can fill in my "Please select a category" option with a single value (i.e "test"). The problem is, I would like to be able to select multiple categories. If I do this in "Shortcuts" class:
final String[] items = new String[]{ "Please select a category","test","test2" };
It would work, but I would like to set it from the "Scanner" class, so I tried this:
String[] categorys = "test","test2";
public String[] getCategorys() {
return categorys;
}
But it just gives me the error:
String cannot be converted to String[]
I would be grateful for any help.
This is wrong:
String[] categorys = "test","test2";
Change it to
String[] categorys = {"test","test2"};
In your last code sample, you have to put { } around your strings, like so:
String[] categorys = { "test","test2" };
public String[] getCategorys() {
return categorys;
}
According to your edit above, you can't add a String[] to an existing String[]. You need to add every item in the String[] you get from getCategorys() to the other array. I would probably switch to an ArrayList<string> in this case, so you don't have to decide what size the array should be, then add each item.
You can initialize categorys as follows
String[] categorys = {"test","test2"};
I'd call the variable as 'categories'.
EDIT :
scanner.getCategorys() cannot be used as the constructor expects a String and not a string array. A good idea would be use ArrayList as pointed out by uncocoder. You could then just use the add method to include "Please select a category".
I recomment to use ArrayList, it's fast and easy like this
ArrayList<String> strings = new ArrayList<String>();
strings.add("SOME TEXT");
strings.get(0);
//and more

Java NullPointerException in Array

I get an error when I do the following operation.
public static String text = "ng";
public static String[] specialConsonants = new String[4];
public static String[] specialConsonantsUni = new String[6];
public void setSpecial(){
specialConsonantsUni[0] = "ං";
specialConsonants[0] = "ng";
specialConsonantsUni[1] = "ඃ";
specialConsonants[1] = "h/g";
specialConsonantsUni[2] = "ඞ";
specialConsonants[2] = "N/g";
specialConsonantsUni[3] = "ඍ";
specialConsonants[3] = "R/g";
// special characher Repaya
specialConsonantsUni[4] = "ර්" + "\u200D";
specialConsonants[4] = "/R/g";
specialConsonantsUni[5] = "ර්" + "\u200D";
specialConsonants[5] = "/\\r/g";
}
public static void main(String args[]){
for (int i=0; i < specialConsonants.length; i++){
text = text.replace(specialConsonants[i], specialConsonantsUni[i]);
System.out.println(text);
}
}
I'm trying to create a locale app. So you may not see some fonts. The error is following.
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.replace(Unknown Source)
at in.isuru.srtuc.Stuff.main(Stuff.java:223)
specialConsonants and specialConsonantsUni are not initilized. You've just defined setSpecial() but not called it before doing replaces
The correct behavior would be:
public static void main(String args[]){
setSpecial();
for (int i=0; i < specialConsonants.length; i++){
text = text.replace(specialConsonants[i], specialConsonantsUni[i]);
System.out.println(text);
}
}
note also that setSpecial should be static in that case
Moreover you have to change dimension of specialConsonants to 6
Because specialConsonants[i] is null. You have not initialized it.
its like
specialConsonants = {null,null,null,null}
You need to make function setSpecial static then call it before the loop.
public static String[] specialConsonants = new String[4];
public void setSpecial(){
// ...
specialConsonants[5] = "/\\r/g";
}
specialConsonants is of array size 4. There is no 5th index for it. Also you haven't called the array initializer method.
You're adding elements to an already filled array. Array indexes start from 0, When you declared :
public static String[] specialConsonants = new String[4];
That means you can only use specialConsonants[0] to specialConsonants[3]
I suggest you use a hashmap for this thing.
HashMap<String, String> specialConsonants = new HashMap<String, String>();
....
specialConsonants.put("ං" , "ng" );
....
You've declared specialConsonants as an array of length 4, but you're assigning 6 elements to it.
specialConsonants[4] has enough room for elements 0, 1, 2, and 3.
You need to declare it as specialConsonants[6] if you want indices 0 - 5.
Then you need to call setSpecial() before you use the array in your loop.
the array definition looks wrong, seems you want two same size array but you defined as :
public static String[] specialConsonants = new String[4];
public static String[] specialConsonantsUni = new String[6];
I think it should be:
public static String[] specialConsonants = new String[6];
public static String[] specialConsonantsUni = new String[6];

Categories

Resources