How to properly add data from String[] to ArrayList<String[]> - java

so for my school project we will be working with an SQL database and have to show the values on a JFrame panel.
For data to show in a JTable we have to require next syntaxt: (def)
JTable table = new JTable(String[][] data , String[] header);
Since I don't know how many queries I will have to handle we will read them into a ArrayList<String[]> . Every time I press the button this method parseJSON will be called and I will create a new 2D-ArrayList consisting of String arrays aka String[] elements
public class DBTest {
public ArrayList<String[]> dataArr = new ArrayList<>();
public String[] varArr = new String[3];
public ArrayList<String[]> parseJSON(String jsonString){
try {
JSONArray array = new JSONArray(jsonString);
dataArr = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
varArr[0] = curObject.getString("nameSensor");
varArr[1] = curObject.getString("value");
varArr[2] = curObject.getString("unitSensor");
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
for (int i = 0; i < array.length(); i++) {
System.out.println(dataArr.get(i));
}
return dataArr;
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
For the first print: I will get the proper Values e.g.
Output
["Weight","500","g"]
["Height", "3", "m"]
But once I add these String[] arrays to the ArrayList and print it I will get:
Output
["Height", "3", "m"]
["Height", "3", "m"]

I want to add one point to #LuiggiMendoza's answer....
In Java, arrays are basically Objects. The reason why creating a new array in each iteration (local to the method) is because the original code was literally overwriting the value of a single object and placing said reference to three different index location on the ArrayList rather than creating distinct references. Therefore, the last System.out.print() was printing out the same array element value for each iteration of the list. In fact, even if the array was created outside the loop, the result would've been the same as the original code. EACH ITERATION needs a new array for this to work.

Move String[] varArr as a local variable in your method:
public class DBTest {
public ArrayList<String[]> dataArr = new ArrayList<>();
//Remove this line of code (delete it)
//public String[] varArr = new String[3];
public ArrayList<String[]> parseJSON(String jsonString){
try {
JSONArray array = new JSONArray(jsonString);
dataArr = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
//declare it locally
String[] varArr = new String[] {
curObject.getString("nameSensor"),
curObject.getString("value"),
curObject.getString("unitSensor")
};
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
for (int i = 0; i < array.length(); i++) {
System.out.println(dataArr.get(i));
}
return dataArr;
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
Other improvements:
Try to design your code to work with interfaces rather than concrete classes e.g. return List instead of ArrayList
Avoid returning null in case the method failed. It'd be better if you return an empty list or throwing a custom exception with a proper message that helps you understand the issue. This also leverages your maintenance effort.
Use attributes only if you need to maintain the state (the values) for later use. Otherwise, it'd be better to use local variables instead. dataArr attribute seems to not be needed (at least from this piece of code).
Wrapping everything, this is how the code would look:
public class DBTest {
public List<String[]> parseJSON(String jsonString) {
List<String[]> dataArr = new ArrayList<>();
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
String[] varArr = new String[] {
curObject.getString("nameSensor"),
curObject.getString("value"),
curObject.getString("unitSensor")
};
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
for (int i = 0; i < array.length(); i++) {
System.out.println(dataArr.get(i));
}
}
catch (JSONException e) {
e.printStackTrace();
}
return dataArr;
}
}

The issue lies in the following block of code.
public String[] varArr = new String[3];
...
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
varArr[0] = curObject.getString("nameSensor");
varArr[1] = curObject.getString("value");
varArr[2] = curObject.getString("unitSensor");
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}
At each iteration of the for-loop, you are doing the following:
Mutate (set values into) the same array instance, which you had instantiated and assigned to the variable varArr before the for-loop.
Add a reference of this array instance to the ArrayList dataArr.
The outcome is that you have added references of the same array instance to the ArrayList multiple times.
Since you were just updating the same underlying array instance over and over again, hence what you get at the second print statement is the last-updated value of that same array instance, printed multiple times.
To fix this, simply move the varArr declaration statement into the for-loop as below. What this does is that at each iteration of the for-loop, a new array instance is created and added to the ArrayList instead.
for (int i = 0; i < array.length(); i++) {
JSONObject curObject = array.getJSONObject(i);
String[] varArr = new String[3]; // move this here
varArr[0] = curObject.getString("nameSensor");
varArr[1] = curObject.getString("value");
varArr[2] = curObject.getString("unitSensor");
dataArr.add(varArr);
System.out.println(Arrays.toString(varArr));
}

Related

Extract String arrays from List

Developing a Java Android App but this is a straight up Java question i think.
I have List declared as follows;
List list= new ArrayList<String[]>();
I want to extract each String [] in a loop;
for(int i=0; i < list.size(); i++) {
//get each String[]
String[] teamDetails = (String[])list.get(i);
}
This errors, I am guessing it just doesn't like me casting the String[] like this.
Can anyone suggest a way to extract the String[] from my List?
Use a List<String[]> and you can use the more up-to-date looping construct:
List<String[]> list = new ArrayList<String[]>();
//I want to extract each String[] in a loop;
for ( String[] teamDetails : list) {
}
// To extract a specific one.
String[] third = list.get(2);
Try declaring the list this way
List<String[]> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++) {
//get each String[]
String[] teamDetails = list.get(i);
}
Moreover the call of your size function was wrong you need to add the brackets
/*ArrayList to Array Conversion */
String array[] = new String[arrlist.size()];
for(int j =0;j<arrlist.size();j++){
array[j] = arrlist.get(j);
}
//OR
/*ArrayList to Array Conversion */
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
In for loop change list.size to list.size()
And it works fine Check this https://ideone.com/jyVd0x
First of all you need to change declaration from
List list= new ArrayList<String[]>(); to
List<String[]> list = new ArrayList();
After that you can do something like
String[] temp = new String[list.size];
for(int i=0;i<list.size();i++)`
{
temp[i] = list.get(i);
}

Converting List<ArrayList> to String[]

I have a
List<ArrayList> arg = new ArrayList<ArrayList>();
with
[[logo], [cd_branche], [lib_branche]],
(other arguments not relevant)
[[1111,22222,3333]],[[2222,324,432]]...
and I want to cast it to a String[] so I did this
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= (String) obj[i];
}
but I'm getting
java.util.ArrayList cannot be cast to java.lang.String
The output I'm looking for is
headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche
Using Java 6
It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").
In that case simply do:
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= Arrays.toString(obj);
}
And each one of your ArrayList objects inside obj will be returned in string array format.
UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:
int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());
String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
for (int j=0; j< arg.get(i).size(); j++) {
headers[count++]= arg.get(i).get(j).toString();
}
}
String headers = "";
for (String header:arg)
{headers += header;}

ArrayList Cast in java Combo box

Hi there i have this code
public void comboCountry(List<Countries> cs) {
country = db.fillComboCountries();
DefaultComboBoxModel dcbm = (DefaultComboBoxModel) CountryComboBox.getModel();
for (int i = 0; i < country.size(); i++) {
String row[] = new String[country.size()];
//row[i] = String.valueOf(country.get(i).getCountryId());
row[i] = country.get(i).getCountryName();
// row[i] = country.get(i).getCountryCode();
dcbm.addElement(row);
}
}
with country = db.fillComboCountries(); i query the database and load everything into an ArrayList.
The Arraylist is country.
When i load my data into combobox i get
[Ljava.lang.String;#fdfc58
how can i avoid that and get the value that i want?
I have try with Arrays.tostring(), but i get also [ ].
Instead of dcbm.addElement(row); use dcbm.addElement(country.get(i).getCountryName());
With this, you will add individual elements of an array rather than array itself. Also you would avoid creating arrays with every item in the country list.
You are creating a new String array in each iteration, you should initialize the array before the for loop:
String row[] = new String[country.size()];
for (int i = 0; i < country.size(); i++) {
...
}
If you only want to add the countryName in each iteration, you don't need the array at all:
for (int i = 0; i < country.size(); i++) {
String countryName = country.get(i).getCountryName();
dcbm.addElement(countryName);
}
Or:
for (Country c : country) {
dcbm.addElement(c.getCountryName());
}

Convert JSON array of strings to Java?

I am trying to convert a JSON String array to Java which is given from this piece of javascript:
javaFunction(["a1", "a2"]); <--- This is called in javascript
In Java
public static void javaFunction(<What here?> jsonStringArray){ //<---- This is called in Java
//Convert the JSON String array here to something i can iterate through,
//For example:
for(int index = 0; index < convertedArray.length; index++){
System.out.println(convertedArray[index];
}
}
You can use this :
List<String> list = new ArrayList<String>();
for(int i = 0; i < jsonStringArray.length(); i++){
list.add(jsonStringArray.getJSONObject(i).getString("name"));
}
I solved it using this:
In the JavaScript:
javaFunction(JSON.Stringify(["a1", "a2"]));
In Java
public static void javaFunction(String jsonArrayString){
JSONArray jsonArray = new JSONArray(jsonArrayString);
List<String> list = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
list.add(jsonArray.getString(i));
}
}
Trim first and last bracket;
i.e.
jsonArrayString = jsonArrayString.subStr(1,jsonArrayString.length()-1);
you will get "a1","a2","a3","a4"
Then use String's split function.
String[] convertedArray= jsonArrayString.split(",");

how to convert the data stored in string to string array

I'm parsing an url using json. I'm getting the value of each tag and storing it in a string using getString in a for-loop.
What I want is to store the String value into a String array. I'm a noob as far as android development is concerned.
Below is the code:
JSONObject json = JsonFunctions.getJSONfromURL("http://www.skytel.mobi/stepheniphone/iphone/stephenFlickr.json");
try {
JSONArray boombaby=json.getJSONArray("items");
for(int i=0;i<boombaby.length();i++) {
JSONObject e = boombaby.getJSONObject(i);
mTitleName=e.getString("title");
String mTitleImage=e.getString("image");
}
}
Use a List to store your titles, and another to store your images. Or design a class holding two fields (title and image), and store instances of this class in a List:
List<String> titles = new ArrayList<String>();
List<String> images = new ArrayList<String>();
for (int i = 0; i < boombaby.length(); i++) {
JSONObject e = boombaby.getJSONObject(i);
titles.add(e.getString("title"));
images.add(e.getString("image"));
}
Read the Java tutorial about collections. This is a must-know.
My solution:
String[] convert2StringArr(String str)
{
if(str!=null&&str.length()>0)
{
String[] arr=new String[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=new String(str.charAt(i)+"");
}
return arr;
}
return null;
}
List<String> titles = new ArrayList<String>();
List<String> images = new ArrayList<String>();
for (int i = 0; i < boombaby.length(); i++) {
JSONObject e = boombaby.getJSONObject(i);
titles.add(e.getString("title"));
images.add(e.getString("image"));
}
and then convert list to array:
String[] titleArray = (String[])titles.toArray(new titles[titles.size()]);
String[] imageArray = (String[])images.toArray(new titles[images.size()]);

Categories