Ejemplo n.º 1
0
  private static List<Address> parseResults(
      final int maxResults, final boolean parseAddressComponents, @NonNull final JSONObject o)
      throws JSONException {
    final JSONArray results = o.getJSONArray(RESULTS);
    final int count = results.length() >= maxResults ? maxResults : results.length();
    final ArrayList<Address> addressList = new ArrayList<>(count);
    for (int i = 0; i < count; i++) {

      final Address address = new Address();
      final JSONObject result = results.getJSONObject(i);

      if (result.has(FORMATTED_ADDRESS)) {
        address.setFormattedAddress(result.getString(FORMATTED_ADDRESS));
      }

      parseGeometry(result, address);

      if (parseAddressComponents) {
        parseAddressComponents(result, address);
      }

      addressList.add(address);
    }
    return addressList;
  }
  public Reitti lueReitti(File tiedosto) {
    JSONObject obj = this.lataaJsonObject(tiedosto);
    JSONArray arr = obj.getJSONArray("features");

    double[] lat = new double[arr.length()];
    double[] lon = new double[arr.length()];
    int[] aika = new int[arr.length()];

    for (int i = 0; i < arr.length(); i++) {
      JSONArray piste = arr.getJSONObject(i).getJSONObject("geometry").getJSONArray("coordinates");
      lat[i] = piste.getDouble(1);
      lon[i] = piste.getDouble(0);

      String aikaString = arr.getJSONObject(i).getJSONObject("properties").getString("time");

      DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss", Locale.ENGLISH);
      Date timestamp = null;
      try {
        timestamp = format.parse(aikaString);
      } catch (ParseException ex) {
        System.out.println("format ex");
      }
      int sekunnit = (int) timestamp.getTime() / 1000;
      aika[i] = sekunnit;
    }
    Reitti reitti = new Reitti(lon, lat, aika);
    return reitti;
  }
  public void refreshAllStories() {
    // get all topics
    if (!user.has("topics")) {
      swipeLayout.setRefreshing(false);
      return;
    }

    try {
      for (int i = 0; i < topics.length(); i++) {
        JSONObject topic = topics.getJSONObject(i);
        JSONArray topicWords = topic.getJSONObject("modifiedTopicWords").names();
        String urlParams = "";
        for (int j = 0; j < topicWords.length(); j++) {
          String curr = topicWords.getString(j);
          curr = curr.replaceAll("\\s+", "+");
          urlParams += ("words=" + curr + "&");
        }
        long timestamp = topic.getLong("lastTimeStamp");
        urlParams += ("timestamp=" + timestamp);
        String category = topic.getString("category");
        urlParams += ("&category=" + category);
        Log.d("SVF", "Would send: " + urlParams);
        new DownloadNextArticleData().execute(urlParams, Integer.toString(i));
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 4
0
  public static ArrayList<ContentProviderOperation> quoteJsonToContentVals(String JSON)
      throws JSONException {
    ArrayList<ContentProviderOperation> batchOperations = new ArrayList<>();
    JSONObject jsonObject = null;
    JSONArray resultsArray = null;
    ContentProviderOperation cpo = null;

    jsonObject = new JSONObject(JSON);
    if (jsonObject != null && jsonObject.length() != 0) {
      jsonObject = jsonObject.getJSONObject(QUERY);
      int count = Integer.parseInt(jsonObject.getString(COUNT));
      if (count == 1) {
        jsonObject = jsonObject.getJSONObject(RESULTS).getJSONObject(QUOTE);
        cpo = buildBatchOperation(jsonObject);
        if (cpo != null) {
          batchOperations.add(cpo);
        }

      } else {
        resultsArray = jsonObject.getJSONObject(RESULTS).getJSONArray(QUOTE);

        if (resultsArray != null && resultsArray.length() != 0) {
          for (int i = 0; i < resultsArray.length(); i++) {
            jsonObject = resultsArray.getJSONObject(i);
            cpo = buildBatchOperation(jsonObject);
            if (cpo != null) {
              batchOperations.add(cpo);
            }
          }
        }
      }
    }

    return batchOperations;
  }
 private Movie[] getMovieData(String movies_detail) {
   final String RESULTS = "results";
   final String TITLE = "original_title";
   final String OVER_VIEW = "overview";
   final String POSTER_PATH = "poster_path";
   final String RELEASE_DATE = "release_date";
   final String RATINGS = "vote_average";
   Movie[] movies = null;
   try {
     JSONObject movie_json = new JSONObject(movies_detail);
     JSONArray movieArray = movie_json.getJSONArray(RESULTS);
     movies = new Movie[movieArray.length()];
     for (int i = 0; i < movieArray.length(); i++) {
       JSONObject movieObject = movieArray.getJSONObject(i);
       Movie temp_movie = new Movie();
       temp_movie.setTitle(movieObject.getString(TITLE));
       temp_movie.setImage_base_url(movieObject.getString(POSTER_PATH));
       temp_movie.setOverview(movieObject.getString(OVER_VIEW));
       temp_movie.setRatings(movieObject.getDouble(RATINGS));
       temp_movie.setRelease_date(movieObject.getString(RELEASE_DATE));
       movies[i] = temp_movie;
     }
   } catch (Exception e) {
     Log.e("main", e.getMessage());
   }
   return movies;
 }
Ejemplo n.º 6
0
 private MediaConstraints constraintsFromJSON(String jsonString) throws JSONException {
   if (jsonString == null) {
     return null;
   }
   MediaConstraints constraints = new MediaConstraints();
   JSONObject json = new JSONObject(jsonString);
   JSONObject mandatoryJSON = json.optJSONObject("mandatory");
   if (mandatoryJSON != null) {
     JSONArray mandatoryKeys = mandatoryJSON.names();
     if (mandatoryKeys != null) {
       for (int i = 0; i < mandatoryKeys.length(); ++i) {
         String key = mandatoryKeys.getString(i);
         String value = mandatoryJSON.getString(key);
         constraints.mandatory.add(new MediaConstraints.KeyValuePair(key, value));
       }
     }
   }
   JSONArray optionalJSON = json.optJSONArray("optional");
   if (optionalJSON != null) {
     for (int i = 0; i < optionalJSON.length(); ++i) {
       JSONObject keyValueDict = optionalJSON.getJSONObject(i);
       String key = keyValueDict.names().getString(0);
       String value = keyValueDict.getString(key);
       constraints.optional.add(new MediaConstraints.KeyValuePair(key, value));
     }
   }
   return constraints;
 }
Ejemplo n.º 7
0
  private void assertGroupByResults(JSONArray jsonArray, Map<Object, Double> groupResultsFromAvro)
      throws JSONException {
    final Map<String, Double> groupResultsFromQuery = new HashMap<String, Double>();
    if (groupResultsFromAvro.size() > 10) {
      Assert.assertEquals(jsonArray.length(), 10);
    } else {
      Assert.assertTrue(jsonArray.length() >= groupResultsFromAvro.size());
    }
    for (int i = 0; i < jsonArray.length(); ++i) {
      groupResultsFromQuery.put(
          jsonArray.getJSONObject(i).getJSONArray("group").getString(0),
          jsonArray.getJSONObject(i).getDouble("value"));
    }

    for (final Object key : groupResultsFromAvro.keySet()) {
      String keyString;
      if (key == null) {
        keyString = "null";
      } else {
        keyString = key.toString();
      }
      if (!groupResultsFromQuery.containsKey(keyString)) {
        continue;
      }
      final double actual = groupResultsFromQuery.get(keyString);
      // System.out.println("Result from query - group:" + keyString + ", value:" + actual);
      final double expected = groupResultsFromAvro.get(key);
      // System.out.println("Result from avro - group:" + keyString + ", value:" + expected);
      try {
        Assert.assertEquals(actual, expected);
      } catch (AssertionError e) {
        throw new AssertionError(e);
      }
    }
  }
 /**
  * Convert json payload to map.
  *
  * @param payloadsArray JSON Array containing payload details
  * @return map of payloads
  */
 private Map<Integer, Map<String, String>> getPayloadsAsMap(JSONArray payloadsArray) {
   Map<Integer, Map<String, String>> payloadsMap = new HashMap<Integer, Map<String, String>>();
   for (int i = 0; i < payloadsArray.length(); i++) {
     try {
       String payload =
           payloadsArray.getJSONObject(i).getString(AnalyticsConstants.JSON_FIELD_PAYLOAD);
       JSONArray eventRefs =
           payloadsArray.getJSONObject(i).getJSONArray(AnalyticsConstants.JSON_FIELD_EVENTS);
       for (int j = 0; j < eventRefs.length(); j++) {
         int eventIndex =
             eventRefs.getJSONObject(j).getInt(AnalyticsConstants.JSON_FIELD_EVENT_INDEX);
         Map<String, String> existingPayloadMap = payloadsMap.get(eventIndex);
         if (existingPayloadMap == null) {
           Map<String, String> attributesMap = new HashMap<String, String>();
           attributesMap.put(
               eventRefs.getJSONObject(j).getString(AnalyticsConstants.JSON_FIELD_ATTRIBUTE),
               payload);
           payloadsMap.put(eventIndex, attributesMap);
         } else {
           existingPayloadMap.put(
               eventRefs.getJSONObject(j).getString(AnalyticsConstants.JSON_FIELD_ATTRIBUTE),
               payload);
         }
       }
     } catch (JSONException e) {
       throw new RuntimeException(
           "Error occured while generating payload map: " + e.getMessage(), e);
     }
   }
   return payloadsMap;
 }
Ejemplo n.º 9
0
  public static Map<String, Object> getStringPlace(String json) {
    Map<String, Object> res = new HashMap<String, Object>();

    try {
      SubjectVo mSV = new SubjectVo();
      JSONObject objItem = new JSONObject(json);
      String subjectname = objItem.getString("subjectname");
      String subjectid = objItem.getString("subjectid");
      mSV.setSubjectId(subjectid);
      mSV.setSubjectName(subjectname);
      res.put("sv", mSV);
      String[] id = null;
      String[] name = null;
      JSONArray classList = objItem.getJSONArray("classlist");
      if (classList != null && classList.length() > 0) {
        id = new String[classList.length()];
        name = new String[classList.length()];
        for (int i = 0; i < classList.length(); i++) {
          JSONObject classItem = (JSONObject) classList.get(i);
          String classid = classItem.getString("classid");
          String schoollocation = classItem.getString("schoollocation");
          name[i] = schoollocation;
          id[i] = classid;
          LogUtil.d("&&&&&&&", schoollocation + "  classid : " + classid);
        }
        res.put("name", name);
        res.put("id", id);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return res;
  }
Ejemplo n.º 10
0
 /**
  * Converts a json array to a string array
  *
  * @param json
  * @return
  */
 public static String[] jsonArrayToString(JSONArray json) throws JSONException {
   String[] values = new String[json.length()];
   for (int i = 0; i < json.length(); i++) {
     values[i] = json.getString(i);
   }
   return values;
 }
Ejemplo n.º 11
0
  public static void fillSpinner() {
    try {
      json_klassen = new JSONArray(strklasse);
      int arraylengh = (json_klassen.length() - 1);
      klasse = new String[arraylengh][3];
      int k = 0;
      for (int j = 1; j < json_klassen.length(); j++) {
        JSONArray temp;
        temp = json_klassen.getJSONArray(j);

        if (j == 37) {
          System.out.println();
        }

        klasse[k][1] = temp.getString(0);
        klasse[k][0] = temp.getString(1);
        klasse[k][2] = temp.getString(2);

        k++;
      }

      arl_klassen.clear();
      for (int i = 0; i < klasse.length; i++) {
        arl_klassen.add(klasse[i][1]);
      }

    } catch (JSONException e) {
      e.printStackTrace();
    }
    adapterspinner.notifyDataSetChanged();
    spinner_klasse.setSelection(favorit);
  }
Ejemplo n.º 12
0
  private void parseItems(List<PhotographerPlace> items, JSONObject jsonBody)
      throws IOException, JSONException {
    JSONArray resultJsonArray = jsonBody.getJSONArray("results");

    for (int i = 0; i < resultJsonArray.length(); i++) {
      PhotographerPlace item = new PhotographerPlace();
      JSONObject resultJsonObject = resultJsonArray.getJSONObject(i);
      if (resultJsonObject.has("photos")) {
        JSONArray photoJsonArray = resultJsonObject.getJSONArray("photos");
        if (photoJsonArray.length() > 0) {
          for (int j = 0; j < photoJsonArray.length(); j++) {
            JSONObject photoJsonObject = photoJsonArray.getJSONObject(j);
            item.setIconURL(photoJsonObject.getString("photo_reference"));
          }
        }
      }
      item.setAddress(resultJsonObject.getString("formatted_address"));
      item.setName(resultJsonObject.getString("name"));
      item.setID(resultJsonObject.getString("place_id"));

      // item.setPriceLevel(resultJsonObject.getString("price_level"));
      // item.setRating(resultJsonObject.getString("rating"));
      items.add(item);
    }
  }
Ejemplo n.º 13
0
  public int populateTracks(int event_id, JITrackAdapter m_trackAdapter) {
    int trackCount = 0;
    Cursor c = this.db.rawQuery("SELECT json FROM events WHERE event_id = " + event_id, null);

    if (c.getCount() == 0) {
      c.close();
      return 0;
    }

    c.moveToFirst();
    try {
      JSONObject json = new JSONObject(c.getString(0));
      JSONArray json_tracks = json.getJSONArray("tracks");
      trackCount = json_tracks.length();

      for (int i = 0; i != json_tracks.length(); i++) {
        m_trackAdapter.add(json_tracks.getJSONObject(i));
      }
    } catch (JSONException e) {
      android.util.Log.e("JoindInApp", "Could not add item to list", e);
    }

    c.close();
    return trackCount;
  }
Ejemplo n.º 14
0
  private User[] parseJson(String json) {
    // TODO: put results into list and display it

    // System.out.print(json);

    User[] users = null;

    try {
      JSONArray jsonArr = new JSONArray(json);
      users = new User[jsonArr.length()];

      Random rand = new Random();
      for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject obj = jsonArr.getJSONObject(i);
        User u =
            new User(
                obj.getInt("id"),
                obj.getJSONObject("user").getString("username"),
                String.valueOf(rand.nextInt((400 - 50) + 1) + 50),
                obj.getJSONObject("user").getString("number"),
                Float.parseFloat(obj.getJSONObject("user").getString("reputation")));
        users[i] = u;
        // System.out.print(u.toString());
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return users;
  }
Ejemplo n.º 15
0
  public static RepostList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
      return null;
    }

    RepostList reposts = new RepostList();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      reposts.previous_cursor = jsonObject.optString("previous_cursor", "0");
      reposts.next_cursor = jsonObject.optString("next_cursor", "0");
      reposts.total_number = jsonObject.optInt("total_number", 0);

      JSONArray jsonArray = jsonObject.optJSONArray("reposts");
      if (jsonArray != null && jsonArray.length() > 0) {
        int length = jsonArray.length();
        reposts.repostsList = new ArrayList<Reposts>(length);
        for (int ix = 0; ix < length; ix++) {
          reposts.repostsList.add(Reposts.parse(jsonArray.getJSONObject(ix)));
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return reposts;
  }
  private List<Place> retrievePlaces(String locationID, String type) throws IOException {

    StringBuilder urlBuilder = new StringBuilder(urlList);
    urlBuilder.append(locationID);
    urlBuilder.append("/");
    urlBuilder.append(type);
    urlBuilder.append("?lang=");
    urlBuilder.append(language);
    urlBuilder.append("&key=");
    urlBuilder.append(apiKey);

    String urlString = urlBuilder.toString();

    String genreJson = restProvider.retrieveRawInformation(urlString);
    JSONObject json = new JSONObject(genreJson);

    JSONArray data = json.getJSONArray("data");

    List<Place> result = new ArrayList<>(data.length());
    for (int i = 0; i < data.length(); i++) {

      Place place = buildPlace(data.getJSONObject(i));
      completePlace(place);
      result.add(place);
    }

    return result;
  }
  /** Unpacks the response from remote TF manager into this object. */
  @Override
  protected CommandResult unpackResponseFromJson(JSONObject json) throws JSONException {
    Status status = Status.NOT_ALLOCATED;
    FreeDeviceState state = FreeDeviceState.AVAILABLE;
    String statusString = json.getString(STATUS);
    try {
      status = CommandResult.Status.valueOf(statusString);
    } catch (IllegalArgumentException e) {
      throw new JSONException(String.format("unrecognized status '%s'", statusString));
    }

    String errorDetails = json.optString(INVOCATION_ERROR, null);
    String freeDeviceString = json.optString(FREE_DEVICE_STATE, null);
    if (freeDeviceString != null) {
      try {
        state = FreeDeviceState.valueOf(freeDeviceString);
      } catch (IllegalArgumentException e) {
        throw new JSONException(String.format("unrecognized state '%s'", freeDeviceString));
      }
    }

    Map<String, String> runMetricsMap = null;
    JSONArray jsonRunMetricsArray = json.optJSONArray(RUN_METRICS);
    if (jsonRunMetricsArray != null && jsonRunMetricsArray.length() > 0) {
      ImmutableMap.Builder<String, String> mapBuilder = new ImmutableMap.Builder<String, String>();
      for (int i = 0; i < jsonRunMetricsArray.length(); i++) {
        JSONObject runMetricJson = jsonRunMetricsArray.getJSONObject(i);
        final String key = runMetricJson.getString(RUN_METRICS_KEY);
        final String value = runMetricJson.getString(RUN_METRICS_VALUE);
        mapBuilder.put(key, value);
      }
      runMetricsMap = mapBuilder.build();
    }
    return new CommandResult(status, errorDetails, state, runMetricsMap);
  }
Ejemplo n.º 18
0
 @Override
 public void handleMessage(Message msg) {
   System.out.println("handler");
   if (msg.what == 0) {
     if (listaDeRemedios.size() > 0) listaDeRemedios.clear();
     if (jArray != null) {
       remedios = new Remedio[jArray.length()];
       for (int i = 0; i < jArray.length(); i++) {
         try {
           System.out.println("agregando..." + i);
           JSONObject json_data = jArray.getJSONObject(i);
           listaDeRemedios.add(new Remedios(json_data.getString("nombreReal"), "", 0));
         } catch (JSONException e) {
           e.printStackTrace();
         }
       }
       listaDeRemedios.add(new Remedios("Últimos Modificados :D", "", 0));
     }
     if (jArray2 != null) {
       for (int i = 0; i < jArray2.length(); i++) {
         try {
           System.out.println("agregando..." + i);
           JSONObject json_data2 = jArray2.getJSONObject(i);
           listaDeRemedios.add(new Remedios(json_data2.getString("nombreReal"), "", 0));
         } catch (JSONException e) {
           e.printStackTrace();
         }
       }
       // adapter.notifyDataSetChanged();
       // listaDeBusquedas.setAdapter(adapter);
     }
   }
   Tabs.mTitleProgressBar.setVisibility(ProgressBar.INVISIBLE);
 }
Ejemplo n.º 19
0
  public Map<String, List<JSONObject>> getAllCms() throws Exception {
    Map<String, List<JSONObject>> resultMap = new HashMap<String, List<JSONObject>>();
    int[] minMaxIds = getMinAndMaxIds();
    logger.debug("minMaxIds: " + Arrays.toString(minMaxIds));
    int length = 500;
    JSONArray cmsResultArray = null;
    for (int i = minMaxIds[0]; i < minMaxIds[1]; i += length) {
      cmsResultArray = loadCmsByPkCms(i, (i + length - 1), length);
      if (cmsResultArray != null) {
        for (int j = 0; j < cmsResultArray.length(); j++) {
          JSONObject cmsObj = cmsResultArray.getJSONObject(j);
          JSONArray cmsKeyword = cmsObj.optJSONArray("keywords");

          addJSONObjectToList(cmsObj.optString("title"), cmsObj, resultMap);
          if (cmsKeyword != null) {
            for (int k = 0; k < cmsKeyword.length(); k++) {
              addJSONObjectToList(cmsKeyword.optString(k), cmsObj, resultMap);
            }
          }
        }
      }
    }

    return resultMap;
  }
Ejemplo n.º 20
0
  /**
   * Constructs a Rate from a JSONObject.
   *
   * @param rateInformationJson The JSONObject holding the data to construct this object with.
   */
  public Rate(final JSONObject rateInformationJson) {

    final List<Room> localRooms;
    final JSONObject roomGroupJson = rateInformationJson.optJSONObject("RoomGroup");
    if (roomGroupJson != null && roomGroupJson.optJSONArray("Room") != null) {
      final JSONArray roomJson = roomGroupJson.optJSONArray("Room");
      localRooms = new ArrayList<Room>(roomJson.length());
      for (int i = 0; i < roomJson.length(); i++) {
        localRooms.add(new Room(roomJson.optJSONObject(i)));
      }
    } else if (roomGroupJson != null && roomGroupJson.optJSONObject("Room") != null) {
      localRooms = Collections.singletonList(new Room(roomGroupJson.optJSONObject("Room")));
    } else {
      localRooms = Collections.emptyList();
    }

    final JSONObject chargeableObject = rateInformationJson.optJSONObject("ChargeableRateInfo");
    final JSONObject convertedObject = rateInformationJson.optJSONObject("ConvertedRateInfo");

    chargeable = new RateInformation(chargeableObject);
    converted = convertedObject == null ? null : new RateInformation(convertedObject);

    promo = rateInformationJson.optBoolean("@promo");
    roomGroup = Collections.unmodifiableList(localRooms);
  }
  private String[] parseJSONData(String result) {
    String zipCodeArray[] = null;
    try {
      JSONObject jsonObj = new JSONObject(result);
      JSONArray arrayList = (JSONArray) jsonObj.get("postalCodes");
      zipCodeArray = new String[arrayList.length()];
      String zipCode = null;
      int iActualCount = 0;
      for (int iIndexCount = 0; iIndexCount <= arrayList.length(); ++iIndexCount) {
        try {
          zipCode = (String) ((JSONObject) arrayList.get(iIndexCount)).get("postalCode");
          zipCodeArray[iActualCount] = zipCode;
          ++iActualCount;

        } catch (org.json.JSONException e) {
          e.printStackTrace();
        }
      }

    } catch (org.json.JSONException e) {
      e.printStackTrace();
    }

    return zipCodeArray;
  }
Ejemplo n.º 22
0
 /**
  * Parses a list of Rate objects from a JSONArray representing their data.
  *
  * @param rateInformationsJson The json from which to parse
  * @return The Rate objects represented by the JSONArray.
  */
 public static List<Rate> parseRates(final JSONArray rateInformationsJson) {
   final List<Rate> rateInformations = new ArrayList<Rate>(rateInformationsJson.length());
   for (int j = 0; j < rateInformationsJson.length(); j++) {
     rateInformations.add(new Rate(rateInformationsJson.optJSONObject(j)));
   }
   return rateInformations;
 }
Ejemplo n.º 23
0
  @Override
  protected ArrayList<String> doInBackground(String... params) {

    ArrayList<String> resultList = null;
    String data;

    data = new AsyncronsTask().downloadData(params[0]);

    try {
      // Create a JSON object hierarchy from the results
      JSONObject jsonObj = new JSONObject(data);
      JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

      // Extract the Place descriptions from the results
      resultList = new ArrayList<String>(predsJsonArray.length());
      for (int i = 0; i < predsJsonArray.length(); i++) {
        resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
      }
    } catch (JSONException e) {
      Log.e("LOG_TAG", "Cannot process JSON results", e);
    }

    Log.e("1", "" + resultList.toString());
    return resultList;
  }
  public String getPersonaggiStoriciJSON() {
    logger.info("ListaPersonaggi JSON");

    String res = "";

    Sparql sp = new Sparql(queryPersonaggiStorici, endpoint);
    JSONObject result = new JSONObject(sp.returnJSON());
    JSONArray jarray = result.getJSONObject("results").getJSONArray("bindings");
    JSONArray arrayRisultati = new JSONArray(); // riscrivamo i risultati in maniera piu bella
    for (int i = 0; i < jarray.length(); i++) {
      JSONObject row = new JSONObject();
      String uri = jarray.getJSONObject(i).getJSONObject("person").getString("value");
      String name = jarray.getJSONObject(i).getJSONObject("name").getString("value");
      String job = "";
      if (jarray.getJSONObject(i).has("job"))
        job = jarray.getJSONObject(i).getJSONObject("job").getString("value");
      row.accumulate("URI", uri);
      row.accumulate("name", name);
      row.accumulate("icona", Place.returnJobIcona(job));
      row.accumulate(
          "detailEndpoint",
          ServerTomcat
              + infoPersonaggio
              + uri.replace("http://www.trentinocultura.net/asp_cat/main.asp?", ""));
      arrayRisultati.put(row);
    }
    logger.info("Restituiti " + arrayRisultati.length() + " personaggi storici");

    // return sp.returnJSON();
    return arrayRisultati.toString();
  }
Ejemplo n.º 25
0
 private String[] readPlaybackSpeedArray(String valueFromPrefs) {
   String[] selectedSpeeds = null;
   // If this preference hasn't been set yet, return the default options
   if (valueFromPrefs == null) {
     String[] allSpeeds = context.getResources().getStringArray(R.array.playback_speed_values);
     List<String> speedList = new LinkedList<String>();
     for (String speedStr : allSpeeds) {
       float speed = Float.parseFloat(speedStr);
       if (speed < 2.0001 && speed * 10 % 1 == 0) {
         speedList.add(speedStr);
       }
     }
     selectedSpeeds = speedList.toArray(new String[speedList.size()]);
   } else {
     try {
       JSONArray jsonArray = new JSONArray(valueFromPrefs);
       selectedSpeeds = new String[jsonArray.length()];
       for (int i = 0; i < jsonArray.length(); i++) {
         selectedSpeeds[i] = jsonArray.getString(i);
       }
     } catch (JSONException e) {
       Log.e(TAG, "Got JSON error when trying to get speeds from JSONArray");
       e.printStackTrace();
     }
   }
   return selectedSpeeds;
 }
Ejemplo n.º 26
0
    @Override
    protected void onPostExecute(String s) {
      super.onPostExecute(s);
      Log.d("Spinner", "e onPostExecute---->" + s);
      try {
        JSONArray jsonArray = new JSONArray(s);
        reasonStrings = new String[jsonArray.length() + 1];
        idStrings = new String[jsonArray.length() + 1];

        for (int i = 0; i < jsonArray.length(); i++) {
          if (i == 0) {
            reasonStrings[i] = "--select reason--";
            idStrings[i] = "";
          } else {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            reasonStrings[i] = jsonObject.getString("res_name");
            idStrings[i] = jsonObject.getString("res_id");
          }
        }

        ArrayAdapter arrayAdapter =
            new ArrayAdapter(context, R.layout.support_simple_spinner_dropdown_item, reasonStrings);
        reason1Spinner.setAdapter(arrayAdapter);
        reason2Spinner.setAdapter(arrayAdapter);

      } catch (Exception e) {
        Log.d("Spinner", "e onPostExecute+++" + e.toString());
      }
    }
  public ArrayList<RecipeGeneral> getRecipesFromJSONString(String result2) {
    ArrayList<RecipeGeneral> recipes = new ArrayList<RecipeGeneral>();
    try {
      JSONArray jsonElements = new JSONArray(result2);
      Log.d(TAG, "In MainListActivity getRecipes(): " + jsonElements);
      Log.d(TAG, "jsonElements.length(): " + jsonElements.length());
      for (int i = 0; i < jsonElements.length(); i++) {
        Recipe favRecipe = (ModelUtil.getRecipeFromJSON(jsonElements.getJSONObject(i)));
        Log.d(TAG, "Recipe: " + jsonElements.getJSONObject(i));
        JSONArray stepsArray = jsonElements.getJSONObject(i).getJSONArray("steps");
        Log.d(TAG, "Steps: " + jsonElements.getJSONObject(i).getJSONArray("steps"));
        ArrayList<Step> favSteps = new ArrayList<Step>();

        for (int j = 0; j < stepsArray.length(); j++) {
          Step step = ModelUtil.getStepFromJSON(stepsArray.getJSONObject(j));
          Log.d(TAG, "Step: " + step);
          favSteps.add(step);
        }
        Log.d(TAG, "Steps ArrayList: " + favSteps);
        favRecipe.setSteps(favSteps);
        recipes.add((RecipeGeneral) favRecipe);
        Log.d(TAG, "In MainListActivity getRecipes() Adding every recipe");
      }
    } catch (Exception e) {
      e.printStackTrace();
      receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
    }
    return recipes;
  }
Ejemplo n.º 28
0
  /**
   * @param jsonData is the total data sent by the OI Note
   * @return It return the array of RecievedData which contains localId and JSON string containing
   *     data like title etc.
   */
  private RecievedData[] getRecievedArray(String jsonData) {
    RecievedData[] rdArray = null;
    try {
      JSONObject jdataobj = new JSONObject(jsonData);
      JSONArray jsonArray = jdataobj.getJSONArray("data");
      rdArray = new RecievedData[jsonArray.length()];
      if (debug)
        Log.d(
            TAG, "length of rdArray and JsonArray: " + rdArray.length + " : " + jsonArray.length());
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jobj = jsonArray.getJSONObject(i);
        int localid = jobj.getInt("id");
        String jsonString = jobj.getString("jsonString");
        rdArray[i] = new RecievedData(localid, jsonString);
        if (debug)
          Log.d(
              TAG,
              "local id inside the RD object: "
                  + rdArray[i].getLocal_id()
                  + " "
                  + rdArray[i].getJsonString());
      }

    } catch (JSONException e) {
      if (debug) Log.d(TAG, "json exception occured", e);
    }
    return rdArray;
  }
 public void doAfterPostSuccess(String s, int articleId) {
   if (s.equals("IOException")) {
     Toast.makeText(
             getActivity().getApplicationContext(),
             "Server not available, please contact application owner",
             Toast.LENGTH_SHORT)
         .show();
     mAdapter.notifyDataSetChanged();
     swipeLayout.setRefreshing(false);
     return;
   }
   addNewArticleToUser(s, articleId);
   done++;
   Log.d("SVF", "Done " + done + " out of " + topics.length());
   if (done == topics.length()) {
     swipeLayout.setRefreshing(false);
     ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
     try {
       JSONArray sortedTopics =
           ValuesAndUtil.getInstance().sortTopicsArray(user.getJSONArray("topics"));
       user.put("topics", sortedTopics);
       ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
       mAdapter = new StoriesViewAdapter(sortedTopics);
       if (numUpdated == 0) {
         Toast.makeText(getActivity(), "No updates found for any stories", Toast.LENGTH_SHORT)
             .show();
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
     mRecyclerView.setAdapter(mAdapter);
     Log.d("SVF", "Finished updating all articles");
   }
 }
Ejemplo n.º 30
0
 private void parseCategories(JSONArray categoryRootArray) {
   categoriesConcatenated = "";
   for (int i = 0; i < categoryRootArray.length(); i++) {
     JSONObject jsoCategory;
     try {
       jsoCategory = categoryRootArray.getJSONObject(i);
       JSONArray jsaSubCategories = jsoCategory.optJSONArray("children");
       if (jsaSubCategories.length() > 0) {
         parseCategories(jsaSubCategories);
       } else // this category is a leaf
       {
         String leafCategoryKey = jsoCategory.optString("key");
         String leafCategoryName =
             MainActivity.translationManager.getTranslation(
                 TranslationManager.MAP_NAME_CATEGORIES, leafCategoryKey);
         categoryLeafNames.add(leafCategoryName);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   boolean firstCategoryAdded = false;
   for (int i = 0; i < categoryLeafNames.size(); i++) {
     if (!firstCategoryAdded) {
       categoriesConcatenated = categoryLeafNames.get(i);
       firstCategoryAdded = true;
     } else categoriesConcatenated += ", " + categoryLeafNames.get(i);
   }
 }