@Override
    public View getView(int i, View view, ViewGroup viewGroup) {
      if (mAnswerArray == null) {
        if (view == null) {
          TextView textView = new TextView(mContext);
          textView.setText("暂无回答内容!");
          textView.setGravity(Gravity.CENTER);
          textView.setPadding(0, 10, 0, 10);
          textView.setTextSize(15);
          view = textView;
        }
        return view;
      }

      ViewHolder holder;
      if (view == null) {
        view = mInflater.inflate(R.layout.question_answer_item, null);
        holder = new ViewHolder();
        holder.mName = (TextView) view.findViewById(R.id.txt_name);
        holder.mContent = (TextView) view.findViewById(R.id.txt_content);
        holder.mTime = (TextView) view.findViewById(R.id.txt_time);
        holder.mPhoto = (ImageView) view.findViewById(R.id.img_photo);
        holder.mFlag = (ImageView) view.findViewById(R.id.txt_flag);
        view.setTag(holder);
      } else {
        holder = (ViewHolder) view.getTag();
      }
      try {
        JSONObject jsonObject = (JSONObject) mAnswerArray.get(i);
        holder.mName.setText(jsonObject.optString("user_name"));
        holder.mTime.setText(jsonObject.optString("time"));
        holder.mContent.setText(jsonObject.optString("answer_content"));
        int best = jsonObject.optInt("is_best");
        if (isOwnQuestion()) {
          holder.mFlag.setVisibility(View.VISIBLE);
          if (best == 0) {
            holder.mFlag.setImageResource(R.drawable.caina);
            holder.mFlag.setOnClickListener(
                new BastClickListener(jsonObject.optInt("answer_id"), 1));
          } else {
            holder.mFlag.setImageResource(R.drawable.zuijiadaan);
          }

        } else {
          if (best == 0) holder.mFlag.setVisibility(View.GONE);
          else {
            holder.mFlag.setVisibility(View.VISIBLE);
            holder.mFlag.setImageResource(R.drawable.zuijiadaan);
            ;
          }
        }
        NetComTools.getInstance(mContext)
            .loadNetImage(
                holder.mPhoto, jsonObject.optString("user_face"), R.drawable.header, 144, 144);
      } catch (Exception e) {
        e.printStackTrace();
      }

      return view;
    }
  public List<TagBean> getGSONMsgList() throws WeiboException {

    String json = getMsgListJson();
    List<TagBean> tagBeanList = new ArrayList<TagBean>();

    try {
      JSONArray array = new JSONArray(json);
      int size = array.length();
      for (int i = 0; i < size; i++) {
        TagBean bean = new TagBean();
        JSONObject jsonObject = array.getJSONObject(i);
        Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext()) {
          String key = iterator.next();
          if (key.equalsIgnoreCase("weight")) {
            String value = jsonObject.optString(key);
            bean.setWeight(value);
          } else {
            String value = jsonObject.optString(key);
            bean.setId(Integer.valueOf(key));
            bean.setName(value);
          }
        }
        tagBeanList.add(bean);
      }

    } catch (JSONException e) {
      AppLogger.e(e.getMessage());
    }

    return tagBeanList;
  }
  @Override
  public void onFinish(ServiceEvent e) {
    if (mOriginalCaller != null) {
      ServiceEvent event = null;
      if (e.StatusCode >= HttpStatus.SC_BAD_REQUEST) {
        event = createErrorEvent(e, e.Body);
        if (mOriginalCaller instanceof ServiceResponseHandler)
          dispatchServiceResponseListener(event, (ServiceResponseHandler) mOriginalCaller);
        else mOriginalCaller.onFinish(event);
      } else {
        JSONObject response = (JSONObject) e.Response;
        String body = response.optString("data");
        if (body != null) {
          event = createServiceEvent(e, body);
        } else {
          body = response.optString("error");
          event = createErrorEvent(e, body);
        }

        if (mOriginalCaller instanceof ServiceResponseHandler)
          dispatchServiceResponseListener(event, (ServiceResponseHandler) mOriginalCaller);
        else mOriginalCaller.onFinish(event);
      }
    }
  }
Example #4
0
    /**
     * Read task from json
     *
     * @param json
     * @param model
     * @param metadata
     * @throws JSONException
     */
    public static void taskFromJson(JSONObject json, Task model, ArrayList<Metadata> metadata)
        throws JSONException {
      metadata.clear();
      model.clearValue(Task.REMOTE_ID);
      model.setValue(Task.REMOTE_ID, json.getLong("id"));
      model.setValue(Task.FLAGS, 0);
      readUser(json.getJSONObject("user"), model, Task.USER_ID, Task.USER);
      readUser(json.getJSONObject("creator"), model, Task.CREATOR_ID, null);
      model.setValue(Task.COMMENT_COUNT, json.getInt("comment_count"));
      model.setValue(Task.TITLE, json.getString("title"));
      model.setValue(Task.IMPORTANCE, json.getInt("importance"));
      model.setValue(
          Task.DUE_DATE, model.createDueDate(Task.URGENCY_SPECIFIC_DAY, readDate(json, "due")));
      model.setValue(Task.COMPLETION_DATE, readDate(json, "completed_at"));
      model.setValue(Task.CREATION_DATE, readDate(json, "created_at"));
      model.setValue(Task.DELETION_DATE, readDate(json, "deleted_at"));
      model.setValue(Task.RECURRENCE, json.optString("repeat", ""));
      model.setValue(Task.NOTES, json.optString("notes", ""));
      model.setValue(Task.DETAILS_DATE, 0L);

      JSONArray tags = json.getJSONArray("tags");
      for (int i = 0; i < tags.length(); i++) {
        JSONObject tag = tags.getJSONObject(i);
        String name = tag.getString("name");
        Metadata tagMetadata = new Metadata();
        tagMetadata.setValue(Metadata.KEY, TagService.KEY);
        tagMetadata.setValue(TagService.TAG, name);
        tagMetadata.setValue(TagService.REMOTE_ID, tag.getLong("id"));
        metadata.add(tagMetadata);
      }
    }
  /** 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);
  }
Example #6
0
  private void updateQueryWithFilter(Query graphQuery, JSONObject obj) throws ParseException {
    String predicateString = obj.optString("predicate");
    JSONArray values = obj.getJSONArray("values");
    PropertyType propertyDataType = PropertyType.convert(obj.optString("propertyDataType"));
    String propertyName = obj.getString("propertyName");
    Object value0 = jsonValueToObject(values, propertyDataType, 0);

    if (PropertyType.STRING.equals(propertyDataType)
        && (predicateString == null || "".equals(predicateString))) {
      graphQuery.has(propertyName, TextPredicate.CONTAINS, value0);
    } else if (PropertyType.BOOLEAN.equals(propertyDataType)
        && (predicateString == null || "".equals(predicateString))) {
      graphQuery.has(propertyName, Compare.EQUAL, value0);
    } else if ("<".equals(predicateString)) {
      graphQuery.has(propertyName, Compare.LESS_THAN, value0);
    } else if (">".equals(predicateString)) {
      graphQuery.has(propertyName, Compare.GREATER_THAN, value0);
    } else if ("range".equals(predicateString)) {
      graphQuery.has(propertyName, Compare.GREATER_THAN_EQUAL, value0);
      graphQuery.has(
          propertyName, Compare.LESS_THAN_EQUAL, jsonValueToObject(values, propertyDataType, 1));
    } else if ("=".equals(predicateString) || "equal".equals(predicateString)) {
      graphQuery.has(propertyName, Compare.EQUAL, value0);
    } else if (PropertyType.GEO_LOCATION.equals(propertyDataType)) {
      graphQuery.has(propertyName, GeoCompare.WITHIN, value0);
    } else {
      throw new LumifyException("unhandled query\n" + obj.toString(2));
    }
  }
 public void onDone(JSONObject paramJSONObject) {
   WebViewActivity.access$000(this$0, "onDone");
   this$0.setResult(-1);
   String str1 = paramJSONObject.optString("title");
   String str2 = paramJSONObject.optString("subtitle");
   boolean bool = paramJSONObject.optBoolean("has_details");
   try {
     paramJSONObject = paramJSONObject.getString("url");
     if (TextUtils.isEmpty(paramJSONObject)) {
       AppData.a("WEBVIEW", "No URL sent with onDone", new Object[0]);
       WebViewActivity.access$300(this$0, true);
       this$0.finish();
       return;
     }
   } catch (JSONException paramJSONObject) {
     AppData.a("WEBVIEW", "Unexpected result from onDone", new Object[0]);
     WebViewActivity.access$300(this$0, true);
     this$0.finish();
     return;
   }
   Intent localIntent = new Intent("android.intent.action.VIEW");
   localIntent.setData(Uri.parse(paramJSONObject));
   localIntent.putExtra("com.yelp.android.webview_done", true);
   localIntent.putExtra("com.yelp.android.webview_title", str1);
   localIntent.putExtra("com.yelp.android.webview_subtitle", str2);
   localIntent.putExtra("com.yelp.android.webview_has_details", bool);
   WebViewActivity.access$400(this$0);
   this$0.enableLoading();
   new ch("webview_done", new WebViewActivity.ForceDirtySessionCallback(this$0, localIntent))
       .execute(new Void[0]);
 }
  /**
   * 認証トークンの解析
   *
   * @param entity
   */
  private boolean parseToken(String entity) {
    boolean retval = false;
    entity = removeJsonPrefix(entity);
    JSONObject jsonEntity;

    try {
      jsonEntity = new JSONObject(entity);

      if (jsonEntity != null) {
        Log.d(LOG_TAG, jsonEntity.toString());

        if (!jsonEntity.optString("stat").equals("ok")) {
          Log.d(LOG_TAG, "failed. : " + jsonEntity.getString("message"));
        } else {
          JSONObject jsonToken = jsonEntity.optJSONObject("auth").optJSONObject("token");
          if (jsonToken != null) {
            this.token = jsonToken.optString("_content");

            SharedPreferences preference =
                context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            Editor editor = preference.edit();
            editor.putString("token", this.token);
            editor.commit();

            retval = true;
          }
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return retval;
  }
  /**
   * トークンチェック要求のresposeを解析
   *
   * @param entity
   * @return
   */
  private boolean parseCheckToken(String entity) {
    entity = removeJsonPrefix(entity);
    JSONObject jsonEntity;
    boolean retval = false;

    try {
      jsonEntity = new JSONObject(entity);

      if (jsonEntity != null) {
        Log.d(LOG_TAG, jsonEntity.toString());

        if (!jsonEntity.optString("stat").equals("ok")) {
          Log.d(LOG_TAG, "failed. : " + jsonEntity.getString("message"));
        }

        JSONObject jsonToken = jsonEntity.optJSONObject("auth").optJSONObject("token");
        if (jsonToken != null) {
          this.token = jsonToken.optString("_content");
          retval = true;
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return retval;
  }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      // Check if this is a recycled list item and if not we inflate it

      if (convertView == null) {

        convertView = getActivity().getLayoutInflater().inflate(R.layout.favorites_row, null);
      }

      // Find the right data to put in the list item

      JSONObject theFavorite = getItem(position);

      // Put the right data into the right components

      TextView lastNameTextView = (TextView) convertView.findViewById(R.id.name);

      lastNameTextView.setText(theFavorite.optString("name", ""));

      TextView phoneNumberView = (TextView) convertView.findViewById(R.id.phone);

      phoneNumberView.setText(theFavorite.optString("phone", ""));

      TextView emailAddressView = (TextView) convertView.findViewById(R.id.email);

      emailAddressView.setText(theFavorite.optString("public_email_address", ""));

      // Return the finished list item for display

      return convertView;
    }
  private static String extractMakeAndModelFromJSON(
      JSONObject json, String firstSearchString, String secondSearchString) {
    if (json == null) {
      return null;
    }

    JSONObject formatObject = json.optJSONObject("format");
    if (formatObject != null) {
      JSONObject tagsObject = formatObject.optJSONObject("tags");
      if (tagsObject != null) {
        String firstDesiredValue = tagsObject.optString(firstSearchString);
        if (!firstDesiredValue.equals("")) {
          return firstDesiredValue;
        }
        String secondDesiredValue = tagsObject.optString(secondSearchString);
        if (!secondDesiredValue.equals("")) {
          return secondDesiredValue;
        }
      }
    }

    LOGGER.debug(
        "Could not extract " + firstSearchString + " or " + secondSearchString + " from json.");
    return null;
  }
Example #12
0
 @Override
 public View getView(int position, View view, ViewGroup arg2) {
   ViewHolder viewHolder;
   if (view == null) {
     viewHolder = new ViewHolder();
     view = getLayoutInflater().inflate(R.layout.item_traderesult, null);
     viewHolder.title = (TextView) view.findViewById(R.id.product_title);
     viewHolder.time = (TextView) view.findViewById(R.id.product_time);
     viewHolder.status = (TextView) view.findViewById(R.id.product_status);
     viewHolder.product_status = (TextView) view.findViewById(R.id.product_trade_status);
     viewHolder.money = (TextView) view.findViewById(R.id.product_money);
     view.setTag(viewHolder);
   } else {
     viewHolder = (ViewHolder) view.getTag();
   }
   JSONObject item = getItem(position);
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   viewHolder.time.setText(sdf.format(item.optLong("tradeTime")));
   if (item.optString("tradeStatus").equals("0")) {
     viewHolder.status.setText("交易中");
   } else if (item.optString("tradeStatus").equals("1")) {
     viewHolder.status.setText("成功");
   } else {
     viewHolder.status.setText("失败");
   }
   viewHolder.product_status.setText(item.optString("tradeType"));
   viewHolder.title.setText(item.optString("proName"));
   viewHolder.money.setText(
       Html.fromHtml("<font color=#ff0000>" + item.optString("tradeMoney") + "</font>" + "元"));
   return view;
 }
  public void create_list1(JSONObject response) {
    JSONArray j_array = response.optJSONArray("solvers");
    int l = j_array.length();
    final LinearLayout ll = (LinearLayout) findViewById(R.id.ll_choose_auth);
    LinearLayout.LayoutParams llp =
        new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    for (int i = 0; i < l; i++) {
      final JSONObject j_obj = j_array.optJSONObject(i);

      final Button btnSolver = new Button(Choose_Authority_activity.this);
      btnSolver.setText(j_obj.optString("Department"));
      btnSolver.setBackgroundResource(R.drawable.btn);
      final Toast toast =
          Toast.makeText(
              this, "You have chosen " + j_obj.optString("Department"), Toast.LENGTH_SHORT);
      btnSolver.setOnClickListener(
          new View.OnClickListener() {
            public void onClick(View v) {
              toast.show();
              Intent intent =
                  new Intent(Choose_Authority_activity.this, Complaint_Form_activity.class);
              Login_activity.lodge_var2 = j_obj.optInt("id");
              startActivity(intent);
            }
          });
      ll.addView(btnSolver, llp);
    }
  }
Example #14
0
  static VmValue createFrom(VmIsolate isolate, JSONObject obj) {
    if (obj == null) {
      return null;
    }

    // {"objectId":4,"kind":"object","text":"Instance of '[email protected]'"}

    VmValue value = new VmValue(isolate);

    value.objectId = obj.optInt("objectId");
    value.classId = obj.optInt("classId");
    value.kind = obj.optString("kind");
    value.text = obj.optString("text");
    value.length = obj.optInt("length", 0);

    // for kind == function
    value.name = obj.optString("name");
    value.signature = obj.optString("signature");

    if (value.text == null && value.isFunction()) {
      value.text = value.name + value.signature;
    }

    return value;
  }
  /**
   * Parses BUFFER method parameters for WPS execute xml variables
   *
   * @param lc WFS layer configuration
   * @param json Method parameters and layer info from the front
   * @param baseUrl Url for Geoserver WPS reference input (input FeatureCollection)
   * @return BufferMethodParams parameters for WPS execution
   *     **********************************************************************
   */
  private BufferMethodParams parseBufferParams(
      WFSLayerConfiguration lc, JSONObject json, String baseUrl) throws ServiceException {
    final BufferMethodParams method = new BufferMethodParams();
    method.setMethod(BUFFER);
    //
    try {
      method.setLayer_id(ConversionHelper.getInt(lc.getLayerId(), 0));
      method.setServiceUrl(lc.getURL());
      baseUrl = baseUrl.replace("&", "&amp;");
      method.setHref(baseUrl + String.valueOf(lc.getLayerId()));
      method.setTypeName(lc.getFeatureNamespace() + ":" + lc.getFeatureElement());
      method.setMaxFeatures(String.valueOf(lc.getMaxFeatures()));
      method.setSrsName(lc.getSRSName());
      method.setOutputFormat(DEFAULT_OUTPUT_FORMAT);
      method.setVersion(lc.getWFSVersion());
      method.setXmlns(
          "xmlns:" + lc.getFeatureNamespace() + "=\"" + lc.getFeatureNamespaceURI() + "\"");

      method.setGeom(lc.getGMLGeometryProperty());

      final JSONObject params = json.getJSONObject(JSON_KEY_METHODPARAMS);
      final JSONObject bbox = json.getJSONObject("bbox");
      method.setX_lower(bbox.optString("left"));
      method.setY_lower(bbox.optString("bottom"));
      method.setX_upper(bbox.optString("right"));
      method.setY_upper(bbox.optString("top"));

      method.setDistance(params.optString("distance"));

    } catch (JSONException e) {
      throw new ServiceException("Method parameters missing.");
    }

    return method;
  }
  public static StatusList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
      return null;
    }

    StatusList statuses = new StatusList();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      statuses.hasvisible = jsonObject.optBoolean("hasvisible", false);
      statuses.previous_cursor = jsonObject.optString("previous_cursor", "0");
      statuses.next_cursor = jsonObject.optString("next_cursor", "0");
      statuses.total_number = jsonObject.optInt("total_number", 0);

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

    return statuses;
  }
  /**
   * Parses UNION method parameters for WPS execute xml variables Originally
   * vec:UnionFeatureCollection Changed to geom union (gs:feature + subprocess gs:CollectGeometries
   *
   * @param lc WFS layer configuration
   * @param json Method parameters and layer info from the front
   * @param baseUrl Url for Geoserver WPS reference input (input FeatureCollection)
   * @return UnionMethodParams parameters for WPS execution
   *     **********************************************************************
   */
  private UnionMethodParams parseUnionParams(
      WFSLayerConfiguration lc, JSONObject json, String baseUrl) throws ServiceException {
    UnionMethodParams method = new UnionMethodParams();
    //
    method.setMethod(UNION);
    // General variable input and variable input of union input 1
    method.setLayer_id(ConversionHelper.getInt(lc.getLayerId(), 0));
    method.setServiceUrl(lc.getURL());
    baseUrl = baseUrl.replace("&", "&amp;");
    method.setHref(baseUrl + String.valueOf(lc.getLayerId()));
    method.setTypeName(lc.getFeatureNamespace() + ":" + lc.getFeatureElement());
    method.setLocalTypeName(lc.getFeatureElement());
    method.setMaxFeatures(String.valueOf(lc.getMaxFeatures()));
    method.setSrsName(lc.getSRSName());
    method.setOutputFormat(DEFAULT_OUTPUT_FORMAT);
    method.setVersion(lc.getWFSVersion());
    method.setXmlns(
        "xmlns:" + lc.getFeatureNamespace() + "=\"" + lc.getFeatureNamespaceURI() + "\"");
    method.setGeom(lc.getGMLGeometryProperty());

    JSONObject bbox = null;

    try {
      bbox = json.getJSONObject("bbox");
      method.setX_lower(bbox.optString("left"));
      method.setY_lower(bbox.optString("bottom"));
      method.setX_upper(bbox.optString("right"));
      method.setY_upper(bbox.optString("top"));
    } catch (JSONException e) {
      throw new ServiceException("Bbox parameters missing.");
    }

    return method;
  }
Example #18
0
 public ExhibitionUnit(JSONObject object) {
   title = object.optString("title");
   id = object.optString("Id");
   thumb = object.optString("thumb");
   companyId = object.optString("companyId");
   company = object.optString("companyName");
 }
Example #19
0
  private ArrayList<Workout> convertFoodJsonStringToActivityList(String activityListJson) {
    ArrayList<Workout> activity_list = new ArrayList<Workout>();
    try {
      JSONObject getjobj = new JSONObject(activityListJson);
      JSONArray jArray = getjobj.optJSONArray("actlist");

      // String txt = "";
      // JSONArray jArray = new JSONArray(txt);
      for (int i = 0; i < jArray.length(); i++) {
        JSONObject json_data = jArray.getJSONObject(i);

        // output val
        // ( name , cal, restaurant, fat, cholesterol, sodium, carbohydrate , protein, type)
        // (String name, String restuarant, String type, int calories, int carbohydrate, int
        // protein, int fat, int cholesterol, int sodium)

        Float val = Float.parseFloat(json_data.optString("val"));
        String name = json_data.optString("name");

        Workout outputact = new Workout(name, val);

        activity_list.add(outputact);
      }
    } catch (JSONException e) {

      Log.e("log_tag", "Errrrrrorr");
    }

    return activity_list;
  }
Example #20
0
 @Override
 public void parseJson(String json) throws JSONException {
   JSONObject jsonObject = new JSONObject(json);
   id = jsonObject.optString("id");
   url = jsonObject.optString("url");
   image = jsonObject.optString("image");
 }
 public Type[] getTypeOptions(String groupName) {
   try {
     JSONObject obj = data.optJSONObject(groupName);
     if (obj != null && "action".equals(obj.optString("type"))) {
       String defaultValue = obj.optString("default", "");
       JSONArray arr = obj.getJSONArray("values");
       Type[] options = new Type[arr.length()];
       for (int i = 0; i < options.length; i++) {
         JSONObject option = arr.getJSONObject(i);
         options[i] = new Type();
         String id = option.getString("id");
         String name = option.getString("name");
         String action = option.getString("action");
         options[i].setId(id);
         options[i].setName(name);
         options[i].setAction(action);
         options[i].setDefault(id.equals(defaultValue));
       }
       return options;
     }
   } catch (JSONException e) {
     // ignore
   }
   return new Type[0];
 }
Example #22
0
  private static void populateEventFromJSON(AccessibilityEvent event, JSONObject message) {
    final JSONArray textArray = message.optJSONArray("text");
    if (textArray != null) {
      for (int i = 0; i < textArray.length(); i++) event.getText().add(textArray.optString(i));
    }

    event.setContentDescription(message.optString("description"));
    event.setEnabled(message.optBoolean("enabled", true));
    event.setChecked(message.optBoolean("checked"));
    event.setPassword(message.optBoolean("password"));
    event.setAddedCount(message.optInt("addedCount", -1));
    event.setRemovedCount(message.optInt("removedCount", -1));
    event.setFromIndex(message.optInt("fromIndex", -1));
    event.setItemCount(message.optInt("itemCount", -1));
    event.setCurrentItemIndex(message.optInt("currentItemIndex", -1));
    event.setBeforeText(message.optString("beforeText"));
    if (Versions.feature14Plus) {
      event.setToIndex(message.optInt("toIndex", -1));
      event.setScrollable(message.optBoolean("scrollable"));
      event.setScrollX(message.optInt("scrollX", -1));
      event.setScrollY(message.optInt("scrollY", -1));
    }
    if (Versions.feature15Plus) {
      event.setMaxScrollX(message.optInt("maxScrollX", -1));
      event.setMaxScrollY(message.optInt("maxScrollY", -1));
    }
  }
Example #23
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;
  }
 /**
  * 同步方法,使用用户名和密码登陆
  *
  * @param param 请求的参数
  * @return 返回{@link PasswordFlowResponseBean}对象
  * @throws RenrenException
  * @throws Throwable
  */
 public PasswordFlowResponseBean login(PasswordFlowRequestParam param)
     throws RenrenException, Throwable {
   String url = PASSWORD_FLOW_URL;
   String method = "POST";
   Bundle bundle = param.getParams();
   try {
     String response = Util.openUrl(url, method, bundle);
     if (response != null) {
       JSONObject obj = new JSONObject(response);
       if (obj != null) {
         if (!TextUtils.isEmpty(obj.optString("error"))) {
           String message = obj.optString("error_description");
           throw new RenrenException(RenrenError.ERROR_CODE_AUTH_FAILED, message, message);
         }
       }
       PasswordFlowResponseBean passwordFlow = new PasswordFlowResponseBean(response);
       return passwordFlow;
     } else {
       Util.logger("null response");
       throw new RenrenException(
           RenrenError.ERROR_CODE_UNKNOWN_ERROR, "null response", "null response");
     }
   } catch (RuntimeException e) {
     Util.logger("runtime exception" + e.getMessage());
     throw new Throwable(e);
   }
 }
Example #25
0
 private void bingSong(ViewHolder holder, LabelStory story) {
   if (LabelStory.TYPE_ONLINEAUDIO.equals(story.getType())) {
     if (story.getThumbImages() != null) {
       AvatarManager.getInstance(context)
           .displaySingerAvatar(
               story.getThumbImages()[0], holder.mAnimView, R.drawable.ic_sound_pic_normal);
     }
     JSONObject jsonObject = VoiceUtiles.getContentJson(story.getContent());
     if (jsonObject != null) {
       holder.songName.setText(
           jsonObject.optString(CommandFields.Dynamic.SONG_NAME) == null
               ? context.getString(R.string.song_name, context.getString(R.string.music_unknown))
               : context.getString(
                   R.string.song_name, jsonObject.optString(CommandFields.Dynamic.SONG_NAME)));
       holder.singName.setText(
           jsonObject.optString(CommandFields.Dynamic.SINGER_NAME) == null
               ? context.getString(
                   R.string.singer_name, context.getString(R.string.music_unknown))
               : context.getString(
                   R.string.singer_name,
                   jsonObject.optString(CommandFields.Dynamic.SINGER_NAME)));
       holder.titleText.setText(jsonObject.optString(CommandFields.Dynamic.DYNAMIC_CONTENT));
     }
   } else {
     holder.titleText.setText(story.getContent());
     holder.mAnimView.setImageResource(R.drawable.ic_sound_play);
     holder.songName.setText(
         context.getString(R.string.song_name, context.getString(R.string.music_unknown)));
     holder.singName.setText(
         context.getString(R.string.singer_name, context.getString(R.string.music_unknown)));
   }
 }
Example #26
0
 public PromptInput(JSONObject obj) {
   mLabel = obj.optString("label");
   mType = obj.optString("type");
   String id = obj.optString("id");
   mId = TextUtils.isEmpty(id) ? mType : id;
   mValue = obj.optString("value");
 }
  /**
   * Create a notification as the visible part to be able to put the service in a foreground state.
   *
   * @return A local ongoing notification which pending intent is bound to the main activity.
   */
  @SuppressLint("NewApi")
  @SuppressWarnings("deprecation")
  private Notification makeNotification() {
    JSONObject settings = BackgroundMode.getSettings();
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);

    Notification.Builder notification =
        new Notification.Builder(context)
            .setContentTitle(settings.optString("title", "Title"))
            .setContentText(settings.optString("text", "Content"))
            .setTicker(settings.optString("ticker", "Ticker"))
            .setOngoing(true)
            .setSmallIcon(getIconResId());

    if (intent != null && settings.optBoolean("resume")) {

      PendingIntent contentIntent =
          PendingIntent.getActivity(
              context, NOTIFICATION_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

      notification.setContentIntent(contentIntent);
    }

    if (Build.VERSION.SDK_INT < 16) {
      // Build notification for HoneyComb to ICS
      return notification.getNotification();
    } else {
      // Notification for Jellybean and above
      return notification.build();
    }
  }
  @Override
  public void onLoginFinish(int type, String values) {
    String userPhoto = null;

    switch (type) {
      case ScoreLoginHelper.LOGIN_TYPE_QQ:
        JSONObject object = null;
        try {
          object = new JSONObject(values);
          mNickName = object.optString("nickname");
          Config.setNickName(mContext, mNickName);
          userPhoto = object.optString("figureurl_qq_2");
        } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        break;
      case ScoreLoginHelper.LOGIN_TYPE_SINA:
        User user = User.parse(values);
        mNickName = user.name;
        Config.setNickName(mContext, mNickName);
        userPhoto = user.avatar_large;
        break;
    }
    if (userPhoto != null) {
      DownloadPicTask task =
          new DownloadPicTask(
              ITask.TYPE_DOWNLOAD_PIC, ThreadManager.getInstance().getNewTaskId(), userPhoto);
      task.setListener(ProfileFragmentActivity.this);
      ThreadManager.getInstance().addTask(task);
    }
  }
Example #29
0
  private void decryptCredentials(DatabaseEntry entry, JSONObject jDatabase) {
    String databaseUsername, databasePassword = null;
    // if no encryption key or both username and password are empty, skip encryption
    if (!SettingsManager.getSyncSetting(SettingsManager.SyncKey.sync_credentials)
        || TextUtils.isEmpty(SettingsManager.getEc())
        || (TextUtils.isEmpty(databaseUsername = jDatabase.optString("database_username"))
            && TextUtils.isEmpty(databasePassword = jDatabase.optString("database_password"))))
      return;
    try {
      AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.keys(SettingsManager.getEc());

      if (!TextUtils.isEmpty(databaseUsername)) {
        AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac =
            new AesCbcWithIntegrity.CipherTextIvMac(databaseUsername);
        entry.databaseUsername = AesCbcWithIntegrity.decryptString(cipherTextIvMac, keys);
      }
      if (!TextUtils.isEmpty(databasePassword)) {
        AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac =
            new AesCbcWithIntegrity.CipherTextIvMac(databasePassword);
        entry.databasePassword = AesCbcWithIntegrity.decryptString(cipherTextIvMac, keys);
      }
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
      if (SettingsManager.DEBUG()) e.printStackTrace();
      // fail silently on any kind of error
      // user will see warning on database entry when restored without username/password
    }
  }
Example #30
0
 public SplashObj getSplashObj() {
   try {
     String json =
         HttpUtils.getHttpContentWithCache(
             BiliUtils.getSplashApi(), "splash", "splash.json", true);
     if (json == null) return null;
     JSONObject jsobj = new JSONObject(json);
     if (jsobj.optString("message").equals("success")) {
       JSONArray array = jsobj.getJSONArray("result");
       JSONObject temp = array.getJSONObject(0);
       SplashObj obj = new SplashObj();
       obj.setAnimation(temp.optString("animation"));
       obj.setDuration(temp.optString("duration"));
       obj.setEnd(temp.optLong("end"));
       obj.setHeight(temp.optInt("height"));
       obj.setImage(temp.optString("image"));
       obj.setStart(temp.optLong("start"));
       obj.setWidth(temp.optInt("width"));
       obj.setVer(temp.optInt("ver"));
       return obj;
     }
   } catch (JSONException e) {
   }
   return null;
 }