//	通知センターに通知を残す(pecoriできる人がいます)
    private void notifyNearUser(HttpResponse res) throws Exception {
      String body = EntityUtils.toString(res.getEntity(), "UTF-8");
      JSONObject json = new JSONObject(body.toString());
      JSONArray nearUsers = json.getJSONArray("near_users");
      for (int i = 0; i < nearUsers.length(); i++) {
        JSONObject user = nearUsers.getJSONObject(i);
        String facebookId = user.getString("facebook_id");
        String name = user.getString("name");

        NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification =
            new Notification(
                android.R.drawable.btn_default,
                "近くに" + name + "さんがいるようです。",
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;

        //	Notificationが選択された場合のIntent
        Intent intent = new Intent(Intent.ACTION_VIEW);
        PendingIntent contentIntent =
            PendingIntent.getActivity(LocationDetectService.this, 0, intent, 0);
        notification.setLatestEventInfo(
            getApplicationContext(), "Pecori", "近くに" + name + "さんがいるようです。", contentIntent);
        notificationManager.notify(R.string.app_name, notification);
      }
    }
 public void addNewArticleToUser(String data, int articleId) {
   Log.d("SVF", "Modifying topic " + articleId);
   try {
     JSONObject article = new JSONObject(data);
     boolean found = article.getBoolean("found");
     if (found) {
       // update topic with new article; don't do anything if not found
       if (!ValuesAndUtil.getInstance().articleAlreadyExists(article, topics, articleId)) {
         article.remove("found");
         article.put("thumbsUp", false);
         article.put("thumbsDown", false);
         JSONObject topic = topics.getJSONObject(articleId);
         JSONArray timeline = topic.getJSONArray("timeline");
         timeline = ValuesAndUtil.getInstance().addToExistingJSON(timeline, 0, article);
         topic.put("timeline", timeline);
         topic.put("lastTimeStamp", article.getLong("date"));
         topic.put("lastSignature", article.getString("signature"));
         topic.put("lastUpdated", System.currentTimeMillis());
         Log.d("SVF", topic.toString(2));
         topics.put(articleId, topic);
         user.put("topics", topics);
         ValuesAndUtil.getInstance().saveUserData(user, getActivity().getApplicationContext());
         mAdapter.notifyItemChanged(articleId);
         numUpdated++;
       }
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
Example #3
0
  public void seenMessagesOnServer(final ArrayList<Message> messages, final boolean retry)
      throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("status", "seen");
    JSONArray messageIdArray = new JSONArray();
    for (Message message : messages) {
      if (message.getSender().getId() != mMe.getId()) {
        messageIdArray.put(message.getId());
      }
    }
    jsonObject.put("messages", messageIdArray);
    if (messageIdArray.length() == 0) {
      return;
    }
    NetworkManager.sendRequest(
        MethodsName.bULK_CHANGE_MESSAGE_STATUS_GOT,
        jsonObject,
        new NetworkReceiver() {
          @Override
          public void onResponse(Object response) {
            // message seen in server side
          }

          @Override
          public void onErrorResponse(BerimNetworkException error) {
            if (retry) {
              try {
                seenMessagesOnServer(messages, false);
              } catch (JSONException e) {

              }
            }
          }
        });
  }
  public void LoadSeedData(String strColl, String metadatafile) throws Exception {
    try {
      InputStream is = this.getClass().getResourceAsStream(metadatafile);
      String xml;
      xml = IOUtils.toString(is);
      JSONObject rwSeed = XML.toJSONObject(xml);

      if (!rwSeed.isNull("ReferralWireSeedData")) {
        JSONObject json = rwSeed.getJSONObject("ReferralWireSeedData");
        DBCollection dbcoll = store.getColl(strColl);

        Object coll = (Object) json.get(strColl);
        if (coll instanceof JSONArray) {
          JSONArray defs = (JSONArray) coll;
          for (int i = 0; i < defs.length(); i++) {
            Object obj = (JSONObject) defs.get(i);
            dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(obj.toString()));
          }
        } else {
          dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(coll.toString()));
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      log.debug("API Error: ", e);
    }
  }
Example #5
0
  static final Quilt createFromJSONObject(JSONObject jsonObject) throws JSONException {

    int rowCount = jsonObject.optInt("rowCount", 0);
    int columnCount = jsonObject.optInt("columnCount", 0);
    float width = (float) jsonObject.optDouble("width", 0);
    float height = (float) jsonObject.optDouble("height", 0);

    Quilt quilt = new Quilt(rowCount, columnCount, width, height);

    if (jsonObject.has("quiltBlocks")) {
      JSONArray jsonQuiltBlocks = jsonObject.getJSONArray("quiltBlocks");

      int index = -1;
      for (int row = 0; row < quilt.m_rowCount; ++row) {
        for (int column = 0; column < quilt.m_columnCount; ++column) {
          index += 1;
          if (index < jsonQuiltBlocks.length()) {
            JSONObject jsonQuiltBlock = jsonQuiltBlocks.optJSONObject(index);
            if (jsonQuiltBlock != null) {
              QuiltBlock quiltBlock = QuiltBlock.createFromJSONObject(jsonQuiltBlock);
              quilt.setQuiltBlock(row, column, quiltBlock);
            }
          }
        }
      }
    }

    quilt.m_new = false;
    return quilt;
  }
Example #6
0
  @Override
  /*
   * doInBackgroundの処理が終わった後に実行される処理
   */
  protected void onPostExecute(String result) {
    pd.dismiss();
    try {
      DefaultHttpClient cli = new DefaultHttpClient();
      JSONArray array = new JSONArray(result);
      arraylist = new ArrayList();

      for (int i = 0; i < array.length(); i++) {
        JSONObject jsonObject = array.getJSONObject(i);
        CustomData item = new CustomData();

        item.setTitleName(jsonObject.getString("description"));
        item.setCommentId(jsonObject.getString("id"));
        item.setIineCount(jsonObject.getString("count") + "件のいいね");
        item.setImageUrl(jsonObject.getString("image_url"));

        // とりあえず仮の画像データを読み込む
        preImg = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher);

        item.setPhoto(preImg);
        arraylist.add(item);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
    adapter = new CustomAdapter(activity, R.layout.main2, arraylist);
    list.setAdapter(adapter);
    adapter.notifyDataSetChanged();
  }
  public CommentsGetInfoResponseBean(String response) {
    super(response);
    // TODO Auto-generated constructor stub
    if (response == null) {
      return;
    }

    try {
      JSONObject obj = new JSONObject(response);
      JSONArray array = obj.optJSONArray(CommentInfo.KEY_COMMENTS);
      if (array != null) {
        comments = new ArrayList<CommentInfo>();
        int size = array.length();
        for (int i = 0; i < size; i++) {
          CommentInfo info = new CommentInfo();
          info.parse(array.optJSONObject(i));
          if (info != null) {
            comments.add(info);
          }
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (NetworkException e) {
      e.printStackTrace();
    }
  }
Example #8
0
    @Override
    protected void onPostExecute(String aVoid) {
      super.onPostExecute(aVoid);
      // masterInfo 정보 세팅해준다.
      try {
        JSONObject jsonObj = new JSONObject(aVoid);
        JSONArray UserInfoJson = jsonObj.getJSONArray("results");

        for (int i = 0; i < UserInfoJson.length(); i++) {
          JSONObject c = UserInfoJson.getJSONObject(i);
          String userid = c.getString("userid");
          String userphonenum = c.getString("userphonenum");
          String user_name = c.getString("user_name");
          String bank_name = c.getString("bank_name");
          String account_number = c.getString("account_number");

          System.out.println("user id : " + userid);
          System.out.println("user phonenum :" + userphonenum);
          System.out.println("user name :" + user_name);
          masterinfo.setMasterID(userid);
          masterinfo.setMasterName(user_name);
          masterinfo.setMasterPhoneNum(userphonenum);
          masterinfo.setMasterBankName(bank_name);
          masterinfo.setMasterBankNum(account_number);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  public static List<AroundFriends> parserAroundFriendsInfoList(String json) throws JSONException {
    List<AroundFriends> mDataList = new ArrayList<AroundFriends>();
    try {
      JSONObject result = new JSONObject(json);
      if (result.getString("status").equals("N")) {
        Log.d("TAG", "请求失败");
        return null;
      }
      JSONArray array = result.getJSONArray("memberList");
      int size = array.length();
      for (int i = 0; i < size; i++) {
        JSONObject object = (JSONObject) array.opt(i);
        AroundFriends friendsInfo = new AroundFriends();
        friendsInfo.setUserName(object.getString("user_name"));
        friendsInfo.setDescription(object.getString("remark"));
        friendsInfo.setAuthentication(
            object.getString("is_cheked").equalsIgnoreCase("Y") ? true : false);
        friendsInfo.setHeadImageURL(object.getString("face"));
        friendsInfo.setLatitude(object.getString("last_lat"));
        friendsInfo.setLongitude(object.getString("last_lng"));
        mDataList.add(friendsInfo);
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return mDataList;
  }
  @Override
  public void handleGet(ActionParameters params) throws ActionException {
    log.info("handleGet");
    final JSONObject response;
    long id = getId(params);
    try {
      if (id > -1) {
        log.info("handleGet: has id");
        User user = userService.getUser(id);
        response = user2Json(user);
      } else {
        log.info("handleGet: no id");
        List<User> users = userService.getUsers();

        log.info("found: " + users.size() + "users");
        response = new JSONObject();
        JSONArray arr = new JSONArray();
        response.put("users", arr);

        List<User> newUsers = userService.getUsersWithRoles();

        for (User user : newUsers) {
          arr.put(user2Json(user));
        }
      }
    } catch (ServiceException se) {
      throw new ActionException(se.getMessage(), se);
    } catch (JSONException je) {
      throw new ActionException(je.getMessage(), je);
    }
    log.info(response);
    ResponseHelper.writeResponse(params, response);
  }
 protected String i() {
   JSONArray localJSONArray = new JSONArray();
   Iterator localIterator = this.a.iterator();
   while (localIterator.hasNext()) {
     GraphApiMethod localGraphApiMethod = (GraphApiMethod) localIterator.next();
     JSONObject localJSONObject = new JSONObject();
     try {
       localJSONObject.put("method", localGraphApiMethod.k);
       if (localGraphApiMethod.k.equals("POST")) {
         localJSONObject.put("relative_url", localGraphApiMethod.a(false, false));
         localJSONObject.put("body", localGraphApiMethod.e().toString());
         String str1 = localGraphApiMethod.h();
         if (!StringUtils.c(str1)) localJSONObject.put("depends_on", str1);
         String str2 = localGraphApiMethod.g();
         if (!StringUtils.c(str2)) localJSONObject.put("name", str2);
         localJSONObject.put("omit_response_on_success", false);
         localJSONArray.put(localJSONObject);
       }
     } catch (JSONException localJSONException) {
       while (true) {
         Log.a(g, "error while constructing the batch param", localJSONException);
         break;
         localJSONObject.put("relative_url", localGraphApiMethod.a(false, true));
       }
     } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
       Log.a(g, "error encoding something for the batch param", localUnsupportedEncodingException);
     }
   }
   return localJSONArray.toString();
 }
  @RequestMapping("/json/app/(*:appId)/(~:appVersion)/form/options")
  public void formAjaxOptions(
      Writer writer,
      @RequestParam("appId") String appId,
      @RequestParam(value = "appVersion", required = false) String appVersion,
      @RequestParam("_dv") String dependencyValue,
      @RequestParam("_n") String nonce,
      @RequestParam("_bd") String binderData)
      throws JSONException {
    AppDefinition appDef = appService.getAppDefinition(appId, appVersion);
    FormRowSet rowSet =
        FormUtil.getAjaxOptionsBinderData(dependencyValue, appDef, nonce, binderData);

    JSONArray jsonArray = new JSONArray();
    if (rowSet != null) {
      for (Map row : rowSet) {
        Map<String, String> data = new HashMap<String, String>();
        data.put(FormUtil.PROPERTY_LABEL, (String) row.get(FormUtil.PROPERTY_LABEL));
        data.put(FormUtil.PROPERTY_VALUE, (String) row.get(FormUtil.PROPERTY_VALUE));
        jsonArray.put(data);
      }
    }

    jsonArray.write(writer);
  }
  public static List<Task> getTasksByUser(int userId) {

    List<Task> tasks = new ArrayList<Task>();

    NoJsonHttpRequest getRequest =
        new NoJsonHttpRequest(serverUrl, tasksPath + "?ownerId=" + userId, "GET");
    getRequest.addHeaderParameter(authorizationHeaderName, Util.base64Header);

    int statusCode = getRequest.execute();

    if (statusCode >= 300) {
      return tasks;
    }

    String response = getRequest.getResponse();

    try {
      JSONArray ja = new JSONArray(response);
      for (int i = 0; i < ja.length(); i++) {
        JSONObject jo = ja.getJSONObject(i);
        tasks.add(
            new Task(
                jo.getInt("id"),
                jo.getString("description"),
                jo.getInt("managerId"),
                jo.getInt("ownerId"),
                jo.getString("deadline"),
                jo.getString("status")));
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return tasks;
  }
  public static List<User> getAllUsers() {

    List<User> users = new ArrayList<User>();

    NoJsonHttpRequest getRequest = new NoJsonHttpRequest(serverUrl, usersPath, "GET");
    getRequest.addHeaderParameter(authorizationHeaderName, Util.base64Header);

    int statusCode = getRequest.execute();

    if (statusCode >= 300) {
      return users;
    }

    String response = getRequest.getResponse();

    try {
      JSONArray ja = new JSONArray(response);
      for (int i = 0; i < ja.length(); i++) {
        JSONObject jo = ja.getJSONObject(i);
        users.add(
            new User(
                jo.getInt("id"),
                jo.getString("name"),
                jo.getString("surname"),
                jo.getBoolean("isManager"),
                jo.getString("username")));
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return users;
  }
  private NetmeraDeviceDetail jsonArraytoNetmeraDeviceDetail(JSONArray array)
      throws JSONException, NetmeraException {
    NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(senderID);
    JSONObject obj = array.getJSONObject(0);

    if (obj.has("tags")) {
      JSONArray tags = obj.getJSONArray("tags");
      ArrayList<String> group = new ArrayList<String>();
      for (int i = 0; i < tags.length(); i++) {
        group.add(tags.getString(i));
      }

      deviceDetail.setDeviceGroups(group);
    }

    if (obj.has("location")) {
      JSONObject location = obj.getJSONObject("location");
      NetmeraGeoLocation geoLocation = new NetmeraGeoLocation();
      double latitude = location.getDouble("latitude");
      double longitude = location.getDouble("longitude");
      geoLocation.setLatitude(latitude);
      geoLocation.setLongitude(longitude);
      deviceDetail.setDeviceLocation(geoLocation);
    }
    return deviceDetail;
  }
Example #16
0
 public static Weibo fromJson(JSONObject weiboJsonObj) throws JSONException {
   Weibo weibo = new Weibo();
   weibo.setMid(weiboJsonObj.getLong("mid"));
   weibo.setSource(weiboJsonObj.getString("source"));
   weibo.setCreateTime(weiboJsonObj.getString("created_at"));
   weibo.setText(weiboJsonObj.getString("text"));
   weibo.setReportsNum(weiboJsonObj.getInt("reposts_count"));
   weibo.setCommentsNum(weiboJsonObj.getInt("comments_count"));
   weibo.setAttitudeStatus(weiboJsonObj.getInt("attitudes_status"));
   weibo.setLikeCount(weiboJsonObj.getInt("like_count"));
   weibo.setBid(weiboJsonObj.getString("bid"));
   weibo.setAttitudesNum(weiboJsonObj.getInt("attitudes_count"));
   if (!weiboJsonObj.isNull("pics")) {
     JSONArray picsJsonArray = weiboJsonObj.getJSONArray("pics");
     for (int i = 0; i < picsJsonArray.length(); i++) {
       JSONObject picsJsonObj = picsJsonArray.getJSONObject(i);
       weibo.getPics().add(picsJsonObj.getString("url"));
     }
   }
   if (!weiboJsonObj.isNull("user")) {
     weibo.setUser(User.fromJson(weiboJsonObj.getJSONObject("user")));
   }
   if (!weiboJsonObj.isNull("retweeted_status")) {
     weibo.setSrcWeibo(Weibo.fromJson(weiboJsonObj.getJSONObject("retweeted_status")));
   }
   return weibo;
 }
 public void a(List<PackageInfo> paramList) {
   JSONArray localJSONArray1;
   try {
     localJSONArray1 = new JSONArray();
     Iterator localIterator = paramList.iterator();
     while (localIterator.hasNext()) {
       PackageInfo localPackageInfo = (PackageInfo) localIterator.next();
       JSONObject localJSONObject = new JSONObject();
       localJSONObject.put("name", localPackageInfo.packageName);
       JSONArray localJSONArray2 = new JSONArray();
       PermissionInfo[] arrayOfPermissionInfo = localPackageInfo.permissions;
       int i = arrayOfPermissionInfo.length;
       for (int j = 0; j < i; j++) localJSONArray2.put(arrayOfPermissionInfo[j].name);
       localJSONObject.put("permissions", localJSONArray2);
       localJSONArray1.put(localJSONObject);
     }
   } catch (JSONException localJSONException) {
     BLog.e("MalwareDetector", localJSONException.getMessage());
   }
   while (true) {
     return;
     HoneyClientEvent localHoneyClientEvent =
         new HoneyClientEvent("android_malware_detected_event");
     localHoneyClientEvent.d("malware_detector");
     localHoneyClientEvent.b("description", localJSONArray1.toString());
     this.b.b(localHoneyClientEvent);
   }
 }
Example #18
0
  private void parseJSONArray(JSONArray checkIns) {

    if (checkIns == null) return;

    try {
      for (int i = 0; i < checkIns.length(); i++) {
        JSONObject checkIn = checkIns.getJSONObject(i);

        NotUsedCheckInPostItem postItem = new NotUsedCheckInPostItem();

        postItem.setCheckInId(checkIn.getLong(TAG_CHECKIN));
        Log.d(LOGTAG, "TEST ::: checkin post item id : " + checkIn.getLong(TAG_CHECKIN));
        postItem.setAuthorId(checkIn.getInt(TAG_AUTHOR));
        postItem.setPageId(checkIn.getInt(TAG_PAGE));
        postItem.setAppId(checkIn.getInt(TAG_APP));
        postItem.setPostId(checkIn.getString(TAG_POST));
        postItem.setTaggedIds(checkIn.getJSONArray(TAG_TAGGED_IDS));

        JSONObject coordObject = checkIn.getJSONObject(TAG_COORDS);
        postItem.setCoords(
            coordObject.getDouble(TAG_COORDS_LONG), coordObject.getDouble(TAG_COORDS_LAT));

        postItem.setTimeStamp(checkIn.getInt(TAG_TIMESTAMP));
        postItem.setMessage(checkIn.getString(TAG_MESSAGE));
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
    @Override
    protected void onPostExecute(String result) {
      progressView.setVisibility(View.INVISIBLE);
      enableButtons();
      JSONObject reader;
      try {
        if (result != null) {
          reader = new JSONObject(result);
          String errCode = reader.getString(Global.ERROR_CODE);
          if (errCode.equals("0")) {
            JSONObject jsonData = reader.getJSONObject(Global.DATA);
            JSONArray jsonArray = jsonData.getJSONArray("messages");

            messageArray = new ArrayList<JSONObject>();

            for (int i = 0; i < jsonArray.length(); i++) {
              JSONObject conf = jsonArray.getJSONObject(i);
              messageArray.add(conf);
            }

            onShowMessages(messageArray);
          } else {
            Toast.makeText(
                    getApplicationContext(), reader.getString(Global.ERROR_MSG), Toast.LENGTH_LONG)
                .show();
          }
        }

      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  private boolean invokeBlinkup(
      final Activity activity, final BlinkupController controller, JSONArray data) {
    int timeoutMs;
    try {
      mApiKey = data.getString(BLINKUP_ARG_API_KEY);
      mDeveloperPlanId = data.getString(BLINKUP_ARG_DEVELOPER_PLAN_ID);
      timeoutMs = data.getInt(BLINKUP_ARG_TIMEOUT_MS);
      mGeneratePlanId = data.getBoolean(BLINKUP_ARG_GENERATE_PLAN_ID);
    } catch (JSONException exc) {
      BlinkUpPluginResult.sendPluginErrorToCallback(ERROR_INVALID_ARGUMENTS);
      return false;
    }

    // if api key not valid, send error message and quit
    if (!apiKeyFormatValid()) {
      BlinkUpPluginResult.sendPluginErrorToCallback(ERROR_INVALID_API_KEY);
      return false;
    }

    Intent blinkupCompleteIntent = new Intent(activity, BlinkUpCompleteActivity.class);
    blinkupCompleteIntent.putExtra(Extras.EXTRA_DEVELOPER_PLAN_ID, mDeveloperPlanId);
    blinkupCompleteIntent.putExtra(Extras.EXTRA_TIMEOUT_MS, timeoutMs);
    controller.intentBlinkupComplete = blinkupCompleteIntent;

    // default is to run on WebCore thread, we have UI so need UI thread
    activity.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            presentBlinkUp(activity, controller);
          }
        });
    return true;
  }
Example #21
0
  /** 插入影片下载数据 */
  public synchronized long insertMovieStore(DownLoadInfo downLoadInfo) {
    if (isStoreByUrl(downLoadInfo.getDownUrl())) return PipiPlayerConstant.ISEXIT_NORMOL;
    long sec = -1;
    try {
      ContentValues values = new ContentValues();
      values.put(TableName.MovieID, downLoadInfo.getDownID());
      values.put(TableName.MovieName, downLoadInfo.getDownName());
      values.put(TableName.MovieImgUrl, downLoadInfo.getDownImg());
      values.put(TableName.MovieUrl, downLoadInfo.getDownUrl());
      values.put(TableName.MoviePlaySourKey, downLoadInfo.getDownTag());

      ArrayList<String> list = downLoadInfo.getPlayList();
      JSONArray array = new JSONArray();
      for (String string : list) array.put(string);

      values.put(TableName.MoviePlayList, array.toString());
      values.put(TableName.MoviePlayPosition, downLoadInfo.getDownPosition());
      Log.i("TAG999", "insertMovieStore MoviePlayPosition===" + downLoadInfo.getDownPosition());
      database = pipiDBHelp.getWritableDatabase();
      sec = database.insert(PipiDBHelp.STORE_TABLENAME, null, values);
    } catch (Exception e) {
      // TODO: handle exception
    }
    return sec;
  }
 /* package */ List<Object> convertJSONArrayToList(JSONArray array) {
   List<Object> list = new ArrayList<>();
   for (int i = 0; i < array.length(); ++i) {
     list.add(decode(array.opt(i)));
   }
   return list;
 }
 private static JSONArray toJSONArray(List<NamedTagHead> tags) throws JSONException {
   JSONArray retval = new JSONArray();
   for (NamedTagHead tag : tags) {
     retval.put(toJSONObject(tag));
   }
   return retval;
 }
Example #24
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;
 }
  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();
    }
  }
  public ArrayList<ElementManager> parseJSON(String jsonStr) {
    ArrayList<ElementManager> elementsList = new ArrayList<ElementManager>();
    try {
      JSONObject json = new JSONObject(jsonStr);
      if (json.has("searchAdvert")) {
        JSONObject jsonCategory = (JSONObject) json.get("searchAdvert");
        int result = jsonCategory.getInt("result");
        if (result == 1) {
          JSONArray jsonArray = jsonCategory.getJSONArray("list");
          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            int advertid = obj.getInt("advert_id");
            String photo = obj.getString("photodata");
            String title = obj.getString("title");
            Log.d("Title : ", title);
            String city = Basic.cities[obj.getInt("cityPosition")];
            String price = String.valueOf(obj.getInt("price"));
            ElementManager element = new ElementManager(advertid, photo, title, city, price);
            elementsList.add(element);
          }
        }

      } else {
        Log.i("JSON ILANARA : ", "Ilanlari çekerken hata oluştu");
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return elementsList;
  }
 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");
   }
 }
  public void getDeviceDetail(JSONArray array, CallbackContext callbackContext)
      throws JSONException {
    JSONObject deviceDetail = new JSONObject();

    NetmeraDeviceDetail netmeraDeviceDetail;
    try {
      netmeraDeviceDetail = NetmeraPushService.getDeviceDetail(Netmera.getContext());
    } catch (NetmeraException e) {
      callbackContext.error(jsonError(e));
      return;
    }
    List<String> deviceGroups = netmeraDeviceDetail.getDeviceGroups();

    if (deviceGroups.size() > 0) {
      JSONArray tagArray = new JSONArray();
      for (int i = 0; i < deviceGroups.size(); i++) {
        tagArray.put(deviceGroups.get(i));
      }
      deviceDetail.put("tags", tagArray);
    }

    NetmeraGeoLocation deviceLocation = netmeraDeviceDetail.getDeviceLocation();
    if (deviceLocation != null) {
      JSONObject location = new JSONObject();
      location.put("latitude", deviceLocation.getLatitude());
      location.put("longitude", deviceLocation.getLongitude());
      deviceDetail.put("location", location);
    }

    callbackContext.success(deviceDetail);
  }
  /**
   * getWishList로 전체 찜 목록을 가져왔을때 호출되는 함수. 기존의 Wish들을 삭제하고, 파라메터의 어레이로 다시 채운다.
   *
   * @param arr
   */
  public void setAllWishList(JSONArray arr) {
    // Realm Database **********************************************************************
    // Obtain a Realm instance
    Realm realm = Realm.getInstance(mContext);

    // remove all
    realm.beginTransaction();
    realm.allObjects(WishObject.class).clear();
    for (int i = 0; i < arr.length(); i++) {
      try {
        JSONObject jo = arr.getJSONObject(i);
        JSONObject asset = jo.getJSONObject("asset");
        String assetId = asset.getString("assetId");
        RealmResults<WishObject> results =
            mRealm.where(WishObject.class).equalTo("sAssetId", assetId).findAll();
        if (results.size() > 0) {
          // skip
        } else {
          // 객체를 생성하거나 데이터를 수정하는 작업을 수행한다.
          WishObject wish = realm.createObject(WishObject.class); // Create a new object
          wish.setsAssetId(assetId);
          wish.setsPhoneNumber(jo.getString("phoneNumber"));
          wish.setsUserId(jo.getString("userId"));
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
    // 트랜잭션 종료
    realm.commitTransaction();
    // Realm Database **********************************************************************
  }
Example #30
0
 List<uz> a(JSONArray paramJSONArray, tb paramtb)
 {
   ArrayList localArrayList = new ArrayList();
   int i = 0;
   while (i < paramJSONArray.length())
   {
     Object localObject2 = paramJSONArray.getJSONObject(i);
     Object localObject1 = tT.a((JSONObject)localObject2, "prefix");
     String str1 = tT.a((JSONObject)localObject2, "view_class");
     int k = ((JSONObject)localObject2).optInt("index", -1);
     String str2 = tT.a((JSONObject)localObject2, "contentDescription");
     int m = ((JSONObject)localObject2).optInt("id", -1);
     String str3 = tT.a((JSONObject)localObject2, "mp_id_name");
     localObject2 = tT.a((JSONObject)localObject2, "tag");
     if ("shortest".equals(localObject1)) {}
     for (int j = 1;; j = 0)
     {
       localObject1 = a(m, str3, paramtb);
       if (localObject1 != null) {
         break label175;
       }
       return e;
       if (localObject1 != null) {
         break;
       }
     }
     new StringBuilder().append("Unrecognized prefix type \"").append((String)localObject1).append("\". No views will be matched").toString();
     return e;
     label175:
     localArrayList.add(new uz(j, str1, k, ((Integer)localObject1).intValue(), str2, (String)localObject2));
     i += 1;
   }
   return localArrayList;
 }