Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

In this page you can find the example usage for org.json JSONArray length.

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:com.fsa.en.dron.activity.MainActivity.java

private void fetchImages() {

    pDialog.setMessage("Levantando vuelo...");
    pDialog.setCanceledOnTouchOutside(false);
    pDialog.show();//from w  w w .  j  a va 2  s  .  c  o m

    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, endpoint, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                    JSONArray array = null;

                    try {
                        JSONObject user = response.getJSONObject("photos");
                        array = user.getJSONArray("photo");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    images.clear();
                    for (int i = 0; i < array.length(); i++) {
                        try {
                            JSONObject object = array.getJSONObject(i);
                            Image image = new Image();

                            image.setSmall("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setMedium("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setLarge("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setUrl("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setId(object.getString("id"));
                            Log.i("uuu", "" + "https://farm2.staticflickr.com/" + object.getString("server")
                                    + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            images.add(image);

                        } catch (JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                        }
                    }

                    mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Error: " + error.getMessage());
                    pDialog.hide();
                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req);
}

From source file:widgets.Graphical_List.java

@SuppressLint("HandlerLeak")
public Graphical_List(tracerengine Trac, Activity context, int id, int dev_id, String name, String type,
        String address, final String state_key, String url, final String usage, int period, int update,
        int widgetSize, int session_type, final String parameters, String model_id, int place_id,
        String place_type, SharedPreferences params) {
    super(context, Trac, id, name, "", usage, widgetSize, session_type, place_id, place_type, mytag, container);
    this.Tracer = Trac;
    this.context = context;
    this.dev_id = dev_id;
    this.id = id;
    this.usage = usage;
    this.address = address;
    //this.type = type;
    this.state_key = state_key;
    this.update = update;
    this.wname = name;
    this.url = url;
    String[] model = model_id.split("\\.");
    this.type = model[0];
    this.place_id = place_id;
    this.place_type = place_type;
    this.params = params;
    packageName = context.getPackageName();
    this.myself = this;
    this.session_type = session_type;
    this.parameters = parameters;
    setOnLongClickListener(this);
    setOnClickListener(this);

    mytag = "Graphical_List (" + dev_id + ")";
    login = params.getString("http_auth_username", null);
    password = params.getString("http_auth_password", null);

    //state key/*from   ww w . ja  va 2  s.co m*/
    state_key_view = new TextView(context);
    state_key_view.setText(state_key);
    state_key_view.setTextColor(Color.parseColor("#333333"));

    //value
    value = new TextView(context);
    value.setTextSize(28);
    value.setTextColor(Color.BLACK);
    animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(1000);

    if (with_list) {
        //Exploit parameters
        JSONObject jparam = null;
        String command;
        JSONArray commandValues = null;
        try {
            jparam = new JSONObject(parameters.replaceAll("&quot;", "\""));
            command = jparam.getString("command");
            commandValues = jparam.getJSONArray("commandValues");
            Tracer.e(mytag, "Json command :" + commandValues);
        } catch (Exception e) {
            command = "";
            commandValues = null;
            Tracer.e(mytag, "Json command error " + e.toString());

        }
        if (commandValues != null) {
            if (commandValues.length() > 0) {
                if (known_values != null)
                    known_values = null;

                known_values = new String[commandValues.length()];
                for (int i = 0; i < commandValues.length(); i++) {
                    try {
                        known_values[i] = commandValues.getString(i);
                    } catch (Exception e) {
                        known_values[i] = "???";
                    }
                }
            }

        }
        //list of choices
        listeChoices = new ListView(context);

        listItem = new ArrayList<HashMap<String, String>>();
        list_usable_choices = new Vector<String>();
        for (int i = 0; i < known_values.length; i++) {
            list_usable_choices.add(getStringResourceByName(known_values[i]));
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("choice", getStringResourceByName(known_values[i]));
            map.put("cmd_to_send", known_values[i]);
            listItem.add(map);

        }

        SimpleAdapter adapter_map = new SimpleAdapter(getContext(), listItem, R.layout.item_choice,
                new String[] { "choice", "cmd_to_send" }, new int[] { R.id.choice, R.id.cmd_to_send });
        listeChoices.setAdapter(adapter_map);
        listeChoices.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ((position < listItem.size()) && (position > -1)) {
                    //process selected command
                    HashMap<String, String> map = new HashMap<String, String>();
                    map = listItem.get(position);
                    cmd_requested = map.get("cmd_to_send");
                    Tracer.d(mytag,
                            "command selected at Position = " + position + "  Commande = " + cmd_requested);
                    new CommandeThread().execute();
                }
            }
        });

        listeChoices.setScrollingCacheEnabled(false);
        //feature panel 2 which will contain list of selectable choices
        featurePan2 = new LinearLayout(context);
        featurePan2.setLayoutParams(
                new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        featurePan2.setGravity(Gravity.CENTER_VERTICAL);
        featurePan2.setPadding(5, 10, 5, 10);
        featurePan2.addView(listeChoices);

    }

    LL_featurePan.addView(value);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 2) {
                Toast.makeText(getContext(), "Command Failed", Toast.LENGTH_SHORT).show();

            } else if (msg.what == 9999) {

                //Message from cache engine
                //state_engine send us a signal to notify value changed
                if (session == null)
                    return;

                String loc_Value = session.getValue();
                Tracer.d(mytag, "Handler receives a new value <" + loc_Value + ">");
                value.setText(getStringResourceByName(loc_Value));
                //To have the icon colored as it has no state
                IV_img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2));

            } else if (msg.what == 9998) {
                // state_engine send us a signal to notify it'll die !
                Tracer.d(mytag, "cache engine disappeared ===> Harakiri !");
                session = null;
                realtime = false;
                removeView(LL_background);
                myself.setVisibility(GONE);
                if (container != null) {
                    container.removeView(myself);
                    container.recomputeViewAttributes(myself);
                }
                try {
                    finalize();
                } catch (Throwable t) {
                } //kill the handler thread itself
            }
        }

    }; //End of handler

    //================================================================================
    /*
     * New mechanism to be notified by widgetupdate engine when our value is changed
     * 
     */
    WidgetUpdate cache_engine = WidgetUpdate.getInstance();
    if (cache_engine != null) {
        session = new Entity_client(dev_id, state_key, mytag, handler, session_type);
        if (tracerengine.get_engine().subscribe(session)) {
            realtime = true; //we're connected to engine
            //each time our value change, the engine will call handler
            handler.sendEmptyMessage(9999); //Force to consider current value in session
        }

    }
    //================================================================================
    //updateTimer();   //Don't use anymore cyclic refresh....   

}

From source file:org.vaadin.addons.locationtextfield.GoogleGeocoder.java

protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException {
    final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>();
    try {//from   ww w  . j  a  v  a 2 s.  c  om
        JSONObject obj = new JSONObject(input);
        if ("OK".equals(obj.getString("status"))) {
            JSONArray results = obj.getJSONArray("results");
            boolean ambiguous = results.length() > 1;
            int limit = results.length();
            if (this.getLimit() > 0)
                limit = Math.min(this.getLimit(), limit);
            for (int i = 0; i < limit; i++) {
                JSONObject result = results.getJSONObject(i);
                GeocodedLocation loc = new GeocodedLocation();
                loc.setAmbiguous(ambiguous);
                loc.setOriginalAddress(address);
                loc.setGeocodedAddress(result.getString("formatted_address"));
                JSONArray components = result.getJSONArray("address_components");
                for (int j = 0; j < components.length(); j++) {
                    JSONObject component = components.getJSONObject(j);
                    String value = component.getString("short_name");
                    JSONArray types = component.getJSONArray("types");
                    for (int k = 0; k < types.length(); k++) {
                        String type = types.getString(k);
                        if ("street_number".equals(type))
                            loc.setStreetNumber(value);
                        else if ("route".equals(type))
                            loc.setRoute(value);
                        else if ("locality".equals(type))
                            loc.setLocality(value);
                        else if ("administrative_area_level_1".equals(type))
                            loc.setAdministrativeAreaLevel1(value);
                        else if ("administrative_area_level_2".equals(type))
                            loc.setAdministrativeAreaLevel2(value);
                        else if ("country".equals(type))
                            loc.setCountry(value);
                        else if ("postal_code".equals(type))
                            loc.setPostalCode(value);
                    }
                }
                JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
                loc.setLat(location.getDouble("lat"));
                loc.setLon(location.getDouble("lng"));
                loc.setType(getLocationType(result));
                locations.add(loc);
            }
        }
    } catch (JSONException e) {
        throw new GeocodingException(e.getMessage(), e);
    }
    return locations;
}

From source file:org.vaadin.addons.locationtextfield.GoogleGeocoder.java

private LocationType getLocationType(JSONObject result) throws JSONException {
    if (!result.has("types"))
        return LocationType.UNKNOWN;
    JSONArray types = result.getJSONArray("types");
    for (int i = 0; i < types.length(); i++) {
        final String type = types.getString(i);
        if ("street_address".equals(type))
            return LocationType.STREET_ADDRESS;
        else if ("route".equals(type))
            return LocationType.ROUTE;
        else if ("intersection".equals(type))
            return LocationType.INTERSECTION;
        else if ("country".equals(type))
            return LocationType.COUNTRY;
        else if ("administrative_area_level_1".equals(type))
            return LocationType.ADMIN_LEVEL_1;
        else if ("administrative_area_level_2".equals(type))
            return LocationType.ADMIN_LEVEL_2;
        else if ("locality".equals(type))
            return LocationType.LOCALITY;
        else if ("neighborhood".equals(type))
            return LocationType.NEIGHBORHOOD;
        else if ("postal_code".equals(type))
            return LocationType.POSTAL_CODE;
        else if ("point_of_interest".equals(type))
            return LocationType.POI;
    }/*from  www  .j  a v a 2s  .  com*/
    return LocationType.UNKNOWN;
}

From source file:edu.mit.mobile.android.locast.data.tags.TaggableUtils.java

public static String toFlattenedString(JSONArray ja) throws JSONException {
    final int len = ja.length();
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        if (i > 0) {
            sb.append(Tag.TAG_DELIM);/*  w w w .ja  v  a 2 s  . c o  m*/
        }
        sb.append(ja.getString(i));
    }
    return sb.toString();
}

From source file:info.aamulumi.tomate.APIConnection.java

/**
 * Send a GET request and create a list with returned JSON datas.
 * The JSONObject returned by server must have :
 * - success : int - 1 if request is successful
 * - data : JSONArray - contains datas which will be parsed
 *
 * @param url            - url to access
 * @param parseMethod    - name of the method used to parse an object in data
 * @param urlParameters  - parameters send in URL
 * @param bodyParameters - parameters send in body (encoded)
 * @return the list of parsed elements//from   w  w w.j  a v  a 2s. c  o  m
 */
private static <T> ArrayList<T> getItems(String url, String parseMethod, HashMap<String, String> urlParameters,
        HashMap<String, String> bodyParameters) {
    ArrayList<T> list = new ArrayList<>();

    // Get parseMethod
    Class<?>[] cArg = new Class[1];
    cArg[0] = JSONObject.class;

    Method parse;
    try {
        parse = APIConnection.class.getMethod(parseMethod, cArg);
    } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
        return null;
    }

    // Do the request
    JSONObject json = makeHttpRequest(url, GET, urlParameters, bodyParameters);

    if (json == null)
        return null;
    try {
        int success = json.getInt("success");
        // Parse if successful
        if (success == 1) {
            JSONArray data = json.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                @SuppressWarnings("unchecked")
                T tmp = (T) parse.invoke(APIConnection.class, data.getJSONObject(i));
                list.add(tmp);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return list;
}

From source file:com.ichi2.preferences.StepsPreference.java

/**
 * Check if the string is a valid format for steps and return that string, reformatted for better usability if
 * needed.// w  ww.j  a v a 2s  .  c  o  m
 * 
 * @param steps User input in text editor.
 * @return The correctly formatted string or null if the input is not valid.
 */
private String getValidatedStepsInput(String steps) {
    JSONArray ja = convertToJSON(steps);
    if (ja == null) {
        return null;
    } else {
        StringBuilder sb = new StringBuilder();
        try {
            for (int i = 0; i < ja.length(); i++) {
                sb.append(ja.getString(i)).append(" ");
            }
            return sb.toString().trim();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.ichi2.preferences.StepsPreference.java

/**
 * Convert steps format.//from  ww  w. j  av a 2  s . co  m
 * 
 * @param a JSONArray representation of steps.
 * @return The steps as a space-separated string.
 */
public static String convertFromJSON(JSONArray a) {
    StringBuilder sb = new StringBuilder();
    try {
        for (int i = 0; i < a.length(); i++) {
            sb.append(a.getString(i)).append(" ");
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return sb.toString().trim();
}

From source file:de.andidog.phonegapplugins.ActionBarSherlockTabBarPlugin.java

@Override
public boolean execute(String action, final JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("setTabSelectedListener")) {
        this.callback = null;

        if (args.length() != 0)
            throw new AssertionError("setTabSelectedListener takes no arguments");

        this.callback = callbackContext;

        return true;
    } else if (action.equals("hide")) {
        final ActionBar actionBar = sherlock.getActionBar();
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override/* w w w . j  a  v a 2s  . com*/
            public void run() {
                actionBar.hide();
            }
        });
        return true;
    } else if (action.equals("show")) {
        final ActionBar actionBar = sherlock.getActionBar();
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                actionBar.show();
            }
        });
        return true;
    } else if (action.equals("selectItem")) {
        if (args.length() != 1)
            throw new AssertionError("selectItem takes tab tag as only argument");

        final ActionBar actionBar = sherlock.getActionBar();
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int count = actionBar.getTabCount();
                boolean found = false;

                try {
                    for (int i = 0; i < count; ++i) {
                        Tab t = actionBar.getTabAt(i);
                        if (t.getTag().equals(args.get(0))) {
                            actionBar.selectTab(t);
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                        Log.e(TAG, "Tab '" + args.get(0) + "' not found");
                } catch (JSONException e) {
                    // Can't happen
                    Log.e(TAG, "", e);
                }
            }
        });

        return true;
    } else if (action.equals("_init")) {
        // This is the signal send from the JavaScript that forces construction of this plugin
        if (onInitListener != null) {
            onInitListener.onActionBarSherlockTabBarPluginInitialized();
            onInitListener = null;
        }

        return true;
    } else {
        Log.e(TAG, "Invalid call: " + action);
        return false;
    }
}

From source file:com.vsu.bruteremote.FileBrowser.java

private FileBrowserItem[] parse(String jString) throws Exception {
    List<FileBrowserItem> items = new ArrayList<FileBrowserItem>();

    JSONObject jObject = new JSONObject(jString);

    String dir = jObject.getString("dir");
    JSONArray subdirArray = jObject.getJSONArray("subdir");
    JSONArray fileArray = jObject.getJSONArray("file");

    for (int ix = 0; ix < subdirArray.length(); ix++) {
        JSONObject obj = subdirArray.getJSONObject(ix);

        String display = obj.getString("display");
        String name = obj.getString("name");
        String path = obj.getString("path");

        items.add(new FileBrowserItem(display, name, dir, path, true));
    }/*from w w w  . j a  va  2 s.  com*/

    for (int ix = 0; ix < fileArray.length(); ix++) {
        JSONObject obj = fileArray.getJSONObject(ix);

        String display = obj.getString("display");
        String name = obj.getString("name");
        String path = obj.getString("path");

        items.add(new FileBrowserItem(display, name, dir, path, false));
    }

    return items.toArray(new FileBrowserItem[0]);
}