List of usage examples for android.net Uri toString
public abstract String toString();
From source file:ca.frozen.curlingtv.classes.Utils.java
public static String saveImage(ContentResolver contentResolver, Bitmap source, String title, String description) {/* w w w .j a v a 2 s .c om*/ File snapshot = null; Uri url = null; try { // get/create the snapshots folder File pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File rpi = new File(pictures, App.getStr(R.string.app_name)); if (!rpi.exists()) { rpi.mkdir(); } // save the file within the snapshots folder snapshot = new File(rpi, title); OutputStream stream = new FileOutputStream(snapshot); source.compress(Bitmap.CompressFormat.JPEG, 90, stream); stream.flush(); stream.close(); // create the content values ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, title); values.put(MediaStore.Images.Media.DISPLAY_NAME, title); if (description != null) { values.put(MediaStore.Images.Media.DESCRIPTION, description); } values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis()); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(MediaStore.Images.ImageColumns.BUCKET_ID, snapshot.toString().toLowerCase(Locale.US).hashCode()); values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, snapshot.getName().toLowerCase(Locale.US)); values.put("_data", snapshot.getAbsolutePath()); // insert the image into the database url = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (Exception ex) { return null; } // return the URL return (url != null) ? url.toString() : null; }
From source file:com.logilite.vision.camera.CameraLauncher.java
/** * Applies all needed transformation to the image received from the gallery. * * @param destType In which form should we return the image * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). *///from w w w .ja va 2 s .com private void processResultFromGallery(int destType, Intent intent) { Uri uri = intent.getData(); int rotate = 0; // If you ask for video or all media type you will automatically get back a file URI // and there will be no attempt to resize any returned data if (this.mediaType != PICTURE) { this.callbackContext.success(uri.toString()); } else { // This is a special case to just return the path as no scaling, // rotating, nor compressing needs to be done if (this.targetHeight == -1 && this.targetWidth == -1 && (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) { this.callbackContext.success(uri.toString()); } else { String uriString = uri.toString(); // Get the path to the image. Makes loading so much easier. String mimeType = FileHelper.getMimeType(uriString, this.cordova); // If we don't have a valid image so quit. Bitmap bitmap = null; try { bitmap = getScaledBitmap(uriString); } catch (IOException e) { e.printStackTrace(); } if (bitmap == null) { Log.d(LOG_TAG, "I either have a null image path or bitmap"); this.failPicture("Unable to create bitmap!"); return; } if (this.correctOrientation) { rotate = getImageOrientation(uri); if (rotate != 0) { Matrix matrix = new Matrix(); matrix.setRotate(rotate); try { bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); this.orientationCorrected = true; } catch (OutOfMemoryError oom) { this.orientationCorrected = false; } } } // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); } // If sending filename back else if (destType == FILE_URI || destType == NATIVE_URI) { // Did we modify the image? if ((this.targetHeight > 0 && this.targetWidth > 0) || (this.correctOrientation && this.orientationCorrected)) { try { String modifiedPath = this.ouputModifiedBitmap(bitmap, uri); // The modified image is cached by the app in order to get around this and not have to delete you // application cache I'm adding the current system time to the end of the file url. this.callbackContext .success("file://" + modifiedPath + "?" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } else { this.callbackContext.success(uri.toString()); } } if (bitmap != null) { bitmap.recycle(); bitmap = null; } System.gc(); } } }
From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java
public JSONObject searchCityImage(String woeid) throws VolleyError { Uri uri = Uri.parse("https://api.flickr.com/services/rest/").buildUpon() .appendQueryParameter("method", "flickr.photos.search") .appendQueryParameter("api_key", FLICKR_API_KEY).appendQueryParameter("sort", "relevance") .appendQueryParameter("tag_mode", "all").appendQueryParameter("privacy_filter", "1") .appendQueryParameter("content_type", "1").appendQueryParameter("group_id", "1463451@N25") .appendQueryParameter("woe_id", woeid).appendQueryParameter("media", "photos") .appendQueryParameter("extras", extras).appendQueryParameter("format", "json") .appendQueryParameter("nojsoncallback", "1").build(); String url = uri.toString(); RequestFuture<JSONObject> requestFuture = RequestFuture.newFuture(); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, requestFuture, requestFuture); sRequestQueue.add(request);// w w w.ja v a 2 s . c o m return getResult(requestFuture); }
From source file:edu.mit.mobile.android.locast.data.MediaSync.java
public void onScanCompleted(String path, Uri locMediaUri) { if (locMediaUri == null) { Log.e(TAG, "Scan failed for newly downloaded content: " + path); return;//from w ww .j ava 2 s . co m } final ScanQueueItem item = scanMap.get(path); if (item == null) { Log.e(TAG, "Couldn't find media item (" + path + ") in scan map, so we couldn't update any casts."); return; } updateCastMediaLocalUri(item.castMediaUri, locMediaUri.toString(), item.contentType); }
From source file:com.cordova.photo.CameraLauncher.java
/** * Cleans up after picture taking. Checking for duplicates and that kind of stuff. * @param newImage//from ww w .j av a 2 s . c o m */ private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) { if (bitmap != null) { bitmap.recycle(); } // Clean up initial camera-written image file. (new File(FileHelper.stripFileProtocol(oldImage.toString()))).delete(); checkForDuplicateImage(imageType); // Scan for the gallery to update pic refs in gallery if (this.saveToPhotoAlbum && newImage != null) { this.scanForGallery(newImage); } System.gc(); }
From source file:com.ccxt.whl.activity.SettingsFragmentCopy.java
/** * ?//w w w .j av a2s .co m * @param uri * @param outputX * @param outputY * @param requestCode */ private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) { /*if(getpathfromUri(uri)!=null&&getpathfromUri(imageUri)!=null){ copyFile(getpathfromUri(uri),getpathfromUri(imageUri)); }else{ return; }*/ Log.d("log", uri.toString()); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); //aspectX aspectY intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY ? intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.putExtra("return-data", false); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, requestCode); }
From source file:com.tealeaf.TeaLeaf.java
private void getLaunchType(Intent intent) { Uri data = intent.getData(); LaunchTypeEvent event;/*from www . j av a 2s.c om*/ //launch type "notification" has been taken out if (data != null) { logger.log("{tealeaf} Launched with intent url:", data.toString()); event = new LaunchTypeEvent("url", data.toString()); } else { event = new LaunchTypeEvent("standard"); } EventQueue.pushEvent(event); }
From source file:co.uk.socialticker.ticker.TickerActivity.java
private void onCreateTwitter() { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);//ww w . java2s . c om cd = new ConnectionDetector(getApplicationContext()); // Check if Internet present if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog(TickerActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Check if twitter keys are set if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) { // Internet Connection is not present alert.showAlertDialog(TickerActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // All UI elements btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter); btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus); btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter); txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus); lblUpdate = (TextView) findViewById(R.id.lblUpdate); llTwitter = (LinearLayout) findViewById(R.id.llTwitter); llCast = (LinearLayout) findViewById(R.id.llCast); /** * Twitter login button click event will call loginToTwitter() function * */ btnLoginTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call login twitter function loginToTwitter(); } }); /** * Button click event to Update Status, will call updateTwitterStatus() * function * */ btnUpdateStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Call update status function // Get the status from EditText String status = txtUpdate.getText().toString(); // Check for blank text if (status.trim().length() > 0) { // update status new updateTwitterStatus().execute(status); } else { // EditText is empty Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT) .show(); } } }); /** * Button click event for logout from twitter * */ btnLogoutTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function logoutFromTwitter(); } }); /** This if conditions is tested once is * redirected from twitter page. Parse the uri to get oAuth * Verifier * */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // Shared Preferences Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); // Hide login button btnLoginTwitter.setVisibility(View.GONE); // Show Update Twitter lblUpdate.setVisibility(View.VISIBLE); txtUpdate.setVisibility(View.VISIBLE); btnUpdateStatus.setVisibility(View.VISIBLE); btnLogoutTwitter.setVisibility(View.VISIBLE); // Getting user details from twitter // For now i am getting his name only long userID = accessToken.getUserId(); User user = twitter.showUser(userID); } catch (Exception e) { // Check log for login errors Log.e("Twitter Login Error", "> " + e.getMessage()); } } } }
From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java
public void startSocketConnection() { final OnlineControllerFragment self = this; final GlobalUtils globalUtils = this.getGlobalUtils(); if (this.socket != null && this.socket.connected()) { return;/* ww w .j a v a 2 s . c o m*/ } this.progressDialog.show(); this.progressDialog.setText(R.string.connecting_socket_server); String url = this.getPreferencesEditor().getString("preference_server_address", this.getString(R.string.preference_value_address)); Uri uri = Uri.parse(url).buildUpon().appendQueryParameter("token", this.token).build(); try { if (url.contains("https://")) { IO.setDefaultSSLContext(SSLContext.getDefault()); } IO.Options options = new IO.Options(); options.forceNew = true; options.reconnection = true; this.socket = IO.socket(uri.toString(), options); /* * When the socket is connected. */ socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { @Override public void call(Object... args) { self.removeAllClients(); self.progressDialog.dismiss(); } /* * When the socket is disconnected. */ }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { @Override public void call(Object... args) { self.removeAllClients(); } /* * When the socket receives an error. */ }).on(Socket.EVENT_ERROR, new Emitter.Listener() { @Override public void call(Object... args) { try { String error = (String) args[0]; if (error.contains("JsonWebToken") || error.contains("TokenExpiredError")) { self.getBaseActivity().getPreferencesEditor().saveString("preference_server_token", ""); globalUtils.showToast(R.string.restoring_token); self.refreshFragment(); return; } } catch (ClassCastException e) { //e.printStackTrace(); } self.progressDialog.dismiss(); globalUtils.showToast(R.string.unknown_error); } /* * When a new client is disconnected. */ }).on("leave_member", new Emitter.Listener() { @Override public void call(Object... args) { try { JSONObject members = ((JSONObject) args[0]).getJSONObject("members"); Iterator<String> membersList = members.keys(); while (membersList.hasNext()) { String id = membersList.next(); Client client = Client.fromJSON(members.getJSONObject(id)); client.setId(id); final int index = self.clientsAdapter.exists(client); if (index == -1) { continue; } if (self.calling != null && self.calling.equals(self.clientsAdapter.get(index).getPeerId())) { self.hideActions(); self.calling = ""; self.controlledBy = null; self.getConnector().motorBC(0, 0, false, false); } self.getActivity().runOnUiThread(new Runnable() { @Override public void run() { self.clientsAdapter.remove(index); } }); } } catch (JSONException e) { //e.printStackTrace(); } } /* * When a new client is connected (also fired on first connection with all the active clients) */ }).on("join_member", new Emitter.Listener() { @Override public void call(Object... args) { try { JSONObject members = ((JSONObject) args[0]).getJSONObject("members"); Iterator<String> membersList = members.keys(); while (membersList.hasNext()) { String id = membersList.next(); JSONObject member = members.getJSONObject(id); final Client client = Client.fromJSON(member); client.setId(id); if (self.clientsAdapter.exists(client) > -1) { continue; } self.getActivity().runOnUiThread(new Runnable() { @Override public void run() { self.clientsAdapter.add(client); } }); } } catch (JSONException e) { e.printStackTrace(); } } /* * When the client has answered our call request. */ }).on("answered", new Emitter.Listener() { @Override public void call(Object... args) { self.progressDialog.dismiss(); try { JSONObject data = (JSONObject) args[0]; String from = data.getString("from"); boolean accepted = data.getBoolean("state"); if (from.equals(self.calling)) { globalUtils.showToast(accepted ? R.string.call_accepted : R.string.call_rejected); if (accepted) { self.controlledBy = self.clientsAdapter.getByPeer(from); self.showActions(); } } } catch (JSONException e) { //e.printStackTrace(); } } /* * When the client sends us a motor order. */ }).on("motors", new Emitter.Listener() { @Override public void call(Object... args) { try { JSONObject data = (JSONObject) args[0]; String sender = data.getString("from"); if (!sender.equals(self.controlledBy.getPeerId())) return; double b = data.getDouble("b"); double c = data.getDouble("c"); self.getConnector().motorBC(c, b, false, false); } catch (JSONException e) { //e.printStackTrace(); } } });/*.on("flash", new Emitter.Listener() { @Override public void call (Object... args) { try { JSONObject data = (JSONObject) args[0]; String sender = data.getString("from"); boolean state = data.getBoolean("state"); if (!sender.equals(self.controlledBy.getPeerId())) return; if (!globalUtils.isFlashAvailable()) return; Camera camera = Camera.open(); Camera.Parameters parameters = camera.getParameters(); parameters.setFlashMode(state ? Camera.Parameters.FLASH_MODE_ON : Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(parameters); camera.startPreview(); } catch (JSONException e) { e.printStackTrace(); } } });*/ socket.connect(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // We are fucked if this ends here! } }
From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java
protected int putAttaches() { int total = 0; PhotoGallery gallery = (PhotoGallery) findViewById(R.id.pg_photos); if (gallery != null && mFeatureId != NOT_FOUND) { List<Integer> deletedAttaches = gallery.getDeletedAttaches(); IGISApplication application = (IGISApplication) getApplication(); Uri uri = Uri.parse("content://" + application.getAuthority() + "/" + mLayer.getPath().getName() + "/" + mFeatureId + "/" + Constants.URI_ATTACH); int size = deletedAttaches.size(); String[] args = new String[size]; for (int i = 0; i < size; i++) args[i] = deletedAttaches.get(i).toString(); if (size > 0) total += getContentResolver().delete(uri, MapUtil.makePlaceholders(size), args); if (total == 0 && size > 0) { Toast.makeText(this, getText(R.string.photo_fail_attach), Toast.LENGTH_SHORT).show(); Log.d(TAG, "attach delete failed"); } else {//from ww w.j av a2s.c om Log.d(TAG, "attach delete success: " + total); } List<String> imagesPath = gallery.getNewAttaches(); for (String path : imagesPath) { String[] segments = path.split("/"); String name = segments.length > 0 ? segments[segments.length - 1] : "image.jpg"; ContentValues values = new ContentValues(); values.put(VectorLayer.ATTACH_DISPLAY_NAME, name); values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg"); Uri result = getContentResolver().insert(uri, values); if (result == null) { Toast.makeText(this, getText(R.string.photo_fail_attach), Toast.LENGTH_SHORT).show(); Log.d(TAG, "attach insert failed"); } else { if (copyToStream(result, path)) total++; Log.d(TAG, "attach insert success: " + result.toString()); } } } return total; }