public void DownLoadImageFilesWithIon(String url) { showDialog(); showTempImage(url); final TextView textView = ((TextView) getActivity().findViewById(R.id.download_image_textView)); final String name = handleString(url); url = Config.url + name; Log.e("Cursor", "ImageSelectedRecommendedFragment:" + url); Ion.with(this) .load(url) .progressBar((ProgressBar) getActivity().findViewById(R.id.download_image_progress_bar)) .progressHandler( new ProgressCallback() { @Override public void onProgress(long l, long l2) { double percent = ((double) l) / l2; NumberFormat format = NumberFormat.getInstance(); format.setMaximumFractionDigits(2); textView.setText("" + format.format(percent * 100) + "%"); } }) .write(new File(Config.SDCARD_MOFA + name)) .setCallback( new FutureCallback<File>() { @Override public void onCompleted(Exception e, File file) { Intent intent = new Intent(getActivity(), HandleImageActivity.class); intent.putExtra(ImageSelectedActivity.INTENT_EXTRA_NAME_IMAGE_SELECTED, name); intent.putExtra("network", true); startActivity(intent); getActivity().finish(); } }); }
private void unregister() { updateState(UnregisterState.UNREGISTERING); String registeredNumber = mPreferenceReader.getRegisteredNumber(); String password = mPreferenceReader.getPassword(); String usernamePassword = registeredNumber + ":" + password; Log.d(TAG, "Using username and password combo: " + usernamePassword); String basicAuth = Base64.encodeToString(usernamePassword.getBytes(), Base64.NO_WRAP); Ion.with(this) .load("DELETE", "https://whisperpush.cyanogenmod.org/v1/accounts/gcm") .addHeader("Authorization", "Basic " + basicAuth) .asString() .withResponse() .setCallback( new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception error, Response<String> stringResponse) { if (error != null) { Log.e(TAG, "HTTP Request Error", error); updateState(UnregisterState.ERROR); } else { int responseCode = stringResponse.getHeaders().getResponseCode(); Log.d(TAG, "HTTP Result: " + responseCode); if (responseCode != 204) { updateState(UnregisterState.ERROR); return; } else { wipeData(); } } } }); }
private void postFormData(String requestUrl, Iterable<Part> files) { // Displays the progress bar for the first time. // mNotificationHelper.createNotification(); Ion.with(getApplicationContext()) .load(requestUrl) .uploadProgressHandler( new ProgressCallback() { @Override public void onProgress(long uploaded, long total) { long percentage = (uploaded * 100) / total; if (percentage % 5 == 0) { // mNotificationHelper.progressUpdate((int) percentage); } } }) .setTimeout(60 * 60 * 1000) .addMultipartParts(files) .asString() .withResponse() .setCallback( new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception e, Response<String> result) { // mNotificationHelper.completed(); if (e != null) { broadcastServiceResult(STATUS_TRANSACTION_FAILED, e.getMessage()); } else { broadcastServiceResult(STATUS_TRANSACTION_COMPLETE, ""); } } }); }
@Override public View getView(final int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(_activity); } else { imageView = (ImageView) convertView; } Ion.with(_activity, _filePaths.get(position)) .withBitmap() .resize(256, 256) .centerCrop() .placeholder(R.drawable.no_photo) .error(R.drawable.no_photo) .intoImageView(imageView); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // v.getTag(); // TODO Auto-generated method stub Intent intent = new Intent(_activity, ImagePreviewActivity.class); intent.putStringArrayListExtra(constants.IMAGES_PATH, _filePaths); intent.putExtra(constants.IMAGE_POSITION, position); _activity.startActivity(intent); } }); return imageView; }
@Override public void run() { mUserAvailability.setText(R.string.checking_availability); mUserAvailability.setVisibility(View.VISIBLE); mAvailabilityProgress.setVisibility(View.VISIBLE); Ion.with(getActivity()) .load( RedditApi.REDDIT_URL + "/user/" + mUsername.getText().toString() + "/about.json") .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (e != null) { e.printStackTrace(); return; } if (result.get("error") != null) { showUsernameAvailable(); } else { showUsernameNotAvailable(); } } }); }
/* Get ratings for the given bssid/ssid ids. Build a notifcation of infected ssids. */ public void setNotification() { Ion.with(c, getUrl()) .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject jsonRepsonse) { if (e != null) { Log.i(GenUtil.LOG_TAG, e.toString()); return; } Set<String> infectedIds = new HashSet<String>(); Rating rating; String bssid, ssid; for (JsonObject jsonObject : jsonObjects) { bssid = getBssid(jsonObject); ssid = getSsid(jsonObject); if (jsonRepsonse.has(bssid)) { rating = new Rating(jsonRepsonse.get(bssid).getAsJsonObject(), ssid); } else { rating = new Rating(jsonRepsonse.get(ssid).getAsJsonObject(), ssid); } if (rating.isInfected()) { infectedIds.add(ssid); } } InfectedNotificationBuilder notificationBuilder = new InfectedNotificationBuilder(c, new ArrayList<String>(infectedIds)); notificationBuilder.build(); } }); }
@Override public void get(HashMap<String, String> params) { Ion.with(mContext) .load(BASE_URL + VERSION + createUrlParameters(params)) .asJsonObject() .setCallback(mFutureCallback); }
@Override public View getView(int position, View convertView, ViewGroup parent) { ListViewHolder mViewHolder; if (convertView == null) { convertView = inflater.inflate(R.layout.item_reviewlist, parent, false); mViewHolder = new ListViewHolder(convertView); convertView.setTag(mViewHolder); } else { mViewHolder = (ListViewHolder) convertView.getTag(); } ReviewItem currentReview = getItem(position); mViewHolder.tv_username.setText(currentReview.getUserName()); mViewHolder.tv_date.setText(currentReview.getDate()); mViewHolder.tv_content.setText(currentReview.getContent()); mViewHolder.rb_rating.setRating(currentReview.getRating()); if (!currentReview.getUserImgUrl().equals("")) { Ion.with(mViewHolder.iv_usericon) .placeholder(R.drawable.ic_stars_black_24dp) .load(currentReview.getUserImgUrl()); } else { mViewHolder.iv_usericon.setScaleType(ImageView.ScaleType.CENTER_CROP); mViewHolder.iv_usericon.setImageResource(R.drawable.user_placeholder); } return convertView; }
/** * Retrieves a list of events which will be processed by the passed in callback. * * @param context used for resource retrieval */ private java.util.Map<Integer, List<Event>> getEvents(final Context context) { java.util.Map<Integer, List<Event>> toReturn = new HashMap<Integer, List<Event>>(); try { Events result = Ion.with(context) .load( context.getResources().getString(R.string.guild_wars_2_api_url) + "event_details.json") .as(new TypeToken<Events>() {}) .get(); for (java.util.Map.Entry<String, EventDetails> entry : result.getEvents().entrySet()) { Event event = new Event(); int mapId = entry.getValue().getMap_id(); event.setId(entry.getKey()); event.setName(entry.getValue().getName()); if (toReturn.containsKey(mapId)) { toReturn.get(mapId).add(event); } else { List<Event> eventList = new ArrayList<Event>(); eventList.add(event); toReturn.put(entry.getValue().getMap_id(), eventList); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return toReturn; }
private void load() { String url = Constants.wcfGetContentById + responseContentItemPk + "/" + BrewSharedPrefs.getUserToken(); loadingObj = Ion.with(getApplicationContext()) .load(url) .setHeader("Cache-Control", "No-Cache") .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { try { if (result != null) { RecipeContent recipeContent = JsonToObject.JsonToRecipeContent(result); BrewSharedPrefs.setCurrentToken(recipeContent.getToken()); BrewSharedPrefs.setCurrentContentTitle(recipeContent.getTitle()); BrewSharedPrefs.setLastContentItemPk(recipeContent.getContentItemPk()); BrewSharedPrefs.setNextContentItemId(recipeContent.getNextContentItemId()); setShareIntent(); toggleStar = recipeContent.isFavorite(); imageList = recipeContent.getImagesMList(); // imageUrlList = new ArrayList<String>(); for (Image item : imageList) { // // imageUrlList.add(item.getImageUrl()); adapter.add(item); } boolean addRecipe = false; if (recipeContent.getNextContentItemId() > 0) { Image placeHolder = new Image(); placeHolder.setImageUrl(Constants.urlRecipePlaceHolder); adapter.add(placeHolder); // // imageUrlList.add(Constants.urlRecipePlaceHolder); addRecipe = true; } adapter.setAddRecipe(addRecipe); adapter.notifyDataSetChanged(); addFabListener(); } } catch (Exception ex) { if (BuildConfig.DEBUG) { Log.e(Constants.LOG, ex.getMessage()); } } } }); }
// fetch the weirdo opaque token google voice needs... void fetchRnrSe(String authToken) throws ExecutionException, InterruptedException { JsonObject json = Ion.with(this) .load("https://www.google.com/voice/request/user") .setHeader("Authorization", "GoogleLogin auth=" + authToken) .asJsonObject() .get(); String rnrse = json.get("r").getAsString(); settings.edit().putString("_rns_se", rnrse).commit(); }
private void getInterventionsSyncro() throws Exception { String jsonReq; Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(REVISION, globalPrefs.getLong(Constants.REVISION_INTERVENTI, 0L)); jsonReq = JsonCR2.createRequest( Constants.JSON_INTERVENTIONS_SECTION, Constants.JSON_MYSYNCRO_INTERVENTIONS_ACTION, parameters, UtenteController.tecnicoLoggato.idutente.intValue()); Ion.with(this) .load(String.format(formattedURL, urlString)) .setBodyParameter(Constants.DATA_POST_PARAMETER, jsonReq) .asString() .setCallback( new FutureCallback<String>() { @Override public void onCompleted(Exception exception, String response) { if (response != null) { try { JSONObject jsonResp = new JSONObject(JsonCR2.read(response.trim()).toJSONString()); runAsyncTaskInterventionsSyncro(jsonResp); } catch (ParseException e) { e.printStackTrace(); BugSenseHandler.sendException(e); } catch (Exception e) { e.printStackTrace(); BugSenseHandler.sendException(e); } finally { setRefreshActionButtonState(false); } } else { setRefreshActionButtonState(false); InterventixToast.makeToast(serviceNotAvailable, Toast.LENGTH_LONG); } } }); }
// Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.txtAppName.setText(""); holder.txtAppDescription.setText(""); MyAppEntity myApp = myApps.get(position); Ion.with(holder.imgAppIcon) .placeholder(R.drawable.more_app_default_icon) .error(R.drawable.more_app_default_icon) .load(myApp.image); holder.txtAppName.setSelected(true); holder.txtAppName.setText(myApp.name); holder.txtAppDescription.setText(myApp.description); }
// hit the google voice api to send a text void sendRnrSe(String authToken, String rnrse, String number, String text) throws Exception { JsonObject json = Ion.with(this) .load("https://www.google.com/voice/sms/send/") .setHeader("Authorization", "GoogleLogin auth=" + authToken) .setBodyParameter("phoneNumber", number) .setBodyParameter("sendErrorSms", "0") .setBodyParameter("text", text) .setBodyParameter("_rnr_se", rnrse) .asJsonObject() .get(); if (!json.get("ok").getAsBoolean()) throw new Exception(json.toString()); }
public List<World> getWorlds(final Context context) { List<World> toReturn = new ArrayList<>(); try { toReturn = Ion.with(context) .load( context.getResources().getString(R.string.guild_wars_2_api_v2_url) + "worlds?ids=all") .as(new TypeToken<List<World>>() {}) .get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } return toReturn; }
private void downloadData() { // AppConfigEntity appConfigEntity = AppCommon.getInstance().getAppLocalConfig(); // if (appConfigEntity != null) { AppLog.i(">>>> MoreAppsDialog # downloadData"); String url = DEFAULT_EXTRA_APP_URL; // appConfigEntity.myExtraApps.download; getExtraAppFuture = Ion.with(getContext()) .load(url) .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (result != null) { layoutLoading.setVisibility(View.GONE); myExtraApps = AppParseUtil.parseExtraApps(result); displayData(); AppLocalSharedPreferences.getInstance().setMyExtraApps(result.toString()); AppLog.i(">>>> MoreAppsDialog # downloadData # success"); } else { if (e != null) { e.printStackTrace(); } String json = AppLocalSharedPreferences.getInstance().getMyExtraAppsString(); myExtraApps = AppParseUtil.parseExtraApps(json); if (myExtraApps != null) { layoutLoading.setVisibility(View.GONE); displayData(); AppLog.i( ">>>> MoreAppsDialog # downloadData # fail # load cached data # success"); } else { progressBar.setVisibility(View.GONE); txtLoading.setText("Can not connect to server!"); AppLog.e( ">>>> MoreAppsDialog # downloadData # fail # load cached data # fail"); } } } }); // } // else { // progressBar.setVisibility(View.GONE); // txtLoading.setText("Can not connect to server"); // AppLog.e(">>>> MoreAppsDialog # downloadData # fail"); // } }
public void doLoad(final String contentUrl) { switch (ContentType.getContentType(contentUrl)) { case DEVIANTART: if (!imageShown) { Ion.with(this) .load("http://backend.deviantart.com/oembed?url=" + contentUrl) .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (result != null && !result.isJsonNull() && (result.has("fullsize_url") || result.has("url"))) { String url; if (result.has("fullsize_url")) { url = result.get("fullsize_url").getAsString(); } else { url = result.get("url").getAsString(); } doLoadImage(url); } else { Intent i = new Intent(getActivity(), Website.class); i.putExtra(Website.EXTRA_URL, contentUrl); getActivity().startActivity(i); } } }); } break; case IMAGE: doLoadImage(contentUrl); break; case IMGUR: doLoadImgur(contentUrl); break; case VID_ME: case STREAMABLE: case GIF: doLoadGif(contentUrl); break; } }
@Override public void loadTropes(Uri url) { Future<Response<String>> articleStr = Ion.with(getActivity(), url.toString()) .asString() .withResponse() .setCallback( new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception e, Response<String> response) { if (e != null) { onLoadError(); } else { Uri redirectUrl = Uri.parse(response.getRequest().getUri().toString()); TropesArticle article = createIndex(response.getResult(), redirectUrl); onLoadFinish(article); } } }); }
public void submitSaman() { getValue(); Future<String> stringFuture = Ion.with(getActivity()) .load(Backend.URL + "saman.php") .setBodyParameter("nomatrik", strNoMatrik) .setBodyParameter("noplat", strNoPlat) .setBodyParameter("catatan", strCatatan) .setBodyParameter("tempat", strTempat) .setBodyParameter("kesalahan", strKesalahan) .setBodyParameter("pelapor", userID) .asString() .setCallback( new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { try { JSONObject json = new JSONObject(result); // Converts the string "result" to a JSONObject String json_result = json.getString( "status"); // Get the string "result" inside the Json-object if (json_result.equalsIgnoreCase( "success")) { // Checks if the "result"-string is equals to "ok" String success = json.getString("status"); Toast.makeText(getActivity(), success, Toast.LENGTH_LONG) .show(); // This will show the user what went wrong with a toast } else { // Result is NOT "OK" String error = json.getString("error"); Toast.makeText(getActivity(), error, Toast.LENGTH_LONG) .show(); // This will show the user what went wrong with a toast } } catch (JSONException er) { // This method will run if something goes wrong with the json, like a typo to // the json-key or a broken JSON. er.printStackTrace(); } } }); }
private void retrieveAccessTokenfromServer() { Ion.with(this) .load("http://localhost:8000/token.php") .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (e == null) { String accessToken = result.get("token").getAsString(); videoClient = new VideoClient(VideoActivity.this, accessToken); } else { Toast.makeText( VideoActivity.this, R.string.error_retrieving_access_token, Toast.LENGTH_LONG) .show(); } } }); }
@Override public View getView(int position, View convertView, ViewGroup parent) { BaseGalleryImage baseGalleryImage = baseGalleryImages.get(position); View mainView = convertView; // check if the view is created if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) ImgurApp.getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE); mainView = layoutInflater.inflate(R.layout.gallery_image_item, null); } ImageView pic = (ImageView) mainView.findViewById(R.id.iv_gallery_image_item_thumb); ImageView backg = (ImageView) mainView.findViewById(R.id.iv_gallery_image_item_back); String url = ""; if (baseGalleryImage instanceof GalleryImage) { url = ImgurConstants.IMGUR_URL + baseGalleryImage.getId() + BaseImage.SMALL_SQUARE_THUMBNAIL + ".jpg"; } else { url = ImgurConstants.IMGUR_URL + ((GalleryAlbum) baseGalleryImage).getCover() + BaseImage.SMALL_SQUARE_THUMBNAIL + ".jpg"; } // setting the picture in the main gallery Ion.with(pic).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).load(url); // setting the color of the backgroun setBackgroundVoteColor(backg, baseGalleryImage); return mainView; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = "Today's Hunts"; // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); JsonObject json = new JsonObject(); json.addProperty("client_id", Constants.API_CLIENT_ID); json.addProperty("client_secret", Constants.API_CLIENT_SECRET); json.addProperty("grant_type", "client_credentials"); Ion.with(getApplicationContext()) .load("https://api.producthunt.com/v1/oauth/token") .setJsonObjectBody(json) .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { if (result != null && result.has("access_token")) { Constants.CLIENT_TOKEN = result.get("access_token").getAsString(); Constants.TOKEN_EXPIRES = System.currentTimeMillis() + ((long) result.get("expires_in").getAsInt()) * 1000l; browsingFragment.refresh(getApplicationContext()); } } }); }
public void setCourseSummary(@NonNull final CourseSummary courseSummary) { this.courseSummary = courseSummary; Ion.with(courseImageView) .centerCrop() .load( "android.resource://" + activity.getPackageName() + "/" + Photos.photoFor(courseSummary.id)); courseNameView.setText(courseSummary.name); courseLocationView.setText(courseSummary.city + ", " + courseSummary.state); courseStatsView.setText( String.format("%d Holes - Par %d", courseSummary.numHoles, courseSummary.par)); Location lastKnownLocation = DoglegApplication.application().lastKnownLocation(); if (lastKnownLocation != null) { double miles = Units.metersToMiles(lastKnownLocation.distanceTo(courseSummary.location.toLocation())); navigationButton.setText(String.format("%.1f miles", miles)); } }
@Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v; if (convertView != null) v = convertView; else v = vi.inflate(R.layout.comment, null); TextView content = (TextView) v.findViewById(R.id.content); TextView username = (TextView) v.findViewById(R.id.from); ImageView profileImage = (ImageView) v.findViewById(R.id.profileImage); TextView time = (TextView) v.findViewById(R.id.time); TextView plusOne = (TextView) v.findViewById(R.id.plusOne); ImageView accepted = (ImageView) v.findViewById(R.id.accepted); if (comments.get(position).isAccepted()) { accepted.setVisibility(View.VISIBLE); accepted.setBackgroundResource(R.drawable.accepted); } else accepted.setVisibility(View.GONE); if (post.getUsername().equals(prefs.getString("loggedIn", ""))) { accepted.setVisibility(View.VISIBLE); if (comments.get(position).isAccepted()) accepted.setBackgroundResource(R.drawable.accepted); else accepted.setBackgroundResource(R.drawable.not_accepted); accepted.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (comments.get(position).isAccepted()) comments.get(position).setAccepted(false); else { for (Comment comment : comments) comment.setAccepted(false); comments.get(position).setAccepted(true); } new AcceptTask(comments.get(position).isAccepted()).execute(comments.get(position)); adapter.notifyDataSetChanged(); } }); } else if (!comments.get(position).isAccepted()) accepted.setVisibility(View.GONE); else if (comments.get(position).isAccepted()) { accepted.setVisibility(View.VISIBLE); accepted.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText( context, "This comment was accepted by the postText author as a good answer", Toast.LENGTH_SHORT) .show(); } }); } plusOne.setText("+" + comments.get(position).getPlusOnes()); if (comments.get(position).getPlusOnes() == 0) plusOne.setVisibility(View.GONE); else plusOne.setVisibility(View.VISIBLE); if (comments.get(position).isPlusOned()) plusOne.setTextColor(Color.RED); else plusOne.setTextColor(Color.parseColor("#ff979797")); content.setText( Html.fromHtml( comments.get(position).getContent() + "", new MyImageGetter(content, context), null)); username.setText(comments.get(position).getUsername()); String timeFormatString = "h:mm a"; String editFormatString = "h:mm a"; Date now = new Date(System.currentTimeMillis()); if (comments.get(position).getCommentTime().getDate() != now.getDate()) timeFormatString = "MMM d, yyyy"; if (comments.get(position).getLastEdit() != null && comments.get(position).getLastEdit().getDate() != now.getDate()) editFormatString = "MMM d, yyyy"; String timeString = String.valueOf( android.text.format.DateFormat.format( timeFormatString, comments.get(position).getCommentTime())); if (comments.get(position).getLastEdit() != null) timeString += "(last edit - " + String.valueOf( android.text.format.DateFormat.format( editFormatString, comments.get(position).getLastEdit())) + ")"; time.setText(timeString); Ion.with(profileImage) .placeholder(R.drawable.user_icon) .load( "https://classmeapp.appspot.com/fileRequest?username="******"<a href=\"https://classmeapp.appspot.com/fileRequest?key=" + key + "\">" + name + "</a>")); attachment.setMovementMethod(LinkMovementMethod.getInstance()); attachmentsLayout.addView(attachment); } } v.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { new CommentOptionsDialog(context, comments.get(position), comments, commentList); } }); return v; }
/** * Retrieves a list of maps which will be processed by the passed in callback. * * @param callback passing the data back to caller * @param context used for resource retrieval */ public void getMaps(final FutureCallback<List<Map>> callback, final Context context) { Ion.with(context) .load(context.getResources().getString(R.string.guild_wars_2_api_url) + "map_names.json") .as(new TypeToken<List<Map>>() {}) .setCallback(callback); }
public void doLoadImgur(String url) { final String finalUrl = url; final String finalUrl1 = url; if (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } String hash = url.substring(url.lastIndexOf("/"), url.length()); if (NetworkUtil.isConnected(getActivity())) { if (hash.startsWith("/")) hash = hash.substring(1, hash.length()); LogUtil.v("Loading" + "https://imgur-apiv3.p.mashape.com/3/image/" + hash + ".json"); Ion.with(this) .load("https://imgur-apiv3.p.mashape.com/3/image/" + hash + ".json") .addHeader("X-Mashape-Key", SecretConstants.getImgurApiKey(getActivity())) .addHeader("Authorization", "Client-ID " + "bef87913eb202e9") .asJsonObject() .setCallback( new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject obj) { if (obj != null && !obj.isJsonNull() && obj.has("error")) { LogUtil.v("Error loading content"); (getActivity()).finish(); } else { try { if (obj != null && !obj.isJsonNull() && obj.has("image")) { String type = obj.get("image") .getAsJsonObject() .get("image") .getAsJsonObject() .get("type") .getAsString(); String urls = obj.get("image") .getAsJsonObject() .get("links") .getAsJsonObject() .get("original") .getAsString(); if (type.contains("gif")) { doLoadGif(urls); } else if (!imageShown) { // only load if there is no image doLoadImage(urls); } } else if (obj.has("data")) { String type = obj.get("data").getAsJsonObject().get("type").getAsString(); String urls = obj.get("data").getAsJsonObject().get("link").getAsString(); String mp4 = ""; if (obj.get("data").getAsJsonObject().has("mp4")) { mp4 = obj.get("data").getAsJsonObject().get("mp4").getAsString(); } if (type.contains("gif")) { doLoadGif(((mp4 == null || mp4.isEmpty()) ? urls : mp4)); } else if (!imageShown) { // only load if there is no image doLoadImage(urls); } } else { if (!imageShown) doLoadImage(finalUrl1); } } catch (Exception e2) { e2.printStackTrace(); Intent i = new Intent(getActivity(), Website.class); i.putExtra(Website.EXTRA_URL, finalUrl); getActivity().startActivity(i); } } } }); } }
// refresh the messages that were on the server void refreshMessages() { String account = settings.getString("account", null); if (account == null) return; try { // tokens! Bundle bundle = AccountManager.get(this) .getAuthToken(new Account(account, "com.google"), "grandcentral", true, null, null) .getResult(); String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN); Payload payload = Ion.with(this) .load("https://www.google.com/voice/request/messages") .setHeader("Authorization", "GoogleLogin auth=" + authToken) .as(Payload.class) .get(); ArrayList<Message> all = new ArrayList<Message>(); for (Conversation conversation : payload.conversations) { for (Message message : conversation.messages) all.add(message); } // sort by date order so the events get added in the same order Collections.sort( all, new Comparator<Message>() { @Override public int compare(Message lhs, Message rhs) { if (lhs.date == rhs.date) return 0; if (lhs.date > rhs.date) return 1; return -1; } }); long timestamp = settings.getLong("timestamp", 0); boolean first = timestamp == 0; long max = timestamp; for (Message message : all) { max = Math.max(max, message.date); if (message.phoneNumber == null) continue; if (message.date <= timestamp) continue; if (message.message == null) continue; // on first sync, just populate the mms provider... // don't send any broadcasts. if (first) { int type; if (message.type == VOICE_INCOMING_SMS) type = PROVIDER_INCOMING_SMS; else if (message.type == VOICE_OUTGOING_SMS) type = PROVIDER_OUTGOING_SMS; else continue; // just populate the content provider and go insertMessage(message.phoneNumber, message.message, type, message.date); continue; } // sync up outgoing messages if (message.type == VOICE_OUTGOING_SMS) { boolean found = false; for (String recent : recentSent) { if (TextUtils.equals(recent, message.message)) { recentSent.remove(message.message); found = true; break; } } if (!found) insertMessage( message.phoneNumber, message.message, PROVIDER_OUTGOING_SMS, message.date); continue; } if (message.type != VOICE_INCOMING_SMS) continue; ArrayList<String> list = new ArrayList<String>(); list.add(message.message); try { // synthesize a BROADCAST_SMS event smsTransport.synthesizeMessages(message.phoneNumber, null, list, message.date); } catch (Exception e) { e.printStackTrace(); ; } } settings.edit().putLong("timestamp", max).commit(); } catch (Exception e) { Log.e(LOGTAG, "Error refreshing messages", e); } }
public static Builders.Any.B request(String method, String url) { return Ion.with(MyApplication.getAppContext()).load(method.toUpperCase(), url); }
private void fillVars() { SummonerUtils utils = new SummonerUtils(); ChampionRankedStat stat = summoner .getRankedStat() .getChampions() .get(summoner.getRankedStat().getChampions().size() - 1); // filling WLP rate ImageView icon = (ImageView) fragment.findViewById(R.id.icon); Ion.with(icon) .placeholder(getResources().getDrawable(R.drawable.icon)) .error(getResources().getDrawable(R.drawable.icon)) .load(RIOT.PROFILE_ICONS_URL + summoner.getProfileIconId() + ".png"); Entry entry = summoner.getLeagueStat().getEntries().get(0); String wins = entry.getWins() > 999 ? (entry.getWins() / 1000) + "K" : entry.getWins() + ""; String losses = entry.getLosses() > 999 ? (entry.getLosses() / 1000) + "K" : entry.getLosses() + ""; String played = (entry.getLosses() + entry.getWins()) > 999 ? ((entry.getLosses() + entry.getWins()) / 1000) + "K" : (entry.getLosses() + entry.getWins()) + ""; int rate = (int) utils.getPerformance(stat); ((TextView) fragment.findViewById(R.id.win_points)).setText(wins); ((TextView) fragment.findViewById(R.id.lose_points)).setText(losses); ((TextView) fragment.findViewById(R.id.played_ponts)).setText(played); bar.setProgress(rate); bar.setTitle(rate + "%"); // filling division section String division = summoner.getLeagueStat().getTier() + " " + entry.getDivision(); ((TextView) fragment.findViewById(R.id.division_text)).setText(division); switch (summoner.getLeagueStat().getTier()) { case RIOT.TIER_BRONZE: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_bronze)); break; case RIOT.TIER_SILVER: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_silver)); break; case RIOT.TIER_GOLD: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_gold)); break; case RIOT.TIER_PLATINUM: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_platinum)); break; case RIOT.TIER_DIAMOND: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_diamond)); break; case RIOT.TIER_MASTER: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_master)); break; case RIOT.TIER_CHALLENGER: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_challenger)); break; default: ((ImageView) fragment.findViewById(R.id.tierImage)) .setImageDrawable(getResources().getDrawable(R.drawable.tier_provisional)); } // filling ranked stats section: String minions_game = utils.getMinionsPerGame(entry, stat); ((TextView) fragment.findViewById(R.id.minions)).setText(minions_game); String gold_game = utils.getGoldPerGame(entry, stat); ((TextView) fragment.findViewById(R.id.gold_earned)).setText(gold_game); String turrets = utils.getTurretsPerGame(entry, stat); ((TextView) fragment.findViewById(R.id.turrets)).setText(turrets); ((TextView) fragment.findViewById(R.id.sprees)).setText(stat.getStats().getKillingSpree() + ""); ((TextView) fragment.findViewById(R.id.leaguepoints)) .setText(entry.getLeaguePoints() + " league points"); // filling kda ((TextView) fragment.findViewById(R.id.kills_summoner)).setText(utils.getKills(stat)); ((TextView) fragment.findViewById(R.id.deaths_single_champion)).setText(utils.getDeaths(stat)); ((TextView) fragment.findViewById(R.id.assist_summoner)).setText(utils.getAssists(stat)); ((TextView) fragment.findViewById(R.id.kda_perc)).setText("KDA:" + utils.KDARatio(stat)); }
public static Future<JsonObject> getMeetups(Context context) { return Ion.with(context).load(route).asJsonObject(); }