List of usage examples for android.net Uri.Builder toString
public abstract String toString();
From source file:org.lol.reddit.reddit.api.RedditAPIIndividualSubredditListRequester.java
private void doSubredditListRequest(final RedditSubredditManager.SubredditListType type, final RequestResponseHandler<WritableHashSet, SubredditRequestFailure> handler, final String after) { URI uri;/* w w w .j av a 2 s . c o m*/ switch (type) { case SUBSCRIBED: uri = Constants.Reddit.getUri(Constants.Reddit.PATH_SUBREDDITS_MINE_SUBSCRIBER); break; case MODERATED: uri = Constants.Reddit.getUri(Constants.Reddit.PATH_SUBREDDITS_MINE_MODERATOR); break; case MOST_POPULAR: uri = Constants.Reddit.getUri(Constants.Reddit.PATH_SUBREDDITS_POPULAR); break; default: throw new UnexpectedInternalStateException(type.name()); } if (after != null) { // TODO move this logic to General? final Uri.Builder builder = Uri.parse(uri.toString()).buildUpon(); builder.appendQueryParameter("after", after); uri = General.uriFromString(builder.toString()); } final CacheRequest aboutSubredditCacheRequest = new CacheRequest(uri, user, null, Constants.Priority.API_SUBREDDIT_INVIDIVUAL, 0, CacheRequest.DownloadType.FORCE, Constants.FileType.SUBREDDIT_LIST, true, true, false, context) { @Override protected void onCallbackException(Throwable t) { handler.onRequestFailed( new SubredditRequestFailure(RequestFailureType.PARSE, t, null, "Internal error", url)); } @Override protected void onDownloadNecessary() { } @Override protected void onDownloadStarted() { } @Override protected void onProgress(long bytesRead, long totalBytes) { } @Override protected void onFailure(RequestFailureType type, Throwable t, StatusLine status, String readableMessage) { handler.onRequestFailed( new SubredditRequestFailure(type, t, status, readableMessage, url.toString())); } @Override protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp, UUID session, boolean fromCache, String mimetype) { } @Override public void onJsonParseStarted(JsonValue result, long timestamp, UUID session, boolean fromCache) { try { final HashSet<String> output = new HashSet<String>(); final ArrayList<RedditSubreddit> toWrite = new ArrayList<RedditSubreddit>(); final JsonBufferedObject redditListing = result.asObject().getObject("data"); final JsonBufferedArray subreddits = redditListing.getArray("children"); final JsonBuffered.Status joinStatus = subreddits.join(); if (joinStatus == JsonBuffered.Status.FAILED) { handler.onRequestFailed(new SubredditRequestFailure(RequestFailureType.PARSE, null, null, "Unknown parse error", url.toString())); return; } if (type == RedditSubredditManager.SubredditListType.SUBSCRIBED && subreddits.getCurrentItemCount() == 0 && after == null) { doSubredditListRequest(RedditSubredditManager.SubredditListType.MOST_POPULAR, handler, null); return; } for (final JsonValue v : subreddits) { final RedditThing thing = v.asObject(RedditThing.class); final RedditSubreddit subreddit = thing.asSubreddit(); subreddit.downloadTime = timestamp; toWrite.add(subreddit); output.add(subreddit.getCanonicalName()); } RedditSubredditManager.getInstance(context, user).offerRawSubredditData(toWrite, timestamp); final String receivedAfter = redditListing.getString("after"); if (receivedAfter != null && type != RedditSubredditManager.SubredditListType.MOST_POPULAR) { doSubredditListRequest(type, new RequestResponseHandler<WritableHashSet, SubredditRequestFailure>() { public void onRequestFailed(SubredditRequestFailure failureReason) { handler.onRequestFailed(failureReason); } public void onRequestSuccess(WritableHashSet result, long timeCached) { output.addAll(result.toHashset()); handler.onRequestSuccess( new WritableHashSet(output, timeCached, type.name()), timeCached); if (after == null) { Log.i("SubredditListRequester", "Got " + output.size() + " subreddits in multiple requests"); } } }, receivedAfter); } else { handler.onRequestSuccess(new WritableHashSet(output, timestamp, type.name()), timestamp); if (after == null) { Log.i("SubredditListRequester", "Got " + output.size() + " subreddits in 1 request"); } } } catch (Exception e) { handler.onRequestFailed(new SubredditRequestFailure(RequestFailureType.PARSE, e, null, "Parse error", url.toString())); } } }; CacheManager.getInstance(context).makeRequest(aboutSubredditCacheRequest); }
From source file:com.cleanwiz.applock.service.AppUpdateService.java
public void checkVersion() { requestQueue = Volley.newRequestQueue(context); String url = "http://www.toolwiz.com/android/checkfiles.php"; final String oldVersionString = getApplicationVersion(); Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("uid", AndroidUtil.getUdid(context)); builder.appendQueryParameter("version", oldVersionString); builder.appendQueryParameter("action", "checkfile"); builder.appendQueryParameter("app", "locklocker"); jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @Override/*from w w w .ja v a2 s . c om*/ public void onResponse(JSONObject arg0) { // TODO Auto-generated method stub LogUtil.e("colin", "success"); if (arg0.has("status")) { try { String status = arg0.getString("status"); if (Integer.valueOf(status) == 1) { JSONObject msgJsonObject = arg0.getJSONObject("msg"); double version = msgJsonObject.getDouble("version"); if (Double.valueOf(oldVersionString) < version) { // ??? String intro = msgJsonObject.getString("intro"); AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle("?").setMessage(intro) .setPositiveButton("", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // ?? } }) .setNegativeButton("?", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.create().show(); } } else { LogUtil.e("colin", "check update status is error"); } } catch (JSONException e) { // TODO Auto-generated catch block LogUtil.e("colin", "JSONException" + e.getMessage()); e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { // TODO Auto-generated method stub } }); requestQueue.add(jsonObjectRequest); }
From source file:com.udacity.movietimes.adapter.MovieDetailAdapter.java
@Override public void bindView(View view, final Context context, final Cursor cursor) { int viewType = getItemViewType(cursor.getPosition()); switch (viewType) { case VIEW_TYPE_MOVIE_BODY: { final MovieViewHolder viewHolder = (MovieViewHolder) view.getTag(); // Set the poster of the movie StringBuilder imagePath = new StringBuilder(MovieUrl.MOVIE_IMAGE_BASE_URL) .append(cursor.getString(COL_POSTER)); Picasso.with(context).load(imagePath.toString()).into(viewHolder.poster, new Callback.EmptyCallback() { @Override/* ww w . j a va 2 s. c om*/ public void onError() { viewHolder.poster.setImageResource(R.drawable.no_poster); } }); // Set the title of the movie viewHolder.title.setText(cursor.getString(COL_TITLE)); // Set the favorite button ON/OFF updateFavoriteButton(viewHolder, context, cursor); // Set the Release date of the movie String date = MovieUtility.formatDate(cursor.getString(COL_RELEASE_DATE)); if (date != null) { viewHolder.releaseDate.setText(date); } // Set the Rating of the Movie viewHolder.rating.setRating((float) (Float.valueOf(cursor.getString(COL_RATING)) / 2.0)); // Set the Overview of the Movie viewHolder.overview.setText(cursor.getString(COL_OVERVIEW)); break; } case VIEW_TYPE_MOVIE_REVIEW: { ReviewVeiwHolder viewHolder = (ReviewVeiwHolder) view.getTag(); viewHolder.author.setText(cursor.getString(COL_AUTHOR_NAME)); viewHolder.review.setText(cursor.getString(COL_REVIEW_CONTENT)); break; } case VIEW_TYPE_MOVIE_TRAILER: { final TrailerVeiwHolder viewHolder = (TrailerVeiwHolder) view.getTag(); // Set the Trailer Image final String trailerKey = cursor.getString(COL_TRAILER_KEY); Uri.Builder mVedioUrl = Uri.parse(MovieUrl.MOVIE_VEDIO_BASE_URL).buildUpon().appendPath(trailerKey) .appendPath(MovieUrl.VEDIO_TN_SIZE); Picasso.with(mContext).load(mVedioUrl.toString()).into(viewHolder.trailerPic, new Callback.EmptyCallback() { @Override public void onSuccess() { viewHolder.trailerPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Intent intent = YouTubeStandalonePlayer.createVideoIntent(activity, MovieConfig.GOOGLE_API_KEY, trailerKey); context.startActivity(intent); } catch (ActivityNotFoundException e) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + trailerKey)); context.startActivity(intent); } } }); } @Override public void onError() { super.onError(); viewHolder.trailerMsg.setText(R.string.noTrailer); } }); break; } } }
From source file:com.ryan.ryanreader.fragments.PostListingFragment.java
private synchronized void onLoadMoreItemsCheck() { if (readyToDownloadMore && after != null && !after.equals(lastAfter) && adapter.getDownloadedCount() > 0 && adapter.getDownloadedCount() - lv.getLastVisiblePosition() < 20) { lastAfter = after;//from w w w . ja v a 2 s. c o m readyToDownloadMore = false; final Uri.Builder uriBuilder = Uri.parse(url.toString()).buildUpon(); uriBuilder.appendQueryParameter("after", after); final URI newUri = General.uriFromString(uriBuilder.toString()); // TODO customise (currently 3 hrs) CacheRequest.DownloadType type = (RRTime.since(timestamp) < 3 * 60 * 60 * 1000) ? CacheRequest.DownloadType.IF_NECESSARY : CacheRequest.DownloadType.NEVER; request = new PostListingRequest(newUri, RedditAccountManager.getInstance(getSupportActivity()).getDefaultAccount(), session, type, false); CacheManager.getInstance(getSupportActivity()).makeRequest(request); } }
From source file:com.michael.openexercise.mc_network.volleydemo.JSONObjectRequestActvity.java
private void makeSampleHttpRequest() { String url = "https://api.flickr.com/services/rest"; Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("api_key", "75ee6c644cad38dc8e53d3598c8e6b6c"); builder.appendQueryParameter("method", "flickr.interestingness.getList"); builder.appendQueryParameter("format", "json"); builder.appendQueryParameter("nojsoncallback", "1"); jsonObjRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @Override// www. ja v a 2 s . co m public void onResponse(JSONObject response) { try { parseFlickrImageResponse(response); mAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); showToast("JSON parse error"); } stopProgress(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button. // For AuthFailure, you can re login with user credentials. // For ClientError, 400 & 401, Errors happening on client side when sending api request. // In this case you can check how client is forming the api and debug accordingly. // For ServerError 5xx, you can do retry or handle accordingly. if (error instanceof NetworkError) { } else if (error instanceof ClientError) { } else if (error instanceof ServerError) { } else if (error instanceof AuthFailureError) { } else if (error instanceof ParseError) { } else if (error instanceof NoConnectionError) { } else if (error instanceof TimeoutError) { } stopProgress(); showToast(error.getMessage()); } }); //Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. Volley does retry for you if you have specified the policy. jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); jsonObjRequest.setTag(TAG_REQUEST); mVolleyQueue.add(jsonObjRequest); }
From source file:com.mani.volleydemo.JSONObjectRequestActvity.java
private void makeSampleHttpRequest() { String url = "http://api.flickr.com/services/rest"; Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("api_key", "5e045abd4baba4bbcd866e1864ca9d7b"); builder.appendQueryParameter("method", "flickr.interestingness.getList"); builder.appendQueryParameter("format", "json"); builder.appendQueryParameter("nojsoncallback", "1"); jsonObjRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @Override//www . java 2 s .c o m public void onResponse(JSONObject response) { try { parseFlickrImageResponse(response); mAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); showToast("JSON parse error"); } stopProgress(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button. // For AuthFailure, you can re login with user credentials. // For ClientError, 400 & 401, Errors happening on client side when sending api request. // In this case you can check how client is forming the api and debug accordingly. // For ServerError 5xx, you can do retry or handle accordingly. if (error instanceof NetworkError) { } else if (error instanceof ClientError) { } else if (error instanceof ServerError) { } else if (error instanceof AuthFailureError) { } else if (error instanceof ParseError) { } else if (error instanceof NoConnectionError) { } else if (error instanceof TimeoutError) { } stopProgress(); showToast(error.getMessage()); } }); //Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. Volley does retry for you if you have specified the policy. jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); jsonObjRequest.setTag(TAG_REQUEST); mVolleyQueue.add(jsonObjRequest); }
From source file:com.michael.openexercise.mc_network.volleydemo.NetworkImageActivity.java
private void makeSampleHttpRequest() { String url = "https://api.flickr.com/services/rest"; Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("api_key", "5e045abd4baba4bbcd866e1864ca9d7b"); builder.appendQueryParameter("method", "flickr.interestingness.getList"); builder.appendQueryParameter("format", "json"); builder.appendQueryParameter("nojsoncallback", "1"); jsonObjRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @Override/*from w ww . j a va 2 s . co m*/ public void onResponse(JSONObject response) { System.out.println( "####### Response JsonObjectRequest SUCCESS ######## " + response.toString()); try { parseFlickrImageResponse(response); mAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); showToast("JSON parse error"); } stopProgress(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { stopProgress(); System.out.println("####### onErrorResponse ########## " + error.getMessage()); showToast(error.getMessage()); } }); jsonObjRequest.setTag(TAG_REQUEST); mVolleyQueue.add(jsonObjRequest); }
From source file:org.LinuxdistroCommunity.android.client.PostEntry.java
/** * Fire the task to post the media entry. The media information is encoded * in Bundles. Each Bundle MUST contain the KEY_FILE_PATH pointing to the * resource. Bundles MAY contain KEY_TITLE and KEY_DESCRIPTION for passing * additional metadata.//from w w w. j a v a 2 s.c om * */ @Override protected JSONObject doInBackground(Bundle... mediaInfoBundles) { Bundle mediaInfo = mediaInfoBundles[0]; HttpURLConnection connection = null; Uri.Builder uri_builder = Uri.parse(mServer + API_BASE + API_POST_ENTRY).buildUpon(); uri_builder.appendQueryParameter(PARAM_ACCESS_TOKEN, mToken); String charset = "UTF-8"; File binaryFile = new File(mediaInfo.getString(KEY_FILE_PATH)); // Semi-random value to act as the boundary String boundary = Long.toHexString(System.currentTimeMillis()); String CRLF = "\r\n"; // Line separator required by multipart/form-data. PrintWriter writer = null; try { URL url = new URL(uri_builder.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important! // Send metadata if (mediaInfo.containsKey(KEY_TITLE)) { writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"title\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF); writer.append(mediaInfo.getString(KEY_TITLE)).append(CRLF).flush(); } if (mediaInfo.containsKey(KEY_DESCRIPTION)) { writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"description\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF); writer.append(mediaInfo.getString(KEY_DESCRIPTION)).append(CRLF).flush(); } // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append( "Content-Disposition: form-data; name=\"file\"; filename=\"" + binaryFile.getName() + "\"") .append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); InputStream input = null; try { input = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } output.flush(); // Important! Output cannot be closed. Close of // writer will close output as well. } finally { if (input != null) try { input.close(); } catch (IOException logOrIgnore) { } } writer.append(CRLF).flush(); // CRLF is important! It indicates end // of binary boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF); writer.close(); // read the response int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Log.d(TAG, Integer.toString(serverResponseCode)); Log.d(TAG, serverResponseMessage); InputStream is = connection.getInputStream(); // parse token_response as JSON to get the token out String str_response = NetworkUtilities.readStreamToString(is); Log.d(TAG, str_response); JSONObject response = new JSONObject(str_response); return response; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // if (writer != null) writer.close(); } return null; }
From source file:com.mani.volleydemo.NetworkImageActivity.java
private void makeSampleHttpRequest() { String url = "http://api.flickr.com/services/rest"; Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("api_key", "5e045abd4baba4bbcd866e1864ca9d7b"); builder.appendQueryParameter("method", "flickr.interestingness.getList"); builder.appendQueryParameter("format", "json"); builder.appendQueryParameter("nojsoncallback", "1"); jsonObjRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @Override/* w w w . j a v a 2s. c o m*/ public void onResponse(JSONObject response) { System.out.println( "####### Response JsonObjectRequest SUCCESS ######## " + response.toString()); try { parseFlickrImageResponse(response); mAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); showToast("JSON parse error"); } stopProgress(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { stopProgress(); System.out.println("####### onErrorResponse ########## " + error.getMessage()); showToast(error.getMessage()); } }); jsonObjRequest.setTag(TAG_REQUEST); mVolleyQueue.add(jsonObjRequest); }
From source file:com.cleanwiz.applock.ui.activity.SplashActivity.java
public void checkVersion() { requestQueue = Volley.newRequestQueue(this); String url = "http://www.toolwiz.com/android/checkfiles.php"; final String oldVersionString = getApplicationVersion(); Locale locale = getResources().getConfiguration().locale; String language = locale.getLanguage(); Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("uid", AndroidUtil.getUdid(this)); builder.appendQueryParameter("version", oldVersionString); builder.appendQueryParameter("action", "checkfile"); builder.appendQueryParameter("app", "locklocker"); builder.appendQueryParameter("language", language); jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @SuppressLint("NewApi") @Override/*from w ww .j ava 2 s . c o m*/ public void onResponse(JSONObject arg0) { // TODO Auto-generated method stub LogUtil.e("colin", "success"); if (arg0.has("status")) { try { String status = arg0.getString("status"); if (Integer.valueOf(status) == 1) { JSONObject msgJsonObject = arg0.getJSONObject("msg"); double version = msgJsonObject.getDouble("version"); downLoadFileUrl = msgJsonObject.getString("url"); fileSize = msgJsonObject.getString("size"); if (Double.valueOf(oldVersionString) < version && !downLoadFileUrl.isEmpty()) { // ??? String intro = msgJsonObject.getString("intro"); LogUtil.e("colin", "........" + intro); showUpdateDialog(intro); } else { LogUtil.e("colin", "check update status is same not to update"); SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); } } else { LogUtil.e("colin", "check update status is error"); SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); } } catch (JSONException e) { // TODO Auto-generated catch block SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { // TODO Auto-generated method stub SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); } }); requestQueue.add(jsonObjectRequest); }