2

I have the following code. I added my text fields dynamically. My desired result shown in Genymotion 5.0 (Google Nexus 5) but when I run my app in other devices/actual device the textfields get shuffled. Please help, Thanks in advance.

JSONObject jsonObject = new JSONObject(question.getSublabels()); final EditText[] editTextSublabels = new EditText[jsonObject.length()]; for (int i = 0; i < jsonObject.length(); i++) { String names = jsonObject.names().get(i).toString(); editTextSublabels[i] = (EditText) LayoutInflater.from(activity).inflate(R.layout.sublabels, null); editTextSublabels[i].setId(i); editTextSublabels[i].setHint(jsonObject.getString(names)); sublabelsContainers.addView(editTextSublabels[i], params); }

Result in Devices

rubberdont
  • 464
  • 3
  • 15
  • maybe you should try to use the addView() with the index parameter, and make the index parameter i like so sublabelsContainers.addView(editTextSublabels[i],i, params); maybe that will work across devices, im not to sure though – JRowan Jan 06 '15 at 06:59
  • 1
    Refer to this question: http://stackoverflow.com/questions/17229418/jsonobject-why-jsonobject-changing-the-order-of-attributes – JayR Jan 06 '15 at 07:00
  • @JRowan still the same. :( – rubberdont Jan 06 '15 at 07:02
  • possible duplicate of [JSON order mixed up](http://stackoverflow.com/questions/3948206/json-order-mixed-up) – Lazy Ninja Jan 06 '15 at 08:10

2 Answers2

3

You cannot and should not rely on the ordering of elements within a JSON object. In JSON, an object is defined thus:

An object is an unordered set of name/value pairs.

If you want order to be preserved, you need to redefine your data structure or put it inside a jsonarray

see http://www.json.org.

hatdoggo
  • 46
  • 5
1

A JSONObject is a type of map. It does not preserve ordering. If you want to preserve ordering using JSON, you will need to use an array (and matching JSONArray in Java).

Anm
  • 3,291
  • 2
  • 29
  • 40