-2

**hello dear friends ,In my project i have an arraylist that filling from beacons data every second , is it possible to convert this arrayL to JSONArray and post it to an URL at the same time ??? **

'private ArrayList<Beacon> arrayL = new ArrayList<>();

@Override
public void onBeaconServiceConnect() {

    iBeaconManager.setRangeNotifier(new RangeNotifier() {
        @Override
        public void didRangeBeaconsInRegion(final Collection<Beacon> iBeacons, Region region) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    arrayL.clear();
                    arrayL.addAll((ArrayList<Beacon>) iBeacons);

                }
            });
        }
    });'

enter image description here

amirofff
  • 5
  • 6
  • Possible duplicate of [convert ArrayList to JSONArray](https://stackoverflow.com/questions/4841952/convert-arraylistmycustomclass-to-jsonarray) – misman Aug 27 '17 at 00:22

1 Answers1

1

You could try something like that:

1) Build the JSON object

ArrayList<Beacon> arrayL = new ArrayList<>();
JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));

2) Post to server

public void postData() {
    ArrayList<String> arrayL = new ArrayList<>();
    JSONArray mJSONArray = new JSONArray(Arrays.asList(arrayL));
    URL url = null;
    try {
        url = new URL("http://www.android.com/");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Type", "application/json");
    try {
        connection.setRequestMethod("POST");
    } catch (ProtocolException e) {
        e.printStackTrace();
    }

    for(int i = 0; i < mJSONArray.length(); i++)
    {
        try {
            JSONObject objects = mJSONArray.getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Iterate through the elements of the array i.
        //Get thier value.
        //Get the value for the first element and the value for the last element.
    }
    JSONObject json = new JSONObject();

    byte[] outputBytes = new byte[0];
    try {
        outputBytes = json.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    OutputStream os = null;
    try {
        os = connection.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        os.write(outputBytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Hope it helps.

Andre Breton
  • 1,273
  • 1
  • 9
  • 19