Esempio n. 1
0
  /**
   * Parses the string returned by GetData into an ArrayList
   *
   * @param itemList JSON String from GetData
   * @return ArrayList<PokemonListItem> used to populate the PokemonListFragment
   */
  public ArrayList<PokemonListItem> parseListItems(String itemList) {
    // Instantiate the ArrayList
    ArrayList<PokemonListItem> pokemonListItems = new ArrayList<>();

    try {
      // Convert the String to a JSONObject
      JSONObject items = new JSONObject(itemList);

      // Get the full list of pokemon
      JSONArray pokemonItems = items.getJSONArray("pokemon");

      // Cycle through the JSONArray and add them to the ArrayList
      for (int i = 0; i < pokemonItems.length(); i++) {
        try {
          // Pull each one out, add it and move on
          JSONObject pokemon = pokemonItems.getJSONObject(i);
          PokemonListItem pokemonListItem =
              new PokemonListItem(pokemon.getString("name"), pokemon.getString("resource_uri"));
          pokemonListItems.add(pokemonListItem);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }

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

    // All done, return the ArrayList
    return pokemonListItems;
  }
Esempio n. 2
0
 public ToxicoViewModel(JSONObject json) {
   try {
     Fecha = Tools.JsonDateToDate(json.getString("Fecha"));
     ToxicosDescripcion = json.getString("ToxicosDescripcion");
   } catch (JSONException e) {
   }
 }
Esempio n. 3
0
 @RequestMapping(value = "PosterLoginServlet", produces = "application/json;charset=UTF-8")
 @ResponseBody
 public String PosterLogin(HttpServletRequest req) {
   String infor = req.getParameter("sendInfor");
   String postername = "";
   String password = "";
   System.out.println(infor);
   JSONObject json;
   try {
     json = new JSONObject(infor);
     postername = json.getString("postername");
     password = json.getString("password");
   } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   Map<String, Object> posterinfo = new HashMap<String, Object>();
   posterinfo = us.PosterLogin(postername, password);
   if (posterinfo != null && !posterinfo.toString().equals("[]")) {
     JSONObject jsonres = new JSONObject(posterinfo);
     System.out.println(jsonres.toString());
     return encodeUTF_8.encodeStr(jsonres.toString());
   } else {
     return "Failed to Login!";
   }
 }
Esempio n. 4
0
  private Blob loadVaultJson(JSONObject jsonObject, String regionId, String baseUrl)
      throws JSONException {
    String vaultName = jsonObject.getString("VaultName");
    String url;
    if (baseUrl.endsWith(vaultName)) {
      url = baseUrl;
    } else {
      url = baseUrl + "/" + vaultName;
    }

    String creationDate = jsonObject.getString("CreationDate");

    long creationTs = parseTimestamp(creationDate);

    if (jsonObject.has("SizeInBytes") && !jsonObject.isNull("SizeInBytes")) {
      Storage<Byte> storage = new Storage<Byte>(jsonObject.getLong("SizeInBytes"), Storage.BYTE);

      // somewhat dangerous: we want to specify a size for the vault, but currently
      // dasein-core only allows this specified on the Blob.getInstance() intended for
      // objects. It has a @Nonnull decorator for objectName, but we pass a null value
      // here. Currently in the implementation it does not matter.

      //noinspection ConstantConditions
      return Blob.getInstance(regionId, url, vaultName, null, creationTs, storage);
    }
    return Blob.getInstance(regionId, url, vaultName, creationTs);
  }
 private Payload doInBackgroundRegister(Payload data) {
   String username = (String) data.data[0];
   String password = (String) data.data[1];
   BasicHttpSyncer server = new RemoteServer(this, null);
   HttpResponse ret = server.register(username, password);
   String hostkey = null;
   boolean valid = false;
   data.returnType = ret.getStatusLine().getStatusCode();
   String status = null;
   if (data.returnType == 200) {
     try {
       JSONObject jo = (new JSONObject(server.stream2String(ret.getEntity().getContent())));
       status = jo.getString("status");
       if (status.equals("ok")) {
         hostkey = jo.getString("hkey");
         valid = (hostkey != null) && (hostkey.length() > 0);
       }
     } catch (JSONException e) {
     } catch (IllegalStateException e) {
       throw new RuntimeException(e);
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
   if (valid) {
     data.success = true;
     data.data = new String[] {username, hostkey};
   } else {
     data.success = false;
     if (status != null) {
       data.data = new String[] {status};
     }
   }
   return data;
 }
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
      throws JSONException {
    try {
      if (ACTION_ADD_CALENDAR_ENTRY.equals(action)) {
        JSONObject arg_object = args.getJSONObject(0);
        Intent calIntent =
            new Intent(Intent.ACTION_EDIT)
                .setType("vnd.android.cursor.item/event")
                .putExtra("beginTime", arg_object.getLong("startTimeMillis"))
                .putExtra("endTime", arg_object.getLong("endTimeMillis"))
                .putExtra("title", arg_object.getString("title"))
                .putExtra("description", arg_object.getString("description"))
                .putExtra("eventLocation", arg_object.getString("eventLocation"));

        this.cordova.getActivity().startActivity(calIntent);
        callbackContext.success();
        return true;
      }
      callbackContext.error("Invalid action");
      return false;
    } catch (Exception e) {
      System.err.println("Exception: " + e.getMessage());
      callbackContext.error(e.getMessage());
      return false;
    }
  }
    @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();
      }
    }
  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;
  }
Esempio n. 9
0
    @Override
    protected String doInBackground(String... args) {
      // String username="******";
      SharedPreferences mySharedPreferences;
      mySharedPreferences = getSharedPreferences("MyPrefs", 0);
      String email1 = mySharedPreferences.getString("email", "");
      List<NameValuePair> params = new ArrayList<>();

      params.add(new BasicNameValuePair("username", email1));

      try {

        JSONObject json = jsonParser.makeHttpRequest(RETRIVER_PROFILE, "POST", params);

        int suscess = json.getInt("sucess");
        System.out.println(suscess);
        Log.d("Register attempt", json.toString());
        // sucess is get from db status
        if (suscess == 1) {

          fname = json.getString("fname");
          lname = json.getString("lname");
          email = json.getString("email");
          phone = json.getString("phoneno");
        }

      } catch (JSONException e) {
        e.printStackTrace();
        System.out.println(e);
      }

      return null;
    }
    //	通知センターに通知を残す(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 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;
  }
  @Override
  protected ArrayList<Review> doInBackground(String... params) {
    ArrayList<Review> reviews = new ArrayList<>();
    try {
      URL url = new URL(Constant.getReviewsUrl(movie.getId()));
      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder().url(url).build();
      Response response = client.newCall(request).execute();
      String responseJSONString = response.body().string();
      if (response.isSuccessful()) {
        JSONObject responseJSON = new JSONObject(responseJSONString);
        JSONArray resultJSONArray = responseJSON.getJSONArray("results");
        for (int i = 0; i < resultJSONArray.length(); i++) {
          JSONObject reviewJSON = resultJSONArray.getJSONObject(i);
          String author = reviewJSON.getString("author");
          String content = reviewJSON.getString("content");
          Review review = new Review(movie.getId(), author, content);
          reviews.add(review);
        }
        return reviews;
      } else {
        Log.v("response", "code not 200");
        return null;
      }

    } catch (Exception e) {
      Log.v("response", e.toString());
      return null;
    }
  }
 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;
 }
Esempio n. 14
0
  /** s Requests access tokens for the given user id and valid auth token. */
  private static List<AccessToken> requestAccessTokens(String userid, String authToken)
      throws JSONException {

    Map<String, String> params = new HashMap<String, String>();
    params.put("username", userid);
    params.put("authtoken", authToken);

    String json = post(new JSONObject(params));
    if (json == null) {
      return null;
    }

    List<AccessToken> accessTokens = new ArrayList<AccessToken>();
    JSONArray tokens = new JSONArray(json);
    for (int i = 0; i < tokens.length(); i++) {

      JSONObject host = tokens.getJSONObject(i);
      AccessToken token =
          new AccessToken(
              host.getString("token"),
              host.getString("host"),
              host.getString("type"),
              host.getInt("port"),
              host.getInt("expiration"));

      accessTokens.add(token);
    }

    return accessTokens;
  }
 private SheetContent deserializeContent(JSONObject sheetJSON) throws Exception {
   SheetContent toReturn = null;
   JSONObject content = sheetJSON.optJSONObject(WorkSheetSerializationUtils.CONTENT);
   if (content == null) {
     logger.warn(
         "Sheet content not found for sheet ["
             + sheetJSON.getString(WorkSheetSerializationUtils.NAME)
             + "].");
     return null;
   }
   String designer = content.getString(WorkSheetSerializationUtils.DESIGNER);
   if (WorkSheetSerializationUtils.DESIGNER_PIVOT.equals(designer)) {
     toReturn =
         (CrosstabDefinition)
             SerializationManager.deserialize(
                 content.getJSONObject(WorkSheetSerializationUtils.CROSSTABDEFINITION),
                 "application/json",
                 CrosstabDefinition.class);
     ((CrosstabDefinition) toReturn).setStatic(false);
   } else if (WorkSheetSerializationUtils.DESIGNER_STATIC_PIVOT.equals(designer)) {
     toReturn =
         (CrosstabDefinition)
             SerializationManager.deserialize(
                 content.getJSONObject(WorkSheetSerializationUtils.CROSSTABDEFINITION),
                 "application/json",
                 CrosstabDefinition.class);
     ((CrosstabDefinition) toReturn).setStatic(true);
   } else if (WorkSheetSerializationUtils.DESIGNER_TABLE.equals(designer)) {
     toReturn = deserializeTable(content);
   } else {
     toReturn = deserializeChart(content);
   }
   return toReturn;
 }
Esempio n. 16
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();
      }
    }
Esempio n. 17
0
  public void checkTilesReporting(String localeCode) throws JSONException {
    // Slight hack: Force top sites grid to reload.
    inputAndLoadUrl(StringHelper.ABOUT_BLANK_URL);
    inputAndLoadUrl(StringHelper.ABOUT_HOME_URL);

    // Click the first tracking tile and verify the posted data.
    JSONObject response = clickTrackingTile(StringHelper.DISTRIBUTION1_LABEL);
    mAsserter.is(response.getInt("click"), 0, "JSON click index matched");
    mAsserter.is(response.getString("locale"), localeCode, "JSON locale code matched");
    mAsserter.is(
        response.getString("tiles"),
        "[{\"id\":123},{\"id\":456},{\"id\":632},{\"id\":629},{\"id\":630},{\"id\":631}]",
        "JSON tiles data matched");

    inputAndLoadUrl(StringHelper.ABOUT_HOME_URL);

    // Pin the second tracking tile.
    pinTopSite(StringHelper.DISTRIBUTION2_LABEL);

    // Click the second tracking tile and verify the posted data.
    response = clickTrackingTile(StringHelper.DISTRIBUTION2_LABEL);
    mAsserter.is(response.getInt("click"), 1, "JSON click index matched");
    mAsserter.is(
        response.getString("tiles"),
        "[{\"id\":123},{\"id\":456,\"pin\":true},{\"id\":632},{\"id\":629},{\"id\":630},{\"id\":631}]",
        "JSON tiles data matched");

    inputAndLoadUrl(StringHelper.ABOUT_HOME_URL);

    // Unpin the second tracking tile.
    unpinTopSite(StringHelper.DISTRIBUTION2_LABEL);
  }
Esempio n. 18
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;
 }
Esempio n. 19
0
 /**
  * Adds the card to the view
  *
  * @param sharedPreferences the shared preferences
  * @param key the key
  */
 private void addCard(SharedPreferences sharedPreferences, String key) {
   String json = sharedPreferences.getString(key, null);
   if (json != null) {
     try {
       JSONObject jsonData = new JSONObject(json);
       if (jsonData.has(IMAGE_KEY)) {
         String image = jsonData.getString(IMAGE_KEY);
         List<ITopic> cards = getSourceTopicModel();
         if (key.equals(POOL_KEY)) {
           cards.add(0, Cards.pool(image, getActivity()));
           removeDuplicates(POOL_KEY, cards);
         } else if (key.equals(FOOD_KEY)) {
           cards.add(0, Cards.food(image, getActivity()));
           removeDuplicates(FOOD_KEY, cards);
         }
       } else if (jsonData.has(MESSAGE_KEY)) {
         String message = jsonData.getString(MESSAGE_KEY);
         List<ITopic> cards = getSourceTopicModel();
         cards.add(0, Cards.test(message, getActivity()));
       }
       UI.execute(this::filterModel);
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
 }
    @Override
    protected Void doInBackground(Void... arg0) {
      ServiceHandler sh = new ServiceHandler();

      String jsonStr = sh.makeServiceCall(checkoutUrl, ServiceHandler.GET);

      Log.d("Response", "<" + jsonStr);

      if (jsonStr != null) {
        try {

          JSONObject jsonObj = new JSONObject(jsonStr);

          String err = jsonObj.getString("error");
          String msg = jsonObj.getString("msg");
          Log.d("err", err);

          if (err.equals("false")) {
            flag = 1;
          }

        } catch (JSONException e) {
          e.printStackTrace();
        }
      } else {
        Log.e("ServiceHandler", "Could not get data");
      }

      return null;
    }
    @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);
            IConnectBase.iConnect = new IConnectConference(jsonData);
            IConnectBase.goToConference(
                IConnectBase.iConnect.isHost, IConnectBase.iConnect.status, MessageActivity.this);
            MessageActivity.this.finish();
          } else {
            Toast.makeText(
                    getApplicationContext(), reader.getString(Global.ERROR_MSG), Toast.LENGTH_LONG)
                .show();
          }
        }

      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Esempio n. 22
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();
    }
  }
  /** Negative test case for addTimeSheets method . */
  @Test(
      groups = {"wso2.esb"},
      description = "tsheets {addTimeSheets} integration test with negative case.")
  public void testAddTimeSheetsWithNegativeCase() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:addTimeSheets");
    RestResponse<JSONObject> esbRestResponse =
        sendJsonRestRequest(
            proxyUrl, "POST", esbRequestHeadersMap, "esb_addTimeSheets_negative.json");

    JSONObject esbResponseObject =
        esbRestResponse
            .getBody()
            .getJSONObject("results")
            .getJSONObject("timesheets")
            .getJSONObject("1");

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/api/v1/timesheets";
    RestResponse<JSONObject> apiRestResponse =
        sendJsonRestRequest(
            apiEndPoint, "POST", apiRequestHeadersMap, "api_addTimeSheets_negative.json");

    JSONObject apiResponseObject =
        apiRestResponse
            .getBody()
            .getJSONObject("results")
            .getJSONObject("timesheets")
            .getJSONObject("1");
    Assert.assertEquals(apiRestResponse.getHttpStatusCode(), esbRestResponse.getHttpStatusCode());
    Assert.assertEquals(
        apiResponseObject.getString("_status_code"), esbResponseObject.getString("_status_code"));
    Assert.assertEquals(
        apiResponseObject.getString("_status_message"),
        esbResponseObject.getString("_status_message"));
  }
  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;
  }
    @Override
    protected void onPostExecute(String s) {
      super.onPostExecute(s);

      // Parse JSON
      try {
        JSONObject jsonObject = new JSONObject(s);
        String status = jsonObject.getString("result");
        if (status.equalsIgnoreCase("success")) {
          errorText.setText("Account Successfully Created!");

          // introduce a small delay to allow for user to know account is created
          Handler h = new Handler();
          h.postDelayed(
              new Runnable() {
                @Override
                public void run() {
                  myDialog.dismiss();
                }
              },
              1500);
        } else {
          String reason = jsonObject.getString("error");
          errorText.setText("Error: " + reason);
        }
      } catch (Exception e) {
        Log.d(TAG, "Parsing JSON Exception " + e.getMessage());
      }
    }
Esempio n. 26
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();
  }
Esempio n. 27
0
  public SlideModel(JSONObject ob) {
    if (ob == null) return;
    try {
      if (ob.has("id")) this.id = ob.getInt("id");
    } catch (Exception ex) {
    }

    try {
      if (ob.has("name")) this.name = ob.getString("name");
    } catch (Exception ex) {
    }

    try {
      if (ob.has("category_id")) this.categoryId = ob.getInt("category_id");
    } catch (Exception ex) {
    }

    try {
      if (ob.has("photo_path")) this.photo_path = ob.getString("photo_path");
    } catch (Exception ex) {
    }

    try {
      if (ob.has("alt")) this.alt = ob.getString("alt");
    } catch (Exception ex) {
    }

    try {
      if (ob.has("url")) this.url = ob.getString("url");
    } catch (Exception ex) {
    }
  }
  /**
   * Deserialize the Sheet
   *
   * @param sheetJSON
   * @return
   * @throws Exception
   */
  private Sheet deserializeSheet(JSONObject sheetJSON) throws Exception {
    String name = sheetJSON.getString(WorkSheetSerializationUtils.NAME);
    JSONObject header = sheetJSON.optJSONObject(WorkSheetSerializationUtils.HEADER);
    String layout = sheetJSON.optString(WorkSheetSerializationUtils.LAYOUT);
    JSONObject footer = sheetJSON.optJSONObject(WorkSheetSerializationUtils.FOOTER);

    JSONObject filtersJSON = sheetJSON.optJSONObject(WorkSheetSerializationUtils.FILTERS);
    List<Filter> filters = deserializeSheetFilters(filtersJSON);
    FiltersPosition position = FiltersPosition.TOP;
    if (filtersJSON != null) {
      position =
          FiltersPosition.valueOf(
              filtersJSON.getString(WorkSheetSerializationUtils.POSITION).toUpperCase());
    }

    JSONArray filtersOnDomainValuesJSON =
        sheetJSON.optJSONArray(WorkSheetSerializationUtils.FILTERS_ON_DOMAIN_VALUES);
    List<Attribute> filtersOnDomainValues =
        deserializeSheetFiltersOnDomainValues(filtersOnDomainValuesJSON);

    logger.debug("Deserializing sheet " + name);
    SheetContent content = deserializeContent(sheetJSON);
    logger.debug("Sheet " + name + " deserialized successfully");

    return new Sheet(
        name, layout, header, filters, position, content, filtersOnDomainValues, footer);
  }
  /**
   * 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 **********************************************************************
  }
    private void updateLabels(JSONObject tags) {
      // Z position label
      String zPosition = "";
      try {
        zPosition = NumberUtils.doubleStringCoreToDisplay(tags.getString("ZPositionUm"));
      } catch (Exception e) {
        try {
          zPosition = NumberUtils.doubleStringCoreToDisplay(tags.getString("Z-um"));
        } catch (Exception e1) {
          // Do nothing...
        }
      }
      zPosLabel_.setText("Z Position: " + zPosition + " um        ");

      // time label
      try {
        int ms = (int) tags.getDouble("ElapsedTime-ms");
        int s = ms / 1000;
        int min = s / 60;
        int h = min / 60;

        String time =
            twoDigitFormat(h)
                + ":"
                + twoDigitFormat(min % 60)
                + ":"
                + twoDigitFormat(s % 60)
                + "."
                + threeDigitFormat(ms % 1000);
        timeStampLabel_.setText("Elapsed time: " + time + "      ");
      } catch (JSONException ex) {
        ReportingUtils.logError("MetaData did not contain ElapsedTime-ms field");
      }
    }