-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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.