This question already has answers here:
ArrayIndexOutOfBoundsException [closed]
(2 answers)
Closed 5 years ago.
Im get from my server an array of objects like this:
Log.i(TAG, "Destinos obtenidos: "+ destinosRuta);
Value of log -
Destinos obtenidos [{"Latitud":41.40404,"nombreDestino":"Barcelona","IDR":5,"IDD":6,"Longitud":2.168679},{"Latitud":37.408424,"nombreDestino":"Sevilla","IDR":5,"IDD":7,"Longitud":-5.9681},{"Latitud":38.92298,"nombreDestino":"Mérida","IDR":5,"IDD":4,"Longitud":-6.363121}]
which I want to stock on SharedPreferences, I have used the code from this answer:
putStringSet and getStringSet
But I don't know if i need to use an array of object, or I need to convert in an array of String, this is my code:
private Emitter.Listener onNuevaRuta = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String destinosRuta = "";
try {
destinosRuta = data.getString("destinosRuta");
}catch (JSONException e) {
return;
}
//destinosRuta has the previous value
ArrayList<String> listaDestinos = new ArrayList<String>(Arrays.asList(destinosRuta));
setStringArrayPref(getApplicationContext(), "listaDestinos", listaDestinos);
listaDestinos = getStringArrayPref(getApplicationContext(), "listaDestinos");
String origen = listaDestinos.remove(0);
String destino = listaDestinos.remove(0);
setStringArrayPref(getApplicationContext(), "listaDestinos", listaDestinos);
...
And, like the previous link, I have used his function:
public static void setStringArrayPref(Context context, String key, ArrayList<String> values) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray a = new JSONArray();
for (int i = 0; i < values.size(); i++) {
a.put(values.get(i));
}
if (!values.isEmpty()) {
editor.putString(key, a.toString());
} else {
editor.putString(key, null);
}
editor.commit();
}
public static ArrayList<String> getStringArrayPref(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(key, null);
ArrayList<String> destinos = new ArrayList<String>();
if (json != null) {
try {
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
String destino = a.optString(i);
destinos.add(destino);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return destinos;
}
And i get an error when I'm tring to removed the first element of listaDestinos here:
String origen = listaDestinos.remove(0);
String destino = listaDestinos.remove(0); <--Error
FATAL EXCEPTION: main
Process: tfg.clienteandroid, PID: 17276
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.remove(ArrayList.java:403)
at tfg.clienteandroid.mapaActivity$3$1.run(mapaActivity.java:320)
Any idea? I want to remove twice and be able to use both objects from my array.
You don't need to store a list object. If you have your server already returning JSON, you can directly store that.
JSONObject data = (JSONObject) args[0];
String response = String.valueOf(data);
//... Or parse out the data you need
sharedPrefs.putString("response", response);
Convert the string into a JSON object or whatever on the way out and optionally parse it into actual Java objects (you can use Jackson or Gson to help you with that)
Anyway, not sure why you think you need to remove an object from a list in order to extract a value; besides, it looks like you only added one value to your list, not two. The Arrays.asList() method is creating you a list of one string. You can't remove two objects from that list
So, try to debug your code better with some breakpoints and more log statements.
In other words, you seem to have a problem parsing your data, not just using SharedPreferences
For example,
data.getString("destinosRuta");
Is that actually a string? Or an array? If an array, use the according method of the JSONObject class to get an array.
Save your json to preference like this
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
prefsEditor.putString("MyObject", destinosRuta);
prefsEditor.commit();
And get it when to use and convert to ArrayList or List as below
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("MyObject", "");
Type type = new TypeToken<List<Object>>(){}.getType();
List<Object> objects= gson.fromJson(json, type);
Related
strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String
I have a JSON Array with a strong single object inside it.
[{
"Date": "2016-02-26 00:54:35",
"Temp": "24.00"
}]
I have been trying to parse it to an Android application via text view, however, the TextView field displays as blank when the application is ran. I've tried many different tutorials and neither has worked. My current code on the parsing is below. I have a separate class for the HTTP connections.
protected void onPostExectue(String stream) {
TextView Temp1 = (TextView) findViewById(R.id.textTemp);
Temp1.setText(stream);
if (stream != null) {
try {
//data arrives as JSON array
JSONArray reader = new JSONArray(stream);
int readerLength = reader.length();
if(readerLength > 0)
{
for(int i = 0; i < readerLength; i++)
{
JSONObject item = reader.getJSONObject(i);
String d = item.getString("Date");
}
}
I attempted to declare the JSONArray first and then read the object from within.
Editing due to comment below to show the stream:
protected String doInBackground(String... strings) {
String stream = null;
String urlString = strings[0];
HTTPDataHandler hh = new HTTPDataHandler();
stream = hh.GetHTTPData(urlString);
// Return the data from specified url
return stream;
}
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
I am trying to use the 2nd value of each of my JSON elemnts and use it in a array of web urls. What I am trying to end of with is a array of urls that include the image names from my json data below.
JSON Data:
[["1","Dragon Neck Tattoo","thm_polaroid.jpg","polaroid.jpg"],["2","Neck Tattoo","thm_default.jpg","default.jpg"],["3","Sweet Tattoo","thm_enhanced-buzz-9667-1270841394-4.jpg","enhanced-buzz-9667-1270841394-4.jpg"]]
MainActivity:
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
try {
//THIS IS WHERE THE VALUES WILL GET ASSIGNED
JSONArray jsonArray = new JSONArray(jsonData);
private String[] mStrings=
{
for(int i=0;i<jsonArray.length();i++)
{
"http://www.mywebsite.com/images/" + jsonArray(i)(2),
}
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As I mentioned in a previous answer, a JSONArray is just an object, not a numerically-indexable array. It looks like you're having trouble with basic Java syntax, as well.
If you actually want to use a String[], not a List<String>:
private String[] mStrings = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings[i] = "http://www.mywebsite.com/images/" + url;
}
If the LazyAdapter you're using can take a List, that'll be even easier to work with:
private List<String> mStrings = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings.add("http://www.mywebsite.com/images/" + url);
}
Im from php, so i want to lear java.
In php in a for loop if i want to create an array i just do
$items = $this->getItems();
for($i=0;$i<count($items);$i++)
{
$myarrayitems[$i] = $items[$i];
}
return $myarrayitems;
But in java i got arrayoutofexponsion or like that.
here is the code im trying
public String[] getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
int items = feed.getItemCount();
int a = 0;
for (int i = 0; i < items; i++)
{
FeedItem item = feed.getItem(i);
String title[i] = item.getTitle();
}
return title;
}
How can i return title as array an make an var_dump of that?
You need to create the array with the right number of elements to start with. Something like this:
public String[] getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
int items = feed.getItemCount();
// We know how many elements we need, so create the array
String[] titles = new String[items];
for (int i = 0; i < items; i++)
{
titles[i] = feed.getItem(i).getTitle();
}
return titles;
}
A potentially nicer alternative, however, is to return a List<String> instead of a string array. I don't know the FeedParser API, but if you can iterate over the items instead you could do something like:
public List<String> getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
List<String> titles = new ArrayList<String>();
for (Item item : feed)
{
titles.add(item.getTitle());
}
return titles;
}
This will work even if you don't know how many items there are to start with. When Java eventually gets concise closures, you may well be able to express this even more simply, as you would in C# with LINQ :)
You have to define title as an array before using using it:
String title = new String[ARRAY_DIMENSION];
If you don't know ARRAY_DIMENSION you could use this:
List<String> title = new ArrayList<String>();
or this, if you do not mind String order in the ArrayList:
Collection<String> title = new ArrayList<String>();