how to convert the data stored in string to string array - java

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

Related

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

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

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

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 do I concatenate all string elements of several arrays into one single array?

How do I concatenate, or append, all of the arrays that contain text strings into a single array? From the following code:
String nList[] = {"indonesia", "thailand", "australia"};
int nIndex[] = {100, 220, 100};
String vkList[] = {"wounded", "hurt"};
int vkIndex[] = {309, 430, 550};
String skList[] = {"robbed", "detained"};
int skIndex[] = {120, 225};
String nationality = "";
//System.out.println(nationality);
I want to store all strings of all three string-containing arrays:
String nList[] = {"indonesia", "thailand", "australia"};
String vkList[] = {"wounded", "hurt"};
String skList[] = {"robbed", "detained"};
into a single array, say array1[].
ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = (String[])temp.toArray();
You can add the content of each array to a temporary List and then convert it's content to a String[].
List<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = new String[temp.size()];
for (int i = 0; i < temp.size(); i++) {
result[i] = (String) temp.get(i);
}
Alternatively, you can use Guava's ObjectArrays#concat(T[] first, T[] second, Class< T > type) method, which returns a new array that contains the concatenated contents of two given arrays. For example:
String[] concatTwoArrays = ObjectArrays.concat(nList, vkList, String.class);
String[] concatTheThirdArray = ObjectArrays.concat(concatTwoArrays, skList, String.class);
public static String[] join(String [] ... parms) {
// calculate size of target array
int size = 0;
for (String[] array : parms) {
size += array.length;
}
String[] result = new String[size];
int j = 0;
for (String[] array : parms) {
for (String s : array) {
result[j++] = s;
}
}
return result;
}
Just define your own join method. Found # http://www.rgagnon.com/javadetails/java-0636.html

Convert array list items to integer

I have an arraylist, say arr. Now this arraylist stores numbers as strings. now i want to convert this arraylist to integer type. So how can i do that???
ArrayList arr = new ArrayList();
String a="Mode set - In Service", b="Mode set - Out of Service";
if(line.contains(a) || line.contains(b)) {
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()) {
arr.add(st.nextToken());
}
}
Since you're using an untyped List arr, you'll need to cast to String before performing parseInt:
List<Integer> arrayOfInts = new ArrayList<Integer>();
for (Object str : arr) {
arrayOfInts.add(Integer.parseInt((String)str));
}
I recommend that you define arr as follows:
List<String> arr = new ArrayList<String>();
That makes the cast in the conversion unnecessary.
run the below code,i hope it meets you requirement.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> strArrayList= new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
int x = 0;
for (String s : strArrayList)
{
ArrayRes[i] = Integer.parseInt(s);
System.out.println(ArrayRes[i]);
i++;
}
}
}
Output:
1
11
111
12343
18475
To convert to an integer array, you will input as a string array then go through each one and change it to an int.
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
//new int for each string
int intarray[] = new int[sarray.length];
//for each int blah blah to array length i
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
final List<String> strs = new ArrayList();
strs.add("1");
strs.add("2");
Integer[] ints = new Integer[strs.size()];
for (int i = 0; i<strs.size(); i++){
ints[i] = Integer.parseInt(strs.get(i));
}
use the Integer.parseInt() method.
http://www.java2s.com/Code/Java/Language-Basics/Convertstringtoint.htm
If you know that you have an arraylist of string but in your you wil use the same list as list of integer so better while initializing array list specify that the array list must insert only int type of data
instead of writing ArrayList arr = new ArrayList();
you could have written ArrayList<Integer> arr = new ArrayList<Integer>();
Alternate solution
If you want to convert that list into Integer ArrayList then use following code
How to convert String ArrayList into ArrayList of int
ArrayList<String> oldList = new ArrayList<String>();
oldList.add(""+5);
oldList.add(""+5);
ArrayList<Integer> newList = new ArrayList<Integer>(oldList.size());
for (String myInt : oldList) {
newList.add(Integer.parseInt(myInt));
}

Categories