Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:com.aokp.romcontrol.github.tasks.DisplayProjectsListTask.java

private void loadProjectsToArray(JSONArray repoProjectsArray) {
    // scroll through each item in array (projects in repo organization)
    for (int i = 0; i < repoProjectsArray.length(); i++) {
        try {//from w ww  . j ava 2  s.  co m
            final JSONObject projectsObject = (JSONObject) repoProjectsArray.get(i);
            final Preference mProject = mCategory.getPreferenceManager().createPreferenceScreen(mContext);
            // extract info about each project
            final String projectName = projectsObject.getString("name");
            String projectDescription = projectsObject.getString("description");
            int githubProjectId = projectsObject.getInt("id");
            // apply info to our preference screen
            mProject.setKey(projectName);
            if (projectDescription.contains("") || projectDescription == null) {
                mProject.setTitle(projectName);
                mProject.setSummary(projectDescription);
            } else {
                mProject.setTitle(projectDescription);
                mProject.setSummary(projectName);
            }
            mProject.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference p) {
                    AlertDialog.Builder adb = new AlertDialog.Builder(mAlertDialog.getContext());
                    if (!mFavPackagesStorage.isFavProject(projectName)) {
                        adb.setNegativeButton(R.string.changelog_add_to_favs_list,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Log.d(TAG, "fav packages size=="
                                                + mFavPackagesStorage.getFavProjects().size());
                                        if (mFavPackagesStorage.getFavProjects().size() > 0) {
                                            mPreferenceScreen.addPreference(mFavProjects);
                                        }
                                        mFavPackagesStorage.addProject(projectName);
                                        mCategory.removePreference(mProject);
                                        mFavProjects.addPreference(mProject);
                                    }
                                }).setMessage(R.string.add_favs_or_view);
                    } else {
                        adb.setNegativeButton(R.string.changelog_remove_from_favs_list,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mFavPackagesStorage.removeProject(projectName);
                                        mFavProjects.removePreference(mProject);
                                        mCategory.addPreference(mProject);
                                        Log.d(TAG, "fav packages size=="
                                                + mFavPackagesStorage.getFavProjects().size());
                                        if (mFavPackagesStorage.getFavProjects().size() == 1) {
                                            mPreferenceScreen.removePreference(mFavProjects);
                                        }
                                    }
                                }).setMessage(R.string.remove_favs_or_view);
                    }
                    adb.setPositiveButton(R.string.changelog_view_commits,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    FragmentTransaction transaction = mFragmentManager.beginTransaction();
                                    CommitsFragment commitFragment = new CommitsFragment(mAlertDialog,
                                            projectName);
                                    transaction.addToBackStack(null);
                                    transaction.replace(mId, commitFragment, projectName);
                                    transaction.commit();
                                }
                            }).create().show();
                    return true;
                }
            });
            if (mFavPackagesStorage.isFavProject(projectName)) {
                if (mFavProjects.findPreference(projectName) == null) {
                    Log.d(TAG, "found Favorite Project: " + projectName);
                    mFavProjects.addPreference(mProject);
                }
            } else {
                if (DEBUG)
                    Log.d(TAG, "adding normal project: " + projectName);
                mCategory.addPreference(mProject);
            }
        } catch (JSONException badJsonRequest) {
            Log.e(TAG, "failed to parse required info about project", badJsonRequest);
        }
    }
    if (mFavPackagesStorage.getFavProjects().size() > 0)
        mPreferenceScreen.addPreference(mFavProjects);
}

From source file:com.yairkukielka.feedhungry.EntryListFragment.java

private Response.Listener<JSONObject> createMyReqSuccessListener(final boolean calledByScrolListener) {
    return new Response.Listener<JSONObject>() {
        @Override/*from w w w.  ja  v a 2  s .c  o m*/
        public void onResponse(JSONObject response) {
            try {
                if (!calledByScrolListener) {
                    removeLoadingFragment();
                }
                if (response.has("continuation")) {
                    continuation = response.getString("continuation");
                } else {
                    // to mark the end of the scrolling and to not ask for
                    // more entries
                    continuation = null;
                }
                JSONArray items = response.getJSONArray("items");
                for (int i = 0; i < items.length(); i++) {
                    ListEntry e = new ListEntry((JSONObject) items.get(i));
                    mEntries.add(e);
                }
                if (!mHasData) {
                    mHasData = true;
                }
                mAdapter.notifyDataSetChanged();
                setLastStreamLoaded();
            } catch (JSONException e) {
                if (e != null && e.getMessage() != null) {
                    Log.e(TAG, e.getMessage());
                }
                showErrorDialog(e.getMessage());
            }
        }
    };
}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

@Test
public void testGetWorkspaces() throws IOException, SAXException, JSONException {
    WebRequest request = new GetMethodWebRequest(SERVER_LOCATION + "/workspace");
    setAuthentication(request);//from w w  w.  j  a v  a 2s.c  om
    WebResponse response = webConversation.getResponse(request);

    //before creating an workspaces we should get an empty list
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("application/json", response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No workspace information in response", responseObject);
    String userId = responseObject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(userId);
    assertEquals(testUserId, responseObject.optString("UserName"));
    JSONArray workspaces = responseObject.optJSONArray("Workspaces");
    assertNotNull(workspaces);
    assertEquals(0, workspaces.length());

    //now create a workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testGetWorkspaces";
    response = basicCreateWorkspace(workspaceName);
    responseObject = new JSONObject(response.getText());
    String workspaceId = responseObject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(workspaceId);

    //get the workspace list again
    request = new GetMethodWebRequest(SERVER_LOCATION + "/workspace");
    setAuthentication(request);
    response = webConversation.getResponse(request);

    //assert that the workspace we created is found by a subsequent GET
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("application/json", response.getContentType());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No workspace information in response", responseObject);
    assertEquals(userId, responseObject.optString(ProtocolConstants.KEY_ID));
    assertEquals(testUserId, responseObject.optString("UserName"));
    workspaces = responseObject.optJSONArray("Workspaces");
    assertNotNull(workspaces);
    assertEquals(1, workspaces.length());
    JSONObject workspace = (JSONObject) workspaces.get(0);
    assertEquals(workspaceId, workspace.optString(ProtocolConstants.KEY_ID));
    assertNotNull(workspace.optString(ProtocolConstants.KEY_LOCATION, null));
}

From source file:eu.sathra.io.IO.java

private Object getValue(JSONArray array, Class<?> clazz) throws Exception {

    Object parsedArray = Array.newInstance(clazz, array.length());

    for (int c = 0; c < array.length(); ++c) {
        if ((clazz.equals(String.class) || clazz.isPrimitive()) && !clazz.equals(float.class)) {
            Array.set(parsedArray, c, array.get(c));
        } else if (clazz.equals(float.class)) {
            Array.set(parsedArray, c, (float) array.getDouble(c));
        } else if (clazz.isArray()) {
            // nested array
            Array.set(parsedArray, c, getValue(array.getJSONArray(c), float.class)); // TODO
        } else {//from   w  ww  . j  a  v  a 2  s.co m
            Array.set(parsedArray, c, load(array.getJSONObject(c), clazz));
        }
    }

    return parsedArray;
}

From source file:glebivanov.sampleweatherapp.JSONWeatherParser.java

public static Weather getSearchedCity(String data) throws JSONException {
    Weather weather = new Weather();

    // We create out JSONObject from the data
    JSONObject jObj = new JSONObject(data);

    int count = getInt("count", jObj);
    if (count > 0) {
        JSONArray citylistArray = getArray("list", jObj);
        weather = getWeather(citylistArray.get(0).toString());
    }//  w w  w .  j  av  a  2  s .c  o m

    return weather;
}

From source file:com.google.android.libraries.cast.companionlibrary.utils.Utils.java

/**
 * Builds and returns a {@link MediaInfo} that was wrapped in a {@link Bundle} by
 * <code>mediaInfoToBundle</code>. It is assumed that the type of the {@link MediaInfo} is
 * {@code MediaMetaData.MEDIA_TYPE_MOVIE}
 *
 * @see <code>mediaInfoToBundle()</code>
 *//*from   w w w  . j av  a2 s  .  co  m*/
public static MediaInfo bundleToMediaInfo(Bundle wrapper) {
    if (wrapper == null) {
        return null;
    }

    MediaMetadata metaData = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

    metaData.putString(MediaMetadata.KEY_SUBTITLE, wrapper.getString(MediaMetadata.KEY_SUBTITLE));
    metaData.putString(MediaMetadata.KEY_TITLE, wrapper.getString(MediaMetadata.KEY_TITLE));
    metaData.putString(MediaMetadata.KEY_STUDIO, wrapper.getString(MediaMetadata.KEY_STUDIO));
    ArrayList<String> images = wrapper.getStringArrayList(KEY_IMAGES);
    if (images != null && !images.isEmpty()) {
        for (String url : images) {
            Uri uri = Uri.parse(url);
            metaData.addImage(new WebImage(uri));
        }
    }
    String customDataStr = wrapper.getString(KEY_CUSTOM_DATA);
    JSONObject customData = null;
    if (!TextUtils.isEmpty(customDataStr)) {
        try {
            customData = new JSONObject(customDataStr);
        } catch (JSONException e) {
            LOGE(TAG, "Failed to deserialize the custom data string: custom data= " + customDataStr);
        }
    }
    List<MediaTrack> mediaTracks = null;
    if (wrapper.getString(KEY_TRACKS_DATA) != null) {
        try {
            JSONArray jsonArray = new JSONArray(wrapper.getString(KEY_TRACKS_DATA));
            mediaTracks = new ArrayList<MediaTrack>();
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = (JSONObject) jsonArray.get(i);
                    MediaTrack.Builder builder = new MediaTrack.Builder(jsonObj.getLong(KEY_TRACK_ID),
                            jsonObj.getInt(KEY_TRACK_TYPE));
                    if (jsonObj.has(KEY_TRACK_NAME)) {
                        builder.setName(jsonObj.getString(KEY_TRACK_NAME));
                    }
                    if (jsonObj.has(KEY_TRACK_SUBTYPE)) {
                        builder.setSubtype(jsonObj.getInt(KEY_TRACK_SUBTYPE));
                    }
                    if (jsonObj.has(KEY_TRACK_CONTENT_ID)) {
                        builder.setContentId(jsonObj.getString(KEY_TRACK_CONTENT_ID));
                    }
                    if (jsonObj.has(KEY_TRACK_LANGUAGE)) {
                        builder.setLanguage(jsonObj.getString(KEY_TRACK_LANGUAGE));
                    }
                    if (jsonObj.has(KEY_TRACKS_DATA)) {
                        builder.setCustomData(new JSONObject(jsonObj.getString(KEY_TRACKS_DATA)));
                    }
                    mediaTracks.add(builder.build());
                }
            }
        } catch (JSONException e) {
            LOGE(TAG, "Failed to build media tracks from the wrapper bundle", e);
        }
    }
    MediaInfo.Builder mediaBuilder = new MediaInfo.Builder(wrapper.getString(KEY_URL))
            .setStreamType(wrapper.getInt(KEY_STREAM_TYPE)).setContentType(wrapper.getString(KEY_CONTENT_TYPE))
            .setMetadata(metaData).setCustomData(customData).setMediaTracks(mediaTracks);

    if (wrapper.containsKey(KEY_STREAM_DURATION) && wrapper.getLong(KEY_STREAM_DURATION) >= 0) {
        mediaBuilder.setStreamDuration(wrapper.getLong(KEY_STREAM_DURATION));
    }

    return mediaBuilder.build();
}

From source file:com.dmbstream.android.adapter.ConcertListAdapter.java

private boolean getMoreConcerts(UrlWithParameters url) {
    final int defaultItemsPerPage = 10;

    try {/*from   w ww.  j  av a2 s  .  c  o m*/
        page = page + 1;

        Log.v(TAG, "getMoreConcerts");

        url.params.put(ApiConstants.PARAM_PAGE, page);
        if (!url.params.has(ApiConstants.PARAM_ITEMS_PER_PAGE))
            url.params.put(ApiConstants.PARAM_ITEMS_PER_PAGE, defaultItemsPerPage);

        JSONObject result = HttpConnection.postAsJson(url, rootActivity.Token);
        JSONArray items = result.getJSONArray("items");
        int size = items.length();
        if (size > 0) {
            moreConcerts = new ArrayList<Concert>(size);
            for (int i = 0; i < size; i++) {
                JSONObject item = (JSONObject) items.get(i);
                Concert concert = new Concert();
                concert.loadFromJson(item);
                moreConcerts.add(concert);
            }
        }

        int totalCount = result.getInt(ApiConstants.PARAM_TOTAL_COUNT);
        int itemsPerPage = result.getInt(ApiConstants.PARAM_RETURN_ITEMS_PER_PAGE);
        endReached = (totalCount <= page * itemsPerPage);

    } catch (Exception e) {
        Log.e(TAG, "Error getting more concerts", e);
    }

    return true;
}

From source file:org.jabsorb.ng.serializer.impl.ArraySerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONArray jso = (JSONArray) o;
    final Class<?> cc = clazz.getComponentType();
    int i = 0;//from www.j  a  v a 2  s.com
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);
    try {
        for (; i < jso.length(); i++) {
            m.setMismatch(ser.tryUnmarshall(state, cc, jso.get(i)).max(m).getMismatch());
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage() + " not found in json object", e);
    }
    return m;
}

From source file:org.jabsorb.ng.serializer.impl.ArraySerializer.java

@Override
public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    final JSONArray jso = (JSONArray) o;
    final Class<?> cc = clazz.getComponentType();
    int i = 0;//  ww  w. j a v a2 s  .  co  m

    try {
        // TODO: Is there a nicer way of doing this without all the ifs?
        if (clazz == int[].class) {
            final int arr[] = new int[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).intValue();
            }
            return arr;
        } else if (clazz == byte[].class) {
            final byte arr[] = new byte[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).byteValue();
            }
            return arr;
        } else if (clazz == short[].class) {
            final short arr[] = new short[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).shortValue();
            }
            return arr;
        } else if (clazz == long[].class) {
            final long arr[] = new long[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).longValue();
            }
            return arr;
        } else if (clazz == float[].class) {
            final float arr[] = new float[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).floatValue();
            }
            return arr;
        } else if (clazz == double[].class) {
            final double arr[] = new double[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).doubleValue();
            }
            return arr;
        } else if (clazz == char[].class) {
            final char arr[] = new char[jso.length()];
            for (; i < jso.length(); i++) {
                arr[i] = ((String) ser.unmarshall(state, cc, jso.get(i))).charAt(0);
            }
            return arr;
        } else if (clazz == boolean[].class) {
            final boolean arr[] = new boolean[jso.length()];
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ((Boolean) ser.unmarshall(state, cc, jso.get(i))).booleanValue();
            }
            return arr;
        } else {
            final Object arr[] = (Object[]) Array.newInstance(cc != null ? cc : java.lang.Object.class,
                    jso.length());
            state.setSerialized(o, arr);
            for (; i < jso.length(); i++) {
                arr[i] = ser.unmarshall(state, cc, jso.get(i));
            }

            if (List.class.isAssignableFrom(clazz)) {
                // List requested
                return Arrays.asList(arr);
            }

            // Array requested
            return arr;
        }
    } catch (final UnmarshallException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage() + " not found in json object", e);
    }
}

From source file:org.dasein.cloud.cloudsigma.compute.image.BootDriveSupport.java

@Override
protected @Nonnull MachineImage capture(@Nonnull ImageCreateOptions options,
        @Nullable AsynchronousTask<MachineImage> task) throws CloudException, InternalException {
    try {//from  w ww.j av  a 2  s.c o m
        if (task != null) {
            task.setStartTime(System.currentTimeMillis());
        }
        VirtualMachine vm;
        boolean restart = false;

        vm = provider.getComputeServices().getVirtualMachineSupport()
                .getVirtualMachine(options.getVirtualMachineId());
        if (vm == null) {
            throw new CloudException("Virtual machine not found: " + options.getVirtualMachineId());
        }
        if (!VmState.STOPPED.equals(vm.getCurrentState())) {
            restart = true;
            provider.getComputeServices().getVirtualMachineSupport().stop(options.getVirtualMachineId());
            try {
                long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 10L);
                vm = null;
                while (timeout > System.currentTimeMillis()) {
                    vm = provider.getComputeServices().getVirtualMachineSupport()
                            .getVirtualMachine(options.getVirtualMachineId());
                    if (vm.getCurrentState().equals(VmState.STOPPED)) {
                        System.out.println("Server stopped");
                        break;
                    }
                    try {
                        Thread.sleep(15000L);
                    } catch (InterruptedException ignore) {
                    }
                }
            } catch (Throwable ignore) {
            }
        }
        String driveId = vm.getProviderMachineImageId();

        try {
            if (driveId != null) {
                JSONObject object = cloneDrive(driveId, options.getName(), vm.getPlatform());

                String id = null;
                if (object.has("objects")) {
                    JSONArray jDrives = object.getJSONArray("objects");
                    JSONObject actualDrive = (JSONObject) jDrives.get(0);
                    id = actualDrive.getString("uuid");
                }
                MachineImage img = null;

                if (id != null) {
                    img = getImage(id);
                }
                if (img == null) {
                    throw new CloudException("Drive cloning completed, but no ID was provided for clone");
                }
                if (task != null) {
                    task.completeWithResult(img);
                }
                return img;
            } else {
                throw new InternalException("Drive id for cloning is null");
            }
        } catch (JSONException e) {
            throw new InternalException(e);
        } finally {
            if (restart) {
                try {
                    provider.getComputeServices().getVirtualMachineSupport()
                            .start(options.getVirtualMachineId());
                } catch (Throwable ignore) {
                    logger.warn("Failed to restart " + options.getVirtualMachineId() + " after drive cloning");
                }
            }
        }
    } finally {
        provider.release();
    }
}