Dynamically inserting string into a string array in Android - android

I receive some data as a JSON response from a server. I extract the data I need and I want to put this data into a string array. I do not know the size of the data, so I cannot declare the array as static. I declare a dynamic string array:
String[] xCoords = {};
After this I insert the data in the array:
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}
But I receive the
java.lang.ArrayIndexOutOfBoundsException
Caused by: java.lang.ArrayIndexOutOfBoundsException
What is the way to dynamically insert strings into a string array?

Use ArrayList although it is not really needed but just learn it:
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
stringArrayList.add(json_data.getString("xCoord")); //add to arraylist
}
//if you want your array
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);

Try like this
String stringArray[];
stringArray=new String[jArray.length()];
String xCoords[]=new String[jArray.length()];;
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}

String Array in Java has a defined size that should be given while declaration, you cannot change it later by adding or removing elements and the pure concept of the dynamic array does not exit in java. Read detailed article here...
This is the right way to declare an array of fixed size.
String[] myString = new String[5];
fruits[0]="hello";
fruits[1]="hello";
fruits[2]="hello";
fruits[3]="hello";
fruits[4]="hello";
Instead, you can use a List to perform a similar task. The list is purely dynamic and you can add multiple values on runtime.
This is the right way to declare a list in Android using JAVA.
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("Value 1");
fruits.add("Value 2");
fruits.add("Value 3");
fruits.add("Value 4");
fruits.add("Value 5");
fruits.add("Value 6");
fruits.add("Value 7");
// add as much values as per requirement
// you can also use loops to add multiple values

Related

Split strings on string array

i have String Array like this:
String[] q1={"AAA-BBB","AAA-CCC","AAA-DDD"}
and i want result like this
temp={"BBB","CCC","DDD"}
i tried below code but the result is wrong
for(int i=0;i<q1.length;i++){
ArrayList<String> temp=new ArrayList<>(Arrays.asList(q1[i].split("AAA-")));
}
Try like this:
ArrayList<String> temp=new ArrayList<>();
for(int i=0;i<q1.length;i++){
String[] array = q1[i].split("-");
temp.add(array[1]);
}
You could use substring:
ArrayList<String> temp = new ArrayList<>();
for(int i=0; i<q1.length; i++){
temp.add(q[i].substring(q[i].indexOf('-') + 1, q[i].length()))
}
you find error Because you use split
Splits this string around matches of the given regular expression.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
q1[i].split("AAA-")
in this line you got 2 result splited 0 = "" AND 1 = "BBB"
so you need to pick the sec result
you have multi Solution
like https://stackoverflow.com/a/50234408/6998825 said
String[] array = q1[i].split("-");
temp.add(array[1]);
//change this q1[i].split("AAA-") to
q1[0].substring(4)
if your AAA- is not going to change
Have you tried creating the ArrayList outside of the loop? As previously you were creating a new ArrayList for every element in your string array
ArrayList<String> temp = new ArrayList<>();
for(int i=0;i<q1.length;i++){
temp.add(q1[i].substring(4);
}
Assuming that "AAA-" is not going to change.

Get jsonArray objects without value name and pass it to list

I am trying to read json array without object name, and pass it to a list.
My json looks like :
"facilites": [
"Pool",
" Air Conditioning",
" Pets Allowed",
" Fitness center",
" Kitchen",
" Internet",
" Sona"
]
I am trying to retrieve it using the following code -
for (int l = 0; l < chaletFacilities.length(); l++){
String facilities = chaletFacilities.getString(l);
list = new ArrayList<String>();
list.add(facilities);
}
Inside the main loop I put to my pojo class chalets.setList(list);
The issue is in this line list.add(facilities); it only add the last element. After looping through all, list carry sona only.
Your list should be instantiated outside the loop.
list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++){
String facilities = chaletFacilities.getString(l);
list.add(facilities);
}
An improvement would be directly add string to list instead of capturing it into a string variable like list.add(chaletFacilities.getString(l))
Move initialization of your ArrayList outside of your loop.
Do like this
list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++){
list.add(chaletFacilities.getString(l))
}
What you doing is initializing yourlist again and again and adding the element. So while last iteration the list is getting initialized again and only single element is being added to it.
ArrayList list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++){
String facilities = chaletFacilities.getString(l);
list.add(facilities);
}
You are creating the new list always. So your list size will be 1 with the last value in chaletFacilities array.
Solution: Keep your list initialization outside the for loop as below, and add all the values under the array into single list you created in the top.
list = new ArrayList<String>();
for (int l = 0; l < chaletFacilities.length(); l++)
{
list.add(chaletFacilities.getString(l));
}

Traverse array IN JSONArray

I'm making an app for android which makes a call to a webservice that returns a json with ARRAY as a parameter, I can go through all the settings and save them easily.
The problem is when I get the array that I returned within the JSON object.
Example of JSON:
[{"codigoArticulo":"0001","nombreArticulo":"CHULETAS DE CORDERO","factorVentasDefecto":"KG","precio":21.95,"factoresDeVenta":["KG","UN"]},{"codigoArticulo":"0007","nombreArticulo":"FALDETA DE CORDERO","factorVentasDefecto":"KG","precio":11.95,"factoresDeVenta":["KG","FL"]}]
I can save "codigoArticulo", "nombreArticulo", "factorVentasDefecto" and "precio easily, BUT i don't know how i can save "factoresDeVenta".
i have this code:
JSONArray resparray = new JSONArray(JSONdevuelto);
for (int i = 0; i < resparray.length(); i++) {
JSONObject respJSON = resparray.getJSONObject(i);
int IDArticulo = respJSON.getInt("codigoArticulo");
String NombreArticulo = respJSON.getString("nombreArticulo");
String FactordeVenta = respJSON.getString("factorVentasDefecto");
int PrecioArticulo = respJSON.getInt("precio");
}
How i can save in one array the variables on "factoresDeVenta"?
I try
String[] Factores = respJSON.getJSONArray("factoresDeVenta");
but no works because are incompatible types.
I need the array to make later a Spinner
Thank you.
factoresDeVenta is an JSONArray inside JSONObject so you will need to use getJSONArray or optJSONArray and use loop for getting values from JSONArray:
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
String str_value=jArray.optString(i); //<< jget value from jArray
}
JSONArray jArray = respJSON.getJSONArray("factoresDeVenta");
It would give you the array of data stored in factoresDeVenta, which you can again traverse to get the individual elements from that array.
You can store in ArrayList<String>
ArrayList<String> arrStr = new ArrayList<String>();
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
arrStr.add(jArray.getString(i));
}
And then you can convert arraylist to string array
String[] Factores = arrStr.toArray(new String[arrStr.size()]);

create an array of all the keys in a JSONObject Android

Hi im wanting to create an array of all the keys in a JSONObject. my understanding (please correct me if i'm wrong) is that i need to convert the JSONObject to a Map and then create an Array from this does anyone know how to do this?
No need to convert JSONObject to a Map and then create an Array of keys just use JSONObject.names() for getting all keys in an JsonArray then convert it to Array or ArrayList. example:
JSONObject json = new JSONObject("json object string");
JSONArray namearray=json.names(); //<<< get all keys in JSONArray
Try this:
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] array = list.toArray(new String[list.size()]);

Android: JSON data loaded into adapter

This might be a simple Java issue I'm struggling with but I'm looking to the community to assist me here as I have hit a brick wall with this situation.
I successfully have data coming in off of a MySQL database and brought to the application through JSON. During parsing I was trying to create another array to be passed onto an ArrayAdapter to be used in a ListView. Here is the code I'm having an issue with:
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
Games game_data[] = new Games[]
{
new Games(ct_id, ct_name)
};
}
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
This line: GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
More specifically the game_data is highlighted red in Eclipse. Where I am curious is why does game_data get out of reach after end of loop? I'm just trying to add specific fields within the row from JSON to the adapter here.
I also tried going through the loop within setting up the array but still no dice as new Games[] gets an error. Here is an example:
Games game_data[] = new Games[]
{
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
// Games game_data[] = new Games[]
// {
new Games(ct_id, ct_name);
// };
}
error: Variable must either provide dimension expressions or array initializer.
Hope this helps...
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
Games game_data[];
game_data[] = new Games[jArray.length()];
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
game_data[i] = new Games(ct_id, ct_name);
}
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
I am thinking that Games is your POJO class so you can better do something like this,
Create a List of the POJO class
private List<Games> games= new ArrayList<Games>();
Now you can add your content in the games list.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
games.add(new Games(ct_id, ct_name));
}
And finally pass the list in the Adapter.
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, games);
error: Variable must either provide dimension expressions or array initializer.
=> This error is obvious because you haven't define any dimensions value to create an array and also haven't passed any initialization to this array.
So I think you are doing wrong, instead do it like:
Games game_data[] = new Games(ct_id, ct_name);
This is the correct way to call a constructor.
And i don't know what you have written inside the Games class so i just have mentioned about the calling of constructor.

Categories

Resources