@Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    if (convertView == null) {
      LayoutInflater inflator = context.getLayoutInflater();
      view = inflator.inflate(R.layout.filter_color_listview_row, parent, false);
      final ViewHolder viewHolder = new ViewHolder();
      viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_color);
      viewHolder.text = (TextView) view.findViewById(R.id.label_color);
      viewHolder.textcolor = (TextView) view.findViewById(R.id.color_display_txt);
      viewHolder.checkbox.setOnCheckedChangeListener(
          new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              Model element = (Model) viewHolder.checkbox.getTag();
              element.setSelected(buttonView.isChecked());
            }
          });
      view.setOnClickListener(
          new OnClickListener() {

            @Override
            public void onClick(View arg0) {
              // TODO Auto-generated method stub
              viewHolder.checkbox.setChecked(!viewHolder.checkbox.isChecked());
            }
          });
      view.setTag(viewHolder);
      viewHolder.checkbox.setTag(list.get(position));
    } else {
      view = convertView;
      ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
    }
    ViewHolder holder = (ViewHolder) view.getTag();

    holder.text.setTextSize(5 * context.getResources().getDisplayMetrics().density);
    holder.checkbox.setChecked(list.get(position).isSelected());
    JSONArray object;
    try {
      object = new JSONArray(list.get(position).getName());
      final float scale = context.getResources().getDisplayMetrics().density;
      GradientDrawable gd = new GradientDrawable();
      gd.setColor(
          Color.parseColor(
              object.getString(
                  1))); // Changes this drawbale to use a single color instead of a gradient
      gd.setCornerRadius((int) (2 * scale + 0.5f));
      gd.setStroke((int) (2 * scale + 0.5f), Color.parseColor("#000000"));
      holder.textcolor.setBackgroundDrawable(gd);

      holder.text.setText(object.getString(0));
      // holder.textcolor.setBackgroundColor(Color.parseColor(object.getString(1)));
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return view;
  }
  private void doJson() {
    try {
      Log.i("json", detail);
      JSONArray arr = new JSONArray(detail);
      JSONArray main = arr.getJSONArray(0);

      tvSender.setText(main.getString(4));
      tvSendTime.setText(HttpConstant.convertTime(main.getLong(7)));
      tvMsg.setText(main.getString(1));
      tvLoc.setText(main.getString(6));
      alert_id = main.getInt(2);
      Picasso.with(this).load(HttpConstant.BAIDUFACE + main.getString(5)).into(ivFace);

      for (int i = 1; i < arr.length(); i++) {
        LostBean lb = new LostBean();
        JSONArray lost = arr.getJSONArray(i);
        lb.title = lost.optString(0);
        lb.description = lost.optString(1);
        lb.alert_id = lost.optString(2);
        lb.from_user_id = lost.optString(3);
        lb.uname = lost.optString(4);
        lb.uface = lost.optString(5);
        lb.position = lost.optString(6);
        lb.time = lost.optLong(7);
        lostList.add(lb);
      }
      adapter.notifyDataSetChanged();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
 public boolean isTagsPresent(String data, JSONObject tags) {
   if (tags == null) return true;
   else {
     int index;
     JSONArray names = tags.names();
     try {
       JSONObject jsonData = new JSONObject(data);
       JSONObject dataTags = new JSONObject(jsonData.getString("tags"));
       for (index = 0; index < names.length(); index++) {
         String name = names.getString(index);
         JSONArray dataTagArray = dataTags.getJSONArray(name);
         JSONArray tagArray = tags.getJSONArray(name);
         boolean isFound = false;
         for (int iteri = 0; iteri < tagArray.length(); iteri++) {
           for (int iterj = 0; iterj < dataTagArray.length(); iterj++) {
             if (tagArray.getString(iteri).contentEquals(dataTagArray.getString(iterj)))
               isFound = true;
           }
         }
         if (dataTagArray.length() * tagArray.length() == 0) isFound = true;
         if (!isFound) return false;
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
   return true;
 }
  public void sendSingleTextMessage(JSONArray data, CallbackContext callbackContext) {
    Log.i(TAG, " sendSingleTextMessage \n" + data);

    final CallbackContext cb = callbackContext;
    try {
      String username = data.getString(0);
      String text = data.getString(1);

      Conversation conversation = JMessageClient.getSingleConversation(username);
      if (conversation == null) {
        conversation = Conversation.createSingleConversation(username);
      }
      if (conversation == null) {
        callbackContext.error("无法创建对话");
        return;
      }
      TextContent content = new TextContent(text);
      final Message msg = conversation.createSendMessage(content);

      JMessageClient.sendMessage(msg);
      callbackContext.success("正在发送");

    } catch (JSONException e) {
      e.printStackTrace();
      callbackContext.error("error reading id json");
    }
  }
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
      throws JSONException {
    this.callbackContext = callbackContext;
    this.limit = 1;
    this.duration = 0;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
      limit = options.optLong("limit", 1);
      duration = options.optInt("duration", 0);
    }

    if (action.equals("getFormatData")) {
      JSONObject obj = getFormatData(args.getString(0), args.getString(1));
      callbackContext.success(obj);
      return true;
    } else if (action.equals("captureAudio")) {
      this.captureAudio();
    } else if (action.equals("captureImage")) {
      this.captureImage();
    } else if (action.equals("captureVideo")) {
      this.captureVideo(duration);
    } else {
      return false;
    }

    return true;
  }
Example #6
0
 private UserData processLookup(JSONObject json) {
   final UserData data = new UserData();
   try {
     final JSONArray local = json.optJSONArray("local");
     if (local == null) {
       SuperBans.log("Unable to properly communicate with MCBans. Check your API Key");
       return data;
     }
     for (int i = 0; i < local.length(); i++) {
       final String[] ban = processBanLookup(local.getString(i));
       data.getBanList()
           .addBanData(new MCBansBanData(ban[1], MCBansBanData.BanType.LOCAL, ban[0]));
     }
     final JSONArray global = json.optJSONArray("global");
     for (int i = 0; i < global.length(); i++) {
       final String[] ban = processBanLookup(global.getString(i));
       data.getBanList()
           .addBanData(new MCBansBanData(ban[1], MCBansBanData.BanType.GLOBAL, ban[0]));
     }
   } catch (final JSONException e) {
     e.printStackTrace();
   }
   data.setExtra("mcbans_rep", String.valueOf(json.optDouble("reputation", 10.0)));
   return data;
 }
  @Override
  public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
      throws JSONException {

    if (action.equals(ACTION_HAS_SMS_POSSIBILITY)) {

      Activity ctx = this.cordova.getActivity();
      if (ctx.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true));
      } else {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, false));
      }
      return true;
    } else if (action.equals(ACTION_SEND_SMS)) {
      try {
        String phoneNumber = args.getString(0);
        String message = args.getString(1);
        this.sendSMS(phoneNumber, message);

        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
      } catch (JSONException ex) {
        callbackContext.sendPluginResult(
            new PluginResult(PluginResult.Status.ERROR, ex.getMessage()));
      }
      return true;
    }
    return false;
  }
  private PADCapturedFriendModel parseFriend(final JSONArray friendResult) throws JSONException {
    MyLog.entry();

    // [4, 333300602, "NeraudMule", 17, 1, "140829151957", 9, 29, 6, 1, 0, 0, 0, 0, 2, 15, 1, 0, 0,
    // 0, 0, 2, 15, 1, 0, 0, 0, 0]
    // New [5, 329993422, "HFR|Neraud", 292, 1, "150613152858", 48, 50, 6, 1, 0, 0, 0, 0, 0, 1422,
    // 99, 1, 13, 12, 9, 6, 0, 1217, 99, 6, 99, 99, 99, 6, 0]
    final PADCapturedFriendModel friend = new PADCapturedFriendModel();
    // index 0 could be the version number for the friend struct
    // version 7 added skill inheritance?
    friend.setId(friendResult.getLong(1));
    friend.setName(friendResult.getString(2));
    friend.setRank(friendResult.getInt(3));
    friend.setStartingColor(StartingColor.valueByCode(friendResult.getInt(4)));
    final String lastActivityDateString = friendResult.getString(5);
    try {
      final DateFormat parseFormat = new SimpleDateFormat("yyMMddHHmmss");
      parseFormat.setTimeZone(region.getTimeZone());
      final Date lastActivityDate = parseFormat.parse(lastActivityDateString);
      friend.setLastActivityDate(lastActivityDate);
    } catch (ParseException e) {
      MyLog.warn("error parsing lastActivityDate : " + e.getMessage());
    }

    final BaseMonsterStatsModel leader1 = extractFriendLeader(friendResult, 16);
    friend.setLeader1(leader1);

    final BaseMonsterStatsModel leader2 = extractFriendLeader(friendResult, 26);
    friend.setLeader2(leader2);

    MyLog.exit();
    return friend;
  }
  private GenomicRegionSearchInfo parseRegionRequest() throws Exception {
    String input = "";
    if ("application/x-www-form-urlencoded".equals(request.getContentType())
        || "GET".equalsIgnoreCase(request.getMethod())) {
      input = request.getParameter("query");
    } else {
      input = IOUtils.toString(request.getInputStream());
    }
    JSONObject jsonRequest = new JSONObject(input);
    GenomicRegionSearchInfo parsed = new GenomicRegionSearchInfo();
    parsed.setOrganism(jsonRequest.getString("organism"));
    if (!jsonRequest.isNull("isInterbase")) {
      parsed.setInterbase(jsonRequest.getBoolean("isInterbase"));
    }
    if (!jsonRequest.isNull("extension")) {
      parsed.setExtension(jsonRequest.optInt("extension", 0));
    }
    JSONArray fts = jsonRequest.getJSONArray("featureTypes");
    int noOfTypes = fts.length();
    List<String> featureTypes = new ArrayList<String>();
    for (int i = 0; i < noOfTypes; i++) {
      featureTypes.add(fts.getString(i));
    }
    parsed.setFeatureTypes(featureTypes);

    JSONArray regs = jsonRequest.getJSONArray("regions");
    int noOfRegs = regs.length();
    List<String> regions = new ArrayList<String>();
    for (int i = 0; i < noOfRegs; i++) {
      regions.add(regs.getString(i));
    }
    parsed.setRegions(regions);
    return parsed;
  }
  public static void fillSpinner() {
    try {
      json_klassen = new JSONArray(strklasse);
      int arraylengh = (json_klassen.length() - 1);
      klasse = new String[arraylengh][3];
      int k = 0;
      for (int j = 1; j < json_klassen.length(); j++) {
        JSONArray temp;
        temp = json_klassen.getJSONArray(j);

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

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

        k++;
      }

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

    } catch (JSONException e) {
      e.printStackTrace();
    }
    adapterspinner.notifyDataSetChanged();
    spinner_klasse.setSelection(favorit);
  }
 /**
  * 从jsonarray中获取产品列表信息
  *
  * @param jsonArray
  * @throws Exception
  */
 private void getProductList(JSONArray jsonArray) throws Exception {
   for (int i = 0; i < jsonArray.length(); i++) {
     Products products = new Products();
     JSONObject o = (JSONObject) jsonArray.get(i);
     JSONArray cidArrayJson = o.getJSONArray("cids");
     JSONArray cidArrayProImg = o.getJSONArray("proImages");
     JSONArray playableArray = o.getJSONArray("playables");
     products.count = o.getInt("count");
     products.findTime = o.getString("findtime");
     products.showTime = o.getString("showtime");
     for (int k = 0; k < cidArrayJson.length(); k++) {
       String cid = cidArrayJson.getString(k);
       LogPrint.Print("lybjson", "cid =" + cid); //
       products.arrcid.add(cid);
     }
     for (int k = 0; k < cidArrayProImg.length(); k++) {
       String proImg = cidArrayProImg.getString(k);
       LogPrint.Print("lybjson", "proImg = " + proImg); //
       products.arrProImg.add(proImg);
     }
     for (int k = 0; k < playableArray.length(); k++) {
       int playable = playableArray.getInt(k);
       products.arrPlayable.add(playable);
     }
     LogPrint.Print("lyb", "arrCommodity size = " + products.arrProImg.size());
     productItem.arrProducts.add(products);
   }
 }
Example #12
0
  // 查詢資料
  // 可以看看回傳結果集及取得資料方式
  private JSONObject SelectTable(JSONObject jsonObject) throws Exception {
    try {
      String selectSQL = jsonObject.getString("sqlCommand");
      JSONArray keys = jsonObject.getJSONArray("keys");

      JSONArray jsonArray = new JSONArray();
      JSONObject result = new JSONObject();
      stat = con.createStatement();
      rs = stat.executeQuery(selectSQL);
      while (rs.next()) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        for (int i = 0; i < keys.length(); i++) {
          hashMap.put(keys.getString(i), rs.getString(keys.getString(i)));
        }
        jsonArray.put(hashMap);
      }
      try {
        result.put("RESULT", jsonArray);
        return result;
      } catch (Exception e) {
        return null;
      }
    } catch (SQLException e) {
      System.out.println("DropDB Exception :" + e.toString());
      return null;
    } finally {
      Close();
    }
  }
Example #13
0
  private void saveToDatabase(JSONArray address) {
    String cityName = null;
    String country = null;
    JSONArray types;
    try {
      for (int j = 0; j < address.length(); j++) {
        types = address.getJSONObject(j).getJSONArray("types");
        if (types.length() > 0) {
          if (types.getString(0).equals("locality")) {
            cityName = address.getJSONObject(j).getString("long_name");
          }
          if (types.getString(0).equals("country")) {
            country = address.getJSONObject(j).getString("long_name");
          }
        }
      }

      if (!cityName.isEmpty()) {
        ContentValues values = new ContentValues();
        values.put(Weather.Columns.CITY_NAME, cityName);
        values.put(Weather.Columns.COUNTRY_NAME, country);
        values.put(Weather.Columns.IS_LOCATION, 1);
        values.put(Weather.Columns.LATITUDE, latitude);
        values.put(Weather.Columns.LONGITUDE, longitude);

        Uri uri = Uri.withAppendedPath(Weather.CONTENT_URI, "islocation/1");
        mContext.getContentResolver().update(uri, values, null, null);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
  @Override
  public PluginResult execute(String action, JSONArray args, String callbackId) {
    // Log.d("MindSetPlugin", "Plugin Called");
    PluginResult result = null;
    PluginResult.Status status = PluginResult.Status.OK;

    try {
      if (START_ACTION.equals(action)) {
        // Log.d("MindSetPlugin", "Start passed");
        String o =
            start(
                args.getString(0),
                args.getBoolean(1),
                args.getInt(2),
                args.getInt(3),
                args.getString(4));
        result = new PluginResult(status, o);

      } else if (STOP_ACTION.equals(action)) {
        // Log.d("MindSetPlugin", "Stop passed");
        stop(args.getString(0));
        result = new PluginResult(status, "");

      } else {
        result = new PluginResult(Status.INVALID_ACTION);
        // Log
        //		.d("MindSetPlugin", "Invalid action : " + action
        //				+ " passed");
      }
    } catch (JSONException ex) {
    }
    return result;
  }
  @Override
  public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
      throws JSONException {
    if (action.equals("upload") || action.equals("download")) {
      String source = args.getString(0);
      String target = args.getString(1);

      if (action.equals("upload")) {
        try {
          source = URLDecoder.decode(source, "UTF-8");
          upload(source, target, args, callbackContext);
        } catch (UnsupportedEncodingException e) {
          callbackContext.sendPluginResult(
              new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "UTF-8 error."));
        }
      } else {
        download(source, target, args, callbackContext);
      }
      return true;
    } else if (action.equals("abort")) {
      String objectId = args.getString(0);
      abort(objectId);
      callbackContext.success();
      return true;
    }
    return false;
  }
Example #16
0
 private Session parseJson(final String json) {
   Session session = null;
   try {
     JSONObject jsonObject = new JSONObject(json);
     session = new Session();
     session.setIp(jsonObject.optString("ip"));
     session.setDomain(jsonObject.optString("domain"));
     session.setPath(jsonObject.optString("path"));
     session.setUserAgent(jsonObject.optString("userAgent"));
     session.setDateTime(parseDateFormat.parse(jsonObject.optString("dateTime")));
     Map<String, BasicClientCookie> cookies = new HashMap<String, BasicClientCookie>();
     JSONObject cookiesObject = jsonObject.optJSONObject("cookies");
     JSONArray cookieArray = cookiesObject.names();
     if (cookieArray != null) {
       for (int i = 0; i < cookieArray.length(); i++) {
         JSONObject cookieObject = cookiesObject.getJSONObject(cookieArray.getString(i));
         BasicClientCookie cookie =
             new BasicClientCookie(
                 cookieObject.optString("name"), cookieObject.optString("value"));
         cookie.setDomain(cookieObject.optString("domain"));
         cookies.put(cookieArray.getString(i), cookie);
       }
     }
     session.setCookies(cookies);
   } catch (JSONException e) {
     e.printStackTrace();
   } catch (ParseException e) {
     e.printStackTrace();
   }
   return session;
 }
  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;
  }
  @Override
  public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
      throws JSONException {
    if (action.equals("upload") || action.equals("download")) {
      String source = args.getString(0);
      String target = args.getString(1);

      if (action.equals("upload")) {
        upload(source, target, args, callbackContext);
      } else {
        download(source, target, args, callbackContext);
      }
      return true;
    } else if (action.equals("abort")) {
      String objectId = args.getString(0);
      abort(objectId);
      callbackContext.success();
      return true;
    } else if (action.equals("pause")) {
      String objectId = args.getString(0);
      pause(objectId);
      callbackContext.success();
      return true;
    }
    return false;
  }
 /**
  * Parses the JSON and returns a list of Youtube video descriptions
  *
  * @return
  * @throws IOException
  * @throws JSONException
  */
 public List<YoutubeDescription> parseJson() {
   StringBuffer jsonString = new StringBuffer();
   List<YoutubeDescription> youtubeDescriptions = new ArrayList<>();
   try {
     BufferedReader readFile = new BufferedReader(new FileReader(new File(inputFilePath)));
     String line = null;
     while ((line = readFile.readLine()) != null) jsonString.append(line);
     JSONArray youtubeDescriptionsArray = new JSONArray(jsonString.toString());
     for (int i = 0; i < youtubeDescriptionsArray.length(); i++) {
       YoutubeDescription video = new YoutubeDescription();
       JSONObject youtubeDescriptionJson = youtubeDescriptionsArray.getJSONObject(i);
       video.setId(i + 1);
       video.setDescription(youtubeDescriptionJson.getString("description"));
       video.setTitle(youtubeDescriptionJson.getString("title"));
       JSONArray categoriesJson = youtubeDescriptionJson.getJSONArray("categories");
       for (int j = 0; j < categoriesJson.length(); j++)
         video.setIndividualCategory(categoriesJson.getString(j));
       // If the output already contains tagged json
       if (tagged) {
         JSONArray tagsJson = youtubeDescriptionJson.getJSONArray("tags");
         for (int j = 0; j < tagsJson.length(); j++) video.setIndividualTag(tagsJson.getString(j));
       }
       youtubeDescriptions.add(video);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return youtubeDescriptions;
 }
Example #20
0
  @Override
  public PluginResult execute(String action, JSONArray args, String callbackId) {
    this.callbackId = callbackId;
    this.limit = 1;
    this.duration = 0.0f;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
      limit = options.optLong("limit", 1);
      duration = options.optDouble("duration", 0.0f);
    }

    if (action.equals("getFormatData")) {
      try {
        JSONObject obj = getFormatData(args.getString(0), args.getString(1));
        return new PluginResult(PluginResult.Status.OK, obj);
      } catch (JSONException e) {
        return new PluginResult(PluginResult.Status.ERROR);
      }
    } else if (action.equals("captureAudio")) {
      this.captureAudio();
    } else if (action.equals("captureImage")) {
      this.captureImage();
    } else if (action.equals("captureVideo")) {
      this.captureVideo(duration);
    }

    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    return r;
  }
Example #21
0
  // Grabs assets off the intarwebz and saves them to a local store/jail for hydration.
  private void fetch(JSONArray args) {
    String url;
    String username;
    String password;
    String id;
    try {
      id = args.getString(0);
      url = args.getString(1);
      username = args.getString(2);
      password = args.getString(3);

      // Create directory for app.
      local_path = "/data/data/" + ctx.getPackageName() + "/remote_app/" + id + "/";
      File fp = new File(local_path);
      fp.mkdirs();

      if (fetchApp(url, username, password)) {
        this.success(
            new PluginResult(PluginResult.Status.OK, "file://" + local_path + "index.html"),
            this.callback);
      } else {
        this.error(
            new PluginResult(
                PluginResult.Status.ERROR,
                "Error during app saving or fetching; protocol or IO error likely."),
            this.callback);
      }
    } catch (JSONException e) {
      this.error(
          new PluginResult(
              PluginResult.Status.JSON_EXCEPTION,
              "JSON exception during argument parsing; make sure the app ID, URL, username and password were passed as an argument."),
          this.callback);
    }
  }
  @Override
  protected void onExtractData(JSONObject jsonData) throws Exception {
    JSONArray jsonArray = jsonData.getJSONArray("Data");
    Log.i(LOG_TAG + "onExtractData", "get cargoTypeList count is " + jsonArray.length());

    // 新建货物列表
    cargoTypeList = new ArrayList<>();

    for (int i = 0; i < jsonArray.length(); i++) {

      JSONArray jsonRow = jsonArray.getJSONArray(i);

      if (jsonRow.length() > 2) {
        // 一条货物数据
        CargoType cargoType = new CargoType();
        cargoType.setId(jsonRow.getString(0));
        cargoType.setName(jsonRow.getString(1));
        cargoType.setShortCode(jsonRow.getString(2));

        // 加入列表
        cargoTypeList.add(cargoType);
      }
    }

    Log.i(LOG_TAG + "onExtractData", "cargo type list count is " + cargoTypeList.size());
  }
 @Override
 public boolean execute(String action, JSONArray data, CallbackContext callbackContext)
     throws JSONException {
   if (action.equals("storeMeasurement")) {
     Context ctxt = cordova.getActivity();
     (new ClientStatsHelper(ctxt))
         .storeMeasurement(
             data.getString(0), // key
             data.getString(1), // value
             data.getString(2)); // ts
     callbackContext.success();
     return true;
   } else if (action.equals("storeEventNow")) {
     Context ctxt = cordova.getActivity();
     new ClientStatsHelper(ctxt)
         .storeMeasurement(
             data.getString(0), // key
             null, // value
             String.valueOf(System.currentTimeMillis())); // ts
     callbackContext.success();
     return true;
   } else {
     return false;
   }
 }
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
      throws JSONException {
    if (action.equals(ACTION_INITIALIZE)) {
      this.initialize(callbackContext, args);
      return true;
    }
    if (action.equals(ACTION_GET_INSTALLATION_ID)) {
      this.getInstallationId(callbackContext);
      return true;
    }

    if (action.equals(ACTION_GET_INSTALLATION_OBJECT_ID)) {
      this.getInstallationObjectId(callbackContext);
      return true;
    }
    if (action.equals(ACTION_GET_SUBSCRIPTIONS)) {
      this.getSubscriptions(callbackContext);
      return true;
    }
    if (action.equals(ACTION_SUBSCRIBE)) {
      this.subscribe(args.getString(0), callbackContext);
      return true;
    }
    if (action.equals(ACTION_UNSUBSCRIBE)) {
      this.unsubscribe(args.getString(0), callbackContext);
      return true;
    }
    return false;
  }
 @Override
 public void call(JSONArray args) throws JSONException {
   if (argsLengthValid(3, args)) {
     Crashlytics.log(args.getInt(0), args.getString(1), args.getString(2));
   } else {
     Crashlytics.log(args.getString(0));
   }
 }
Example #26
0
 public void testJSONIncludesScopesWhenScoped() throws Exception {
   JSONObject actual = new ProvisioningRole(SuiteRole.STUDY_SUBJECT_CALENDAR_MANAGER).toJSON();
   JSONArray scopes = actual.optJSONArray("scopes");
   assertNotNull(scopes);
   assertEquals("Wrong number of scopes", 2, scopes.length());
   assertEquals("Wrong scope", "site", scopes.getString(0));
   assertEquals("Wrong scope", "study", scopes.getString(1));
 }
  /** {@inheritDoc} */
  @Override
  public ServiceConfiguration fromJSON(JSONObject json) throws JSONException {
    ServiceConfiguration serviceConfiguration = new ServiceConfiguration();

    JsonObjectWrapper wrapper = JsonObjectWrapper.newInstance(json);

    serviceConfiguration.setEnsureRunning(wrapper.optBooleanNull(ENSURE_RUNNING));
    serviceConfiguration.setEnabled(wrapper.optBooleanNull(ENABLED));

    if (wrapper.has(FILES)) {
      JSONArray files = wrapper.getArray(FILES);
      for (int i = 0; i < files.length(); i++) {
        serviceConfiguration.getFiles().add(files.getString(i));
      }
    }

    if (wrapper.has(SOURCES)) {
      JSONArray sources = wrapper.getArray(SOURCES);
      for (int i = 0; i < sources.length(); i++) {
        serviceConfiguration.getSources().add(sources.getString(i));
      }
    }

    if (wrapper.has(COMMANDS)) {
      JSONArray commands = wrapper.getArray(COMMANDS);
      for (int i = 0; i < commands.length(); i++) {
        serviceConfiguration.getCommands().add(commands.getString(i));
      }
    }

    if (wrapper.has(PACKAGES)) {
      JsonObjectWrapper jsonPackagesWrapper = wrapper.getWrapper(PACKAGES);

      @SuppressWarnings("unchecked")
      Iterator<String> keysIterator = (Iterator<String>) jsonPackagesWrapper.toJsonObject().keys();
      while (keysIterator.hasNext()) {
        String packageManagerName = keysIterator.next();
        PackageDependenciesParser parser = new PackageDependenciesParser();
        PackageManagerName packageManagerKey = PackageManagerName.fromString(packageManagerName);

        if (packageManagerKey != null) {
          serviceConfiguration
              .getPackages()
              .put(
                  packageManagerKey,
                  parser.fromJSON(jsonPackagesWrapper.getArray(packageManagerKey)));
        } else {
          LOG.error(
              "Unknown package manager specified under config section: " + packageManagerName);
          throw new JSONException(
              "Unknown package manager specified under config section: " + packageManagerName);
        }
      }
    }

    return serviceConfiguration;
  }
  private void JsonResondResult(String con) {
    // TODO Auto-generated method stub
    try {
      resonpList = new ArrayList<Map<String, String>>();

      JSONObject all = new JSONObject(con);
      Log.d(TAG + "JsonResult", con);
      Boolean result = all.optBoolean("result");
      String resultMSG = all.optString("resultMSG");
      if (mToastLoding != null && mToastLoding.isShowing()) {
        mToastLoding.cancel();
      }
      if (result) {
        JSONObject data = all.optJSONObject("data");
        if (null != data) {
          JSONArray acceptPhoneNums = data.optJSONArray("acceptPhoneNums");
          if (null != acceptPhoneNums) {
            for (int i = 0; i < acceptPhoneNums.length(); i++) {
              Map<String, String> map = new HashMap<String, String>();
              map.put("accept", acceptPhoneNums.getString(i));
              map.put("type", "1");
              resonpList.add(map);
            }
          }
          JSONArray refusePhoneNums = data.optJSONArray("refusePhoneNums");
          if (null != refusePhoneNums) {
            for (int i = 0; i < refusePhoneNums.length(); i++) {
              Map<String, String> map1 = new HashMap<String, String>();
              map1.put("refuse", refusePhoneNums.getString(i));
              map1.put("type", "2");
              resonpList.add(map1);
            }
          }
          JSONArray notRespondPhoneNums = data.optJSONArray("notRespondPhoneNums");
          if (null != notRespondPhoneNums) {
            for (int i = 0; i < notRespondPhoneNums.length(); i++) {
              Map<String, String> map2 = new HashMap<String, String>();
              map2.put("notRespond", notRespondPhoneNums.getString(i));
              map2.put("type", "3");
              resonpList.add(map2);
            }
          }
        }
        RespondPopupWindow mRespondPopupWindow = new RespondPopupWindow(this);
        mRespondPopupWindow.initmPopupWindowView(
            (LinearLayout) findViewById(R.id.MySendMemoActivityID), resonpList);
      } else {
        new DialogUtil(this, resultMSG).show();
      }
      all = null;

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #29
0
  private PluginResult startServer(JSONArray inputs, CallbackContext callbackContext) {
    Log.w(LOGTAG, "startServer");
    fromApplicationData = false;
    final String docRoot;

    // Get the input data.
    try {
      docRoot = inputs.getString(WWW_ROOT_ARG_INDEX);
      port = inputs.getInt(PORT_ARG_INDEX);
      cordovaRoot = inputs.getString(CORDOVA_ROOT_ARG_INDEX);
    } catch (JSONException exception) {
      Log.w(LOGTAG, String.format("JSON Exception: %s", exception.getMessage()));
      callbackContext.error(exception.getMessage());
      return null;
    }
    if (docRoot.startsWith("../../Documents/meteor")) {
      Context ctx = cordova.getActivity().getApplicationContext();
      localPath =
          new File(ctx.getApplicationInfo().dataDir, docRoot.substring(6)).getAbsolutePath();
      Log.w(LOGTAG, "setting app dir path to " + localPath);
      fromApplicationData = true;
    } else {
      if (docRoot.startsWith("/")) {
        // localPath =
        // Environment.getExternalStorageDirectory().getAbsolutePath();
        localPath = docRoot;
      } else {
        // localPath = "file:///android_asset/www";
        localPath = "www";
        if (docRoot.length() > 0) {
          localPath += "/";
          localPath += docRoot;
        }
      }
    }
    Log.w(LOGTAG, "localpath is set to " + docRoot);

    final CallbackContext delayCallback = callbackContext;
    cordova
        .getActivity()
        .runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                String errmsg = __startServer();
                if (errmsg != "") {
                  delayCallback.error(errmsg);
                } else {
                  url = "http://" + __getLocalIpAddress() + ":" + port;
                  delayCallback.success(url);
                }
              }
            });

    return null;
  }
  public void initialize(JSONArray params, CallbackContext callbackContext) throws JSONException {
    Context context = this.cordova.getActivity().getApplicationContext();

    String apiKey = params.getString(0);
    String senderId = params.getString(1);

    Netmera.init(context, apiKey);
    senderID = senderId;
    callbackContext.success();
  }