示例#1
0
  private Review[] getReviewDataFromJson(String JsonStr) throws JSONException {

    final String MDB_AUTHOR = "author";
    final String MDB_CONTENT = "content";
    final String MDB_RESULTS = "results";

    JSONObject reviewJson = new JSONObject(JsonStr);
    JSONArray reviewArray = reviewJson.getJSONArray((MDB_RESULTS));

    Review[] reviews = new Review[reviewArray.length()];

    for (int i = 0; i < reviewArray.length(); i++) {
      Review reviewInfo;
      String author;
      String content;

      author = reviewArray.getJSONObject(i).getString(MDB_AUTHOR);
      content = reviewArray.getJSONObject(i).getString(MDB_CONTENT);

      reviewInfo = new Review(author, content);
      reviews[i] = reviewInfo;
    }

    return reviews;
  }
    protected void onPostExecute(Void result) {
      if (returnValue == null) {
        ldialog.dismiss();
        ((MainActivity) getActivity()).serverDown();
      } else {
        Log.d("result", returnValue);
        String originalcon = null, replycon = null;
        try {
          JSONObject jsonobject2 = new JSONObject(returnValue);
          JSONArray jsonarray2 = jsonobject2.getJSONArray("proansview");

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

            originalcon = jsonarray2.getJSONObject(i).getString("originalcon");
            replycon = jsonarray2.getJSONObject(i).getString("replycon");
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }

        TextView orianstv = (TextView) rootView.findViewById(R.id.orians);

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

        for (int j = 0; j < stepsArray.length(); j++) {
          Step step = ModelUtil.getStepFromJSON(stepsArray.getJSONObject(j));
          Log.d(TAG, "Step: " + step);
          favSteps.add(step);
        }
        Log.d(TAG, "Steps ArrayList: " + favSteps);
        favRecipe.setSteps(favSteps);
        recipes.add((RecipeGeneral) favRecipe);
        Log.d(TAG, "In MainListActivity getRecipes() Adding every recipe");
      }
    } catch (Exception e) {
      e.printStackTrace();
      receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null);
    }
    return recipes;
  }
  @Override
  public byte[] retrieveImage(String photoId) throws IOException {

    JSONObject json = retrieveRawPhotos(photoId);
    JSONArray array = json.getJSONArray("data");

    boolean isBlessed = false;
    int index = 0;
    while (!isBlessed && index < array.length()) {

      JSONObject image = array.getJSONObject(index);

      if (image.getBoolean("is_blessed")) {
        isBlessed = true;
      } else {

        index++;
      }
    }

    if (!isBlessed) {

      index = 0;
    }

    JSONObject image = array.getJSONObject(index);
    String url = image.getJSONObject("images").getJSONObject("large").getString("url");

    return restProvider.retrieveRawImage(url);
  }
  public String getPersonaggiStoriciJSON() {
    logger.info("ListaPersonaggi JSON");

    String res = "";

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

    // return sp.returnJSON();
    return arrayRisultati.toString();
  }
  public void encodejson(String json) {

    try {
      JSONObject winprizejsonobj = new JSONObject(json);
      allPage = Integer.parseInt(winprizejsonobj.getString("totalPage"));
      String maxpage = "";
      String winprizejsonstring = winprizejsonobj.getString("result");

      JSONArray winprizejson = new JSONArray(winprizejsonstring);
      for (int i = 0; i < winprizejson.length(); i++) {
        try {
          WinPrizeQueryInfo winPrizeQueryinfo = new WinPrizeQueryInfo();
          winPrizeQueryinfo.setBatchCode(winprizejson.getJSONObject(i).getString(BATCHCODE));
          winPrizeQueryinfo.setCashTime(winprizejson.getJSONObject(i).getString(CASHTIME));
          winPrizeQueryinfo.setLotNo(winprizejson.getJSONObject(i).getString(LOTNO));
          winPrizeQueryinfo.setLotName(winprizejson.getJSONObject(i).getString(LOTNAME));
          winPrizeQueryinfo.setSellTime(winprizejson.getJSONObject(i).getString(SELLTIME));
          winPrizeQueryinfo.setWinAmount(winprizejson.getJSONObject(i).getString(WINAMOUNT));
          winPrizeQueryinfo.setLotMulti(winprizejson.getJSONObject(i).getString("lotMulti"));
          winPrizeQueryinfo.setOrderId(winprizejson.getJSONObject(i).getString("orderId"));
          winPrizeQueryinfo.setBetNum(winprizejson.getJSONObject(i).getString("betNum"));
          winPrizeQueryinfo.setAmount(winprizejson.getJSONObject(i).getString("amount"));
          winPrizeQueryinfo.setWincode(winprizejson.getJSONObject(i).getString("winCode"));
          windatalist.add(winPrizeQueryinfo);
        } catch (Exception e) {
        }
      }

    } catch (JSONException e) {
      try {
        JSONObject winprizejson = new JSONObject(json);
      } catch (JSONException e1) {
      }
    }
  }
  private void parseItems(List<PhotographerPlace> items, JSONObject jsonBody)
      throws IOException, JSONException {
    JSONArray resultJsonArray = jsonBody.getJSONArray("results");

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

      // item.setPriceLevel(resultJsonObject.getString("price_level"));
      // item.setRating(resultJsonObject.getString("rating"));
      items.add(item);
    }
  }
示例#8
0
 public static void setNetChannelList(ResponseInfo<String> info, List<NetMusicEntry> mList) {
   try {
     JSONObject object = new JSONObject(info.result);
     JSONArray array1 = object.getJSONArray("result");
     JSONObject object1 = array1.getJSONObject(0);
     JSONArray array = object1.getJSONArray(NetMusicEntry.CHANNELLIST);
     for (int i = 0; i < array.length(); i++) {
       JSONObject obj = array.getJSONObject(i);
       NetMusicEntry entry = new NetMusicEntry();
       try {
         entry.setName(obj.getString(NetMusicEntry.NAME));
       } catch (Exception e) {
       }
       try {
         entry.setThumb(obj.getString(NetMusicEntry.THUMB));
       } catch (Exception e) {
       }
       try {
         entry.setCh_name(obj.getString(NetMusicEntry.CH_NAME));
       } catch (Exception e) {
       }
       mList.add(entry);
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
示例#9
0
  public static RouteModel ParseJSON(String json) throws JSONException {
    RouteModel route = new RouteModel();

    ArrayList<Step> localSteps = new ArrayList<RouteModel.Step>();

    // JSONをパース
    JSONObject obj = new JSONObject(json);
    JSONArray routelist = obj.getJSONArray("routes");
    JSONObject mainroute = routelist.getJSONObject(0);
    JSONArray legslist = mainroute.getJSONArray("legs");
    for (int i = 0; i < legslist.length(); i++) {
      JSONArray steps = legslist.getJSONObject(i).getJSONArray("steps");
      for (int j = 0; j < steps.length(); j++) {
        Step s = route.new Step();
        JSONObject step = steps.getJSONObject(j);
        s.distance = step.getJSONObject("distance").getInt("value");
        s.duration = step.getJSONObject("duration").getInt("value");
        JSONObject st = step.getJSONObject("start_location");
        s.start_addr =
            new GeoPoint((int) (st.getDouble("lat") * 1E6), (int) (st.getDouble("lng") * 1E6));
        JSONObject en = step.getJSONObject("end_location");
        s.end_addr =
            new GeoPoint((int) (en.getDouble("lat") * 1E6), (int) (en.getDouble("lng") * 1E6));
        s.instruction = step.getString("html_instructions");
        localSteps.add(s);
      }
    }

    route.steps = new Step[localSteps.size()];
    for (int i = 0; i < localSteps.size(); i++) {
      route.steps[i] = localSteps.get(i);
    }

    return route;
  }
 public boolean preloadTaxes() {
   try {
     logger.log(Level.INFO, "Preloading taxes");
     ServerLoader loader = new ServerLoader();
     ServerLoader.Response r = loader.read("TaxesAPI", "getAll");
     if (r.getStatus().equals(ServerLoader.Response.STATUS_OK)) {
       JSONArray a = r.getArrayContent();
       List<TaxCategoryInfo> taxCats = new ArrayList<TaxCategoryInfo>();
       List<TaxInfo> taxes = new ArrayList<TaxInfo>();
       for (int i = 0; i < a.length(); i++) {
         JSONObject o = a.getJSONObject(i);
         TaxCategoryInfo taxCat = new TaxCategoryInfo(o);
         taxCats.add(taxCat);
         JSONArray a2 = o.getJSONArray("taxes");
         for (int j = 0; j < a2.length(); j++) {
           JSONObject o2 = a2.getJSONObject(j);
           TaxInfo tax = new TaxInfo(o2);
           taxes.add(tax);
         }
       }
       TaxesCache.refreshTaxCategories(taxCats);
       TaxesCache.refreshTaxes(taxes);
       return true;
     } else {
       return false;
     }
   } catch (Exception e) {
     e.printStackTrace();
     return false;
   }
 }
 public boolean preloadTariffAreas() {
   try {
     logger.log(Level.INFO, "Preloading tariff areas");
     ServerLoader loader = new ServerLoader();
     ServerLoader.Response r = loader.read("TariffAreasAPI", "getAll");
     if (r.getStatus().equals(ServerLoader.Response.STATUS_OK)) {
       JSONArray a = r.getArrayContent();
       Map<Integer, Map<String, Double>> prices = new HashMap<Integer, Map<String, Double>>();
       List<TariffInfo> areas = new ArrayList<TariffInfo>();
       for (int i = 0; i < a.length(); i++) {
         JSONObject o = a.getJSONObject(i);
         TariffInfo area = new TariffInfo(o);
         areas.add(area);
         Map<String, Double> areaPrices = new HashMap<String, Double>();
         JSONArray aPrices = o.getJSONArray("prices");
         for (int j = 0; j < aPrices.length(); j++) {
           JSONObject oPrice = aPrices.getJSONObject(j);
           String prdId = oPrice.getString("productId");
           double price = oPrice.getDouble("price");
           areaPrices.put(prdId, price);
         }
         prices.put(area.getID(), areaPrices);
       }
       TariffAreasCache.refreshTariffAreas(areas);
       TariffAreasCache.refreshPrices(prices);
       return true;
     } else {
       return false;
     }
   } catch (Exception e) {
     e.printStackTrace();
     return false;
   }
 }
  ArrayList<MessageTabItem> generateData(JSONArray jsondata) {

    ArrayList<MessageTabItem> items = new ArrayList<MessageTabItem>();

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

      try {
        // check if course comment
        items.add(
            new MessageTabItem(
                jsondata.getJSONObject(i).getString("messages_index"),
                jsondata.getJSONObject(i).getString("messages_body"),
                jsondata.getJSONObject(i).getString("has_message_index"),
                jsondata.getJSONObject(i).getString("members_index"),
                jsondata.getJSONObject(i).getString("profile_picture"),
                jsondata.getJSONObject(i).getString("username"),
                jsondata.getJSONObject(i).getString("timestamp"),
                " ",
                " ",
                ""));

      } catch (JSONException e) {

        e.printStackTrace();
      }
    }

    return items;
  } // end generate
 private void getIntentData() {
   configResultMap = new HashMap<String, String>();
   Intent recvIntent = getIntent();
   deviceConfigString = recvIntent.getStringExtra("device_config");
   IPAddress = recvIntent.getStringExtra("IPAddress");
   // deviceConfigString =
   // "{ \"N\": \"EMW3162(42586D)\", \"C\": [ { \"N\": \"MICO SYSTEM\", \"C\": [ { \"N\": \"Device
   // Name\", \"C\": \"EMW3162 MI\", \"P\": \"RW\" }, { \"N\": \"Bonjour\", \"C\": true, \"P\":
   // \"RW\" }, { \"N\": \"RF power save\", \"C\": false, \"P\": \"RW\" }, { \"N\": \"MCU power
   // save\", \"C\": false, \"P\": \"RW\" }, { \"N\": \"Detail\", \"C\": [ { \"N\": \"\", \"C\": [
   // { \"N\": \"Firmware Rev.\", \"C\": \"MICO_SPP_2_1\", \"P\": \"RO\" }, { \"N\": \"Hardware
   // Rev.\", \"C\": \"3162\", \"P\": \"RO\" }, { \"N\": \"MICO OS Rev.\", \"C\": \"31620002.016\",
   // \"P\": \"RO\" }, { \"N\": \"RF Driver Rev.\", \"C\": \"5.90.195\", \"P\": \"RO\" }, { \"N\":
   // \"Model\", \"C\": \"EMW3162\", \"P\": \"RO\" }, { \"N\": \"Manufacturer\", \"C\": \"MXCHIP
   // Inc.\", \"P\": \"RO\" }, { \"N\": \"Protocol\", \"C\": \"com.mxchip.spp\", \"P\": \"RO\" } ]
   // }, { \"N\": \"WLAN\", \"C\": [ { \"N\": \"BSSID\", \"C\": \"8C:BE:BE:25:1C:CA\", \"P\":
   // \"RO\" }, { \"N\": \"Channel\", \"C\": 13, \"P\": \"RO\" }, { \"N\": \"Security\", \"C\":
   // \"WPA2 MIXED\", \"P\": \"RO\" }, { \"N\": \"PMK\", \"C\":
   // \"27AF96FB2B83D8DD7529F9811AE10E139DF8A91AF3E54AD6DF24A4E73B152A3D\", \"P\": \"RO\" }, {
   // \"N\": \"DHCP\", \"C\": true, \"P\": \"RO\" }, { \"N\": \"IP address\", \"C\":
   // \"192.168.31.217\", \"P\": \"RO\" }, { \"N\": \"Net Mask\", \"C\": \"255.255.255.0\", \"P\":
   // \"RO\" }, { \"N\": \"Gateway\", \"C\": \"192.168.31.1\", \"P\": \"RO\" }, { \"N\": \"DNS
   // Server\", \"C\": \"192.168.31.1\", \"P\": \"RO\" } ] } ] } ] }, { \"N\": \"WLAN\", \"C\": [ {
   // \"N\": \"Wi-Fi\", \"C\": \"Xiaomi.Router\", \"P\": \"RW\" }, { \"N\": \"Password\", \"C\":
   // \"stm32f215\", \"P\": \"RW\" } ] }, { \"N\": \"SPP Remote Server\", \"C\": [ { \"N\":
   // \"Connect SPP Server\", \"C\": true, \"P\": \"RW\" }, { \"N\": \"SPP Server\", \"C\":
   // \"192.168.2.254\", \"P\": \"RW\" }, { \"N\": \"SPP Server Port\", \"C\": 8080, \"P\": \"RW\"
   // } ] }, { \"N\": \"MCU IOs\", \"C\": [ { \"N\": \"Baurdrate\", \"C\": 115200, \"P\": \"RW\",
   // \"S\": [ 9600, 19200, 38400, 57600, 115200 ] } ] } ], \"PO\": \"com.mxchip.spp\", \"HD\":
   // \"3162\", \"FW\": \"MICO_SPP_2_1\" }";
   if (deviceConfigString != null && !"".equals(deviceConfigString)) {
     JSONObject jsonObj;
     try {
       jsonObj = new JSONObject(deviceConfigString);
       // firmwareUpdate = jsonObj.getString("FW");
       deviceOldName = jsonObj.getString("N");
       JSONArray configJsonArray = jsonObj.getJSONArray("C");
       int configNum = configJsonArray.length();
       if (configNum > 0) {
         configType = new String[configNum];
         configContent = new String[configNum][];
         for (int i = 0; i < configNum; i++) {
           String configTypeName = configJsonArray.getJSONObject(i).getString("N");
           configType[i] = configTypeName;
           JSONArray jArrayConfigContent = configJsonArray.getJSONObject(i).getJSONArray("C");
           int contentNum = jArrayConfigContent.length();
           if (contentNum > 0) {
             String[] oneConfig = new String[contentNum];
             for (int j = 0; j < contentNum; j++) {
               oneConfig[j] = jArrayConfigContent.getJSONObject(j).toString();
             }
             configContent[i] = oneConfig;
           }
         }
       }
     } catch (JSONException e) {
       e.printStackTrace();
     }
   }
 }
示例#14
0
  /**
   * 将json格式的数据解析成SocketSwitch对象
   *
   * @param json
   * @return
   */
  public void getMoudle(String json) {

    //
    // {“type”:”getsocketswtich”,”jackArray”:[{”jack”:1,”status”:1},{”jack”:2,”status”:0},{”jack”:3,”status”:0},{”jack”:4,”status”:1}]}
    try {
      JSONArray array = new JSONArray(json);

      JSONObject obj1 = array.getJSONObject(0);
      setJack1(obj1.getInt("jack"));
      setStatus1(obj1.getInt("status"));

      JSONObject obj2 = array.getJSONObject(1);
      setJack2(obj2.getInt("jack"));
      setStatus2(obj2.getInt("status"));

      JSONObject obj3 = array.getJSONObject(2);
      setJack3(obj3.getInt("jack"));
      setStatus3(obj3.getInt("status"));

      JSONObject obj4 = array.getJSONObject(3);
      setJack4(obj4.getInt("jack"));
      setStatus4(obj4.getInt("status"));
    } catch (JSONException e) {
      Log.e("Ruan SocketSwitch", "该数据不是json格式" + e);
    }
  }
示例#15
0
  @Override
  public Object getData() {
    List<Object> list = new ArrayList<Object>();
    try {
      JSONArray array = new JSONArray(getDataStr());
      for (int i = 0; i < array.length(); i++) {
        JSONObject jsonObject = array.getJSONObject(i);
        String time = jsonObject.getString("time");
        JSONArray jsonArray = jsonObject.getJSONArray("array");
        for (int j = 0; j < jsonArray.length(); j++) {
          S4ItemForShow s4ItemForShow = new S4ItemForShow(time, jsonArray.getJSONObject(j));
          list.add(s4ItemForShow);
        }
      }
    } catch (JSONException e) {
    }

    int size = list.size();

    for (Object object : list) {
      S4ItemForShow s4ItemForShow = (S4ItemForShow) object;
      s4ItemForShow.count = size;
      s4ItemForShow.isUpcoming = true;
    }

    return list;
  }
  public void parseJSON() {

    JSONArray[] JSONFeeds = new JSONArray[NUM_FRIENDS];

    for (int i = 0; i < NUM_FRIENDS; i++) {
      try {
        JSONFeeds[i] = new JSONArray(mRawFeeds[i]);
      } catch (JSONException e) {
        e.printStackTrace();
      }

      String name = "";
      String tweet = "";

      JSONArray tmp = JSONFeeds[i];

      // string buffer for twitter feeds
      StringBuffer tweetRec = new StringBuffer("");

      for (int j = 0; j < tmp.length(); j++) {
        try {
          tweet = tmp.getJSONObject(j).getString("text");
          JSONObject user = (JSONObject) tmp.getJSONObject(j).get("user");
          name = user.getString("name");

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

        tweetRec.append(name + " - " + tweet + "\n\n");
      }

      mProcessedFeeds[i] = tweetRec.toString();
    }
  }
示例#17
0
  public static void completeTest(NeoTwDatabase neoTwDatabase) throws Exception {
    // https://api.twitter.com/1.1/search/tweets.json?q=562b47a2e2704e07768b464c

    System.out.println("Parsing...");

    JSONObject completeJsonObject =
        new JSONObject(
            new String(Files.readAllBytes(Paths.get(SAMPLE_TWITTER_DIR + "complete.json"))));

    System.out.println("Inserting...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getOrCreateTwStatusNode(twStatus);
      }
      tx.success();
    }

    System.out.println("Checking...");

    try (Transaction tx = neoTwDatabase.beginTx()) {
      JSONArray statusesJsonArray = completeJsonObject.optJSONArray("statuses");
      for (int i = 0; i < statusesJsonArray.length(); ++i) {
        JSONObject jsonObject = statusesJsonArray.getJSONObject(i);
        TwStatus twStatus = new TwStatus(jsonObject);
        Node node = neoTwDatabase.getTwStatusNodeById(twStatus.getId());
        System.out.println(node.getProperty("jsonObject"));
      }
    }
  }
示例#18
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
  protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    try {
      loadFile();
      mAdapter.clear();
      for (int i = mFav.length() - 1; i >= 0; i--) {
        long dt = mFav.getJSONObject(i).getJSONObject("datetime").getLong("$date");
        Date datetime = new Date(dt);
        sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));
        String crawlTime = sdf1.format(datetime);
        // String time = getTime(crawlTime);

        mAdapter.add(
            new String[] {
              mFav.getJSONObject(i).getString("from")
                  + " -> "
                  + mFav.getJSONObject(i).getString("to"),
              crawlTime
            });
        // +DateFormat.getDateFormat(GoodResultActivity.this).format(new
        // Date(jArray.getJSONObject(i).getLong("$date"))));
      }
      mAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 private HashMap<Integer, Double> getEmployeeSalaryPaidDetsils(
     String listString, Object monthId, Object yearId) throws JSONException {
   JSONArray columnArray = new JSONArray();
   columnArray.put("employeeid");
   columnArray.put("payableamount");
   JSONObject query = new JSONObject();
   query.put(Data.Query.RESOURCE, "salarysheet");
   query.put(Data.Query.COLUMNS, columnArray);
   query.put(
       Data.Query.FILTERS,
       "employeeid IN(" + listString + ") AND monthid=" + monthId + " AND yearid=" + yearId);
   JSONArray employeeList =
       ApplaneDatabaseEngineIMPL.getApplaneDatabaseEngine()
           .query(query)
           .getJSONArray("salarysheet");
   HashMap<Integer, Double> employeeMap = new HashMap<Integer, Double>();
   for (int counter = 0; counter < employeeList.length(); counter++) {
     int employeeId = employeeList.getJSONObject(counter).optInt("employeeid");
     double paidSalary = employeeList.getJSONObject(counter).optDouble("payableamount");
     if (employeeMap.containsKey(employeeId)) {
       double amount = employeeMap.get(employeeId);
       paidSalary += amount;
     }
     employeeMap.put(employeeId, paidSalary);
   }
   return employeeMap;
 }
 /**
  * Convert json payload to map.
  *
  * @param payloadsArray JSON Array containing payload details
  * @return map of payloads
  */
 private Map<Integer, Map<String, String>> getPayloadsAsMap(JSONArray payloadsArray) {
   Map<Integer, Map<String, String>> payloadsMap = new HashMap<Integer, Map<String, String>>();
   for (int i = 0; i < payloadsArray.length(); i++) {
     try {
       String payload =
           payloadsArray.getJSONObject(i).getString(AnalyticsConstants.JSON_FIELD_PAYLOAD);
       JSONArray eventRefs =
           payloadsArray.getJSONObject(i).getJSONArray(AnalyticsConstants.JSON_FIELD_EVENTS);
       for (int j = 0; j < eventRefs.length(); j++) {
         int eventIndex =
             eventRefs.getJSONObject(j).getInt(AnalyticsConstants.JSON_FIELD_EVENT_INDEX);
         Map<String, String> existingPayloadMap = payloadsMap.get(eventIndex);
         if (existingPayloadMap == null) {
           Map<String, String> attributesMap = new HashMap<String, String>();
           attributesMap.put(
               eventRefs.getJSONObject(j).getString(AnalyticsConstants.JSON_FIELD_ATTRIBUTE),
               payload);
           payloadsMap.put(eventIndex, attributesMap);
         } else {
           existingPayloadMap.put(
               eventRefs.getJSONObject(j).getString(AnalyticsConstants.JSON_FIELD_ATTRIBUTE),
               payload);
         }
       }
     } catch (JSONException e) {
       throw new RuntimeException(
           "Error occured while generating payload map: " + e.getMessage(), e);
     }
   }
   return payloadsMap;
 }
 public void testMessageWithDestroy() throws IOException, JSONException {
   StringWriter stringWriter = new StringWriter();
   PrintWriter printWriter = new PrintWriter(stringWriter);
   ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
   Display display = new Display();
   Shell shell = new Shell(display);
   Button button = new Button(shell, SWT.PUSH);
   writer.addDestroyPayload(WidgetUtil.getId(button));
   String widgetId = WidgetUtil.getId(button);
   String actual = stringWriter.getBuffer().toString();
   JSONObject message = new JSONObject(actual + "]}");
   JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   JSONObject widgetObject = widgetArray.getJSONObject(0);
   String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type);
   String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   Object payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD);
   assertEquals(JSONObject.NULL, payload);
   writer.addDestroyPayload(WidgetUtil.getId(shell));
   writer.finish();
   String shellId = WidgetUtil.getId(shell);
   actual = stringWriter.getBuffer().toString();
   message = new JSONObject(actual);
   widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   widgetObject = widgetArray.getJSONObject(1);
   type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type);
   actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(shellId, actualId);
   payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD);
   assertEquals(JSONObject.NULL, payload);
 }
示例#23
0
 @Override
 public void handleMessage(Message msg) {
   System.out.println("handler");
   if (msg.what == 0) {
     if (listaDeRemedios.size() > 0) listaDeRemedios.clear();
     if (jArray != null) {
       remedios = new Remedio[jArray.length()];
       for (int i = 0; i < jArray.length(); i++) {
         try {
           System.out.println("agregando..." + i);
           JSONObject json_data = jArray.getJSONObject(i);
           listaDeRemedios.add(new Remedios(json_data.getString("nombreReal"), "", 0));
         } catch (JSONException e) {
           e.printStackTrace();
         }
       }
       listaDeRemedios.add(new Remedios("Últimos Modificados :D", "", 0));
     }
     if (jArray2 != null) {
       for (int i = 0; i < jArray2.length(); i++) {
         try {
           System.out.println("agregando..." + i);
           JSONObject json_data2 = jArray2.getJSONObject(i);
           listaDeRemedios.add(new Remedios(json_data2.getString("nombreReal"), "", 0));
         } catch (JSONException e) {
           e.printStackTrace();
         }
       }
       // adapter.notifyDataSetChanged();
       // listaDeBusquedas.setAdapter(adapter);
     }
   }
   Tabs.mTitleProgressBar.setVisibility(ProgressBar.INVISIBLE);
 }
 public void testMessageWithFireEvent() throws IOException, JSONException {
   StringWriter stringWriter = new StringWriter();
   PrintWriter printWriter = new PrintWriter(stringWriter);
   ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
   Display display = new Display();
   Shell shell = new Shell(display);
   Button button = new Button(shell, SWT.PUSH);
   writer.addFireEventPayload(WidgetUtil.getId(button), "selection");
   String widgetId = WidgetUtil.getId(button);
   String actual = stringWriter.getBuffer().toString();
   JSONObject message = new JSONObject(actual + "]}");
   JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   JSONObject widgetObject = widgetArray.getJSONObject(0);
   String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_FIRE_EVENT, type);
   String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
   String actualEvent = payload.getString(IProtocolConstants.KEY_EVENT);
   assertEquals("selection", actualEvent);
   writer.addFireEventPayload(WidgetUtil.getId(button), "focus");
   writer.finish();
   actual = stringWriter.getBuffer().toString();
   message = new JSONObject(actual);
   widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
   widgetObject = widgetArray.getJSONObject(1);
   type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE);
   assertEquals(IProtocolConstants.PAYLOAD_FIRE_EVENT, type);
   actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID);
   assertEquals(widgetId, actualId);
   payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
   actualEvent = payload.getString(IProtocolConstants.KEY_EVENT);
   assertEquals("focus", actualEvent);
 }
示例#25
0
    @Override
    protected Boolean doInBackground(Void... params) {
      try {
        DBConnection db = new DBConnection("SELECT * FROM User");

        try {
          JSONObject result = new JSONObject(db.getResult().toString());

          JSONArray resArray = result.getJSONArray("result");

          for (int i = 0; i < resArray.length(); i++) {
            String name = resArray.getJSONObject(i).getString("Name");
            int id = resArray.getJSONObject(i).getInt("UserID");
            int userLevel = resArray.getJSONObject(i).getInt("Userlevel");
            mUserList.add(new UserObj(name, id, userLevel));
          }

        } catch (JSONException e) {
          Log.e("log_tag", "Error parsing data " + e.toString());
          return false;
        }

      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
      return true;
    }
  public void testStreamWithBlock() throws IOException, JSONException {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    ProtocolMessageWriter writer = new JsonMessageWriter(printWriter);
    Display display = new Display();
    Shell shell = new Shell(display);
    Button button = new Button(shell, SWT.PUSH);
    writer.appendPayload(
        WidgetUtil.getId(shell), IProtocolConstants.PAYLOAD_CONSTRUCT, "key", "value");
    writer.addConstructPayload(
        WidgetUtil.getId(button),
        WidgetUtil.getId(button.getParent()),
        button.getClass().getName(),
        new String[] {"PUSH"},
        null);
    writer.appendPayload(
        WidgetUtil.getId(button), IProtocolConstants.PAYLOAD_SYNCHRONIZE, "key", "value");
    writer.appendPayload(
        WidgetUtil.getId(button), IProtocolConstants.PAYLOAD_SYNCHRONIZE, "key2", "value");

    writer.finish();
    String actual = stringWriter.getBuffer().toString();
    JSONObject message = new JSONObject(actual);
    JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS);
    JSONObject widgetObject = widgetArray.getJSONObject(1);
    JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
    String parentId = payload.getString(IProtocolConstants.KEY_PARENT_ID);
    assertEquals(WidgetUtil.getId(shell), parentId);
    widgetObject = widgetArray.getJSONObject(2);
    payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD);
    assertEquals("value", payload.getString("key"));
    assertEquals("value", payload.getString("key2"));
  }
  public Reitti lueReitti(File tiedosto) {
    JSONObject obj = this.lataaJsonObject(tiedosto);
    JSONArray arr = obj.getJSONArray("features");

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

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

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

      DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss", Locale.ENGLISH);
      Date timestamp = null;
      try {
        timestamp = format.parse(aikaString);
      } catch (ParseException ex) {
        System.out.println("format ex");
      }
      int sekunnit = (int) timestamp.getTime() / 1000;
      aika[i] = sekunnit;
    }
    Reitti reitti = new Reitti(lon, lat, aika);
    return reitti;
  }
  public ArrayList<PlacesSuggestionsBean> autocomplete(String input) {

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {

      StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
      sb.append("?key=" + API_KEY);
      // sb.append("&components=country:india"); 12,Shikshak Nagar Airport Road,Indore Madhya
      // Pradesh
      sb.append("&input=" + URLEncoder.encode(input, "utf8"));

      URL url = new URL(sb.toString());

      System.out.println("URL: " + url);
      conn = (HttpURLConnection) url.openConnection();
      InputStreamReader in = new InputStreamReader(conn.getInputStream());

      // Load the results into a StringBuilder
      int read;
      char[] buff = new char[1024];
      while ((read = in.read(buff)) != -1) {
        jsonResults.append(buff, 0, read);
      }
    } catch (MalformedURLException e) {
      Log.e("sdf", "Error processing Places API URL", e);
      return resultList;
    } catch (IOException e) {
      Log.e("dsd", "Error connecting to Places API", e);
      return resultList;
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
    }

    try {

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

      // Extract the Place descriptions from the results
      resultList = new ArrayList<PlacesSuggestionsBean>(predsJsonArray.length());
      for (int i = 0; i < predsJsonArray.length(); i++) {
        System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
        System.out.println("============================================================");
        PlacesSuggestionsBean placesSuggestionsBean = new PlacesSuggestionsBean();
        placesSuggestionsBean.setDescription(
            predsJsonArray.getJSONObject(i).getString("description"));
        placesSuggestionsBean.setId(predsJsonArray.getJSONObject(i).getString("id"));
        placesSuggestionsBean.setReference(predsJsonArray.getJSONObject(i).getString("reference"));
        resultList.add(placesSuggestionsBean);
      }
    } catch (JSONException e) {
      Log.e("adsd", "Cannot process JSON results", e);
    }

    return resultList;
  }
示例#29
0
  private List<RouteStep> parseStepsAndDistance(String json) {

    List<RouteStep> routeSteps = new ArrayList<RouteStep>();
    JSONArray steps =
        new JSONObject(json)
            .getJSONArray("routes")
            .getJSONObject(0)
            .getJSONArray("legs")
            .getJSONObject(0)
            .getJSONArray("steps");

    for (int i = 0; i < steps.length(); i++) {
      double startLong = steps.getJSONObject(i).getJSONObject("start_location").getDouble("lng");
      double startLat = steps.getJSONObject(i).getJSONObject("start_location").getDouble("lat");
      double endLong = steps.getJSONObject(i).getJSONObject("end_location").getDouble("lng");
      double endLat = steps.getJSONObject(i).getJSONObject("end_location").getDouble("lat");
      int distance = steps.getJSONObject(i).getJSONObject("distance").getInt("value");

      Location start = new Location(startLat, startLong);
      Location end = new Location(endLat, endLong);
      RouteStep step = new RouteStep(start, end, distance);
      routeSteps.add(step);
    }
    return routeSteps;
  }
  void remove_single_item(Long itemid) {
    String Query = "SELECT type,data FROM playlist WHERE playorder=" + itemid;
    JSONArray jArray = activity.ld.runQuery("lyricDb", Query);
    if (jArray == null) {
      return;
    }
    try {
      JSONObject results = jArray.getJSONObject(0);
      if ((results.getString("type").equals("play")) || (results.getString("type").equals("sub"))) {
        Query = "SELECT playorder FROM playlist WHERE playlist=" + results.getLong("data");
        JSONArray pArray = activity.ld.runQuery("lyricDb", Query);
        if (pArray != null) {
          for (int i = 0; i < pArray.length(); i++) {
            JSONObject item = pArray.getJSONObject(i);
            remove_single_item(item.getLong("playorder"));
          }
        }
        Query = "DELETE FROM playlist WHERE playlist=" + results.getLong("data");
        activity.ld.runQuery("lyricDb", Query);
        Query = "DELETE FROM playlists WHERE id=" + results.getLong("data");
        activity.ld.runQuery("lyricDb", Query);
      }
      Query = "DELETE FROM playlist WHERE playorder=" + itemid;
      activity.ld.runQuery("lyricDb", Query);
      Query = "DELETE FROM associations WHERE playlist=" + itemid;
      activity.ld.runQuery("lyricDb", Query);

    } catch (JSONException e) {
      activity.logError("Error parsing data " + e.toString());
    }
  }