Example usage for android.net Uri getScheme

List of usage examples for android.net Uri getScheme

Introduction

In this page you can find the example usage for android.net Uri getScheme.

Prototype

@Nullable
public abstract String getScheme();

Source Link

Document

Gets the scheme of this URI.

Usage

From source file:com.mifos.mifosxdroid.dialogfragments.DocumentDialogFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case FILE_SELECT_CODE:
        if (resultCode == Activity.RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();

            Log.d(LOG_TAG, "File Uri: " + uri.toString());
            // Get the path
            try {

                String scheme = uri.getScheme();

                if (scheme.equals("file")) {
                    filePath = FileUtils.getPath(getActivity(), uri);
                    fileChoosen = new File(filePath);
                    Log.d(LOG_TAG, "File Path: " + filePath);
                } else if (scheme.equals("content")) {

                    Toast.makeText(getActivity(),
                            "The application currently does not "
                                    + "support file picking from apps other than File " + "Managers.",
                            Toast.LENGTH_SHORT).show();
                    resultCode = Activity.RESULT_CANCELED;
                }/*from  ww w  .j  ava 2  s  .  c  o m*/

                if (fileChoosen != null) {
                    tv_choose_file.setText(fileChoosen.getName());
                } else {
                    break;
                }
                bt_upload.setEnabled(true);

            } catch (URISyntaxException e) {
                Log.d(LOG_TAG, e.getMessage());
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.cbtec.eliademy.EliademyLms.java

/**
 * Called when an activity you launched exits, giving you the requestCode
 * you started it with, the resultCode it returned, and any additional data
 * from it./* ww w.  j  av  a 2 s  .co m*/
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param data
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch (requestCode) {
    case submitFileCode:
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();
            if (uri.getScheme().toString().compareTo("content") == 0) {
                Cursor cursor = cordova.getActivity().getApplicationContext().getContentResolver().query(uri,
                        null, null, null, null);
                if (cursor.moveToFirst()) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
                    uri = Uri.parse(cursor.getString(column_index));
                }
            }
            if (this.mCallbackContext != null) {
                this.mCallbackContext.success(uri.toString());
                return;
            } else {
                Log.i("HLMS", "callback context is null");
            }
        }
        break;
    }
    if (this.mCallbackContext != null) {
        this.mCallbackContext.error(resultCode);
    } else {
        Log.i("HLMS", "callback context is null");
    }
}

From source file:com.deliciousdroid.fragment.MainSearchResultsFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    base = (FragmentBaseActivity) getActivity();
    base.setTitle(R.string.main_search_results_title);

    String[] MENU_ITEMS = new String[] { getString(R.string.search_results_bookmark),
            getString(R.string.search_results_tag), getString(R.string.search_results_global_tag) };

    setListAdapter(new ArrayAdapter<String>(base, R.layout.main_view, MENU_ITEMS));

    final Intent intent = base.getIntent();

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        if (intent.hasExtra(SearchManager.QUERY)) {
            Intent i = new Intent(base, MainSearchResultsFragment.class);
            i.putExtras(intent.getExtras());
            startActivity(i);//from w w w.  j a va 2 s  .  c o m
            base.finish();
        } else {
            base.onSearchRequested();
        }
    } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {

        Uri data = intent.getData();
        String path = null;
        String tagname = null;

        if (data != null) {
            path = data.getPath();
            tagname = data.getQueryParameter("tagname");
        }

        if (data.getScheme() == null || !data.getScheme().equals("content")) {
            Intent i = new Intent(Intent.ACTION_VIEW, data);

            startActivity(i);
            base.finish();
        } else if (path.contains("bookmarks") && TextUtils.isDigitsOnly(data.getLastPathSegment())) {
            Intent viewBookmark = new Intent(base, ViewBookmark.class);
            viewBookmark.setData(data);

            Log.d("View Bookmark Uri", data.toString());
            startActivity(viewBookmark);
            base.finish();
        } else if (tagname != null) {
            Intent viewTags = new Intent(base, BrowseBookmarks.class);
            viewTags.setData(data);

            Log.d("View Tags Uri", data.toString());
            startActivity(viewTags);
            base.finish();
        }
    }

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0) {
                searchActionListener.onBookmarkSearch();
            } else if (position == 1) {
                searchActionListener.onTagSearch();
            } else if (position == 2) {
                searchActionListener.onGlobalTagSearch();
            }
        }
    });
}

From source file:info.guardianproject.otr.app.im.app.AddContactActivity.java

/**
 * Implement {@code xmpp:} URI parsing according to the RFC: http://tools.ietf.org/html/rfc5122
 * @param uri the URI to be parsed//ww  w.  j av  a  2  s . c  om
 */
private void addContactFromUri(Uri uri) {
    Log.i(TAG, "addContactFromUri: " + uri + "  scheme: " + uri.getScheme());
    Map<String, String> parsedUri = XmppUriHelper.parse(uri);
    if (!parsedUri.containsKey(XmppUriHelper.KEY_ADDRESS)) {
        Toast.makeText(this, "error parsing address: " + uri, Toast.LENGTH_LONG).show();
        return;
    }
    String address = parsedUri.get(XmppUriHelper.KEY_ADDRESS);
    this.mAddressList.setText(address);
    this.mInviteButton.setBackgroundColor(R.drawable.btn_green);

    //store this for future use... ideally the user comes up as verified the first time!
    String fingerprint = parsedUri.get(XmppUriHelper.KEY_OTR_FINGERPRINT);
    if (!TextUtils.isEmpty(fingerprint)) {
        Log.i(TAG, "fingerprint: " + fingerprint);
        OtrAndroidKeyManagerImpl.getInstance(this).verifyUser(address, fingerprint);
    }
}

From source file:com.danjarvis.documentcontract.DocumentContract.java

/**
 * Creates a new file from the data resolved through the provided content URI.
 *
 * @return name of created file (residing at cordova.file.dataDirectory).
 *//*w w w . j  a  va 2s.  c  om*/
private void createFile(JSONObject args, CallbackContext callback) {
    try {
        Uri uri;
        String fileName;
        ContentResolver contentResolver;
        InputStream is;
        FileOutputStream fs;
        byte[] buffer;
        int read = 0;

        uri = getUri(args);
        if (null == uri || !(uri.getScheme().equals(ContentResolver.SCHEME_CONTENT))) {
            callback.error(INVALID_URI_ERROR);
            return;
        }

        fileName = getFileName(args);
        if (null == fileName) {
            callback.error(INVALID_PARAMS_ERROR);
            return;
        }

        contentResolver = cordova.getActivity().getContentResolver();
        if (null == contentResolver) {
            callback.error("Failed to get ContentResolver object.");
            return;
        }

        is = contentResolver.openInputStream(uri);
        fs = cordova.getActivity().openFileOutput(fileName, Context.MODE_PRIVATE);

        buffer = new byte[32768];
        while ((read = is.read(buffer, 0, buffer.length)) != -1) {
            fs.write(buffer, 0, read);
        }

        fs.close();
        fs.flush();
        is.close();

        callback.success(fileName);
    } catch (FileNotFoundException fe) {
        callback.error(fe.getMessage());
    } catch (IOException ie) {
        callback.error(ie.getMessage());
    }
}

From source file:com.rokolabs.app.common.image.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the
 * AsyncTask background thread.//from   w  w  w  . j a  va  2  s.c  o  m
 * 
 * @param data
 *            The data to load the bitmap, in this case, a regular http URL
 * @return The downloaded and resized bitmap
 */
@Override
protected Bitmap processBitmap(ImageFetchTask data, int index) {
    if (Utils.DEBUG) {
        Log.d(TAG, "processBitmap - " + data.getImageUrl(index));
    }
    File temp = null;
    Bitmap bmp = null;
    boolean diskCache = true;
    try {
        String url = data.getImageUrl(index);
        Logger.d("image url: " + url);
        Uri uri = Uri.parse(url);
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            Logger.d("encoded path: " + uri.getEncodedPath());
            diskCache = false;
            bmp = decodeSampledBitmapFromFile(uri.getEncodedPath(), data.getDesiredWidth(),
                    data.getDesiredHeight());
        } else if ("asset".equalsIgnoreCase(uri.getScheme())) {
            diskCache = false;
            String path = uri.getEncodedPath();
            if (path.startsWith("/"))
                path = path.substring(1);
            Logger.d("asset path: " + path);
            bmp = decodeSampledBitmapFromAsset(mResources.getAssets(), path, data.getDesiredWidth(),
                    data.getDesiredHeight());
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            diskCache = false;
            Logger.d("content path: " + url);
            bmp = decodeSampledBitmapFromInputStream(mAppContext.getContentResolver().openInputStream(uri),
                    data.getDesiredWidth(), data.getDesiredHeight());
        } else if ("video".equals(uri.getScheme())) {
            Logger.d("encoded path: " + uri.getEncodedPath());
            bmp = ThumbnailUtils.createVideoThumbnail(uri.getEncodedPath(), Thumbnails.MINI_KIND);
        } else {
            Logger.d(tempDir.getAbsolutePath());
            if (mImageCache != null) {
                bmp = mImageCache.getBitmapFromDiskCache(data.getImageUrl(index), data.getDesiredWidth(),
                        data.getDesiredHeight());
            }
            if (bmp == null) {
                temp = File.createTempFile("img_" + Math.random(), ".jpg", tempDir);
                if (downloadUrlToStream(data.getImageUrl(index), new FileOutputStream(temp))) {
                    Logg.d(temp.getAbsolutePath() + ", size =" + temp.length());
                    bmp = decodeSampledBitmapFromFile(temp.getAbsolutePath(), data.getDesiredWidth(),
                            data.getDesiredHeight());
                    if (bmp != null && mImageCache != null
                            && data.getTaskCachePolicy() == CachePolicy.MEM_AND_DISK) {
                        mImageCache.saveBitmapToDisk(data.getImageUrl(index), temp);
                    } else {
                        if (temp.length() < 2 * 1024)
                            Logg.d("temp file: " + new String(IOUtils.toByteArray(new FileInputStream(temp))));
                        temp.delete();
                    }
                } else {
                    temp.delete();
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "processBitmap - " + e);
    } catch (OutOfMemoryError oom) {
        Logger.printMemory("OOM error " + data.getImageUrl(index));
    } finally {
        if (bmp != null && mImageCache != null && diskCache
                && data.getTaskCachePolicy() == CachePolicy.MEM_AND_DISK)
            mImageCache.saveBitmapToDisk(data.getStoreKey(index), bmp);
    }
    return bmp;
}

From source file:de.vanita5.twittnuker.activity.support.MediaViewerActivity.java

public boolean onMenuItemClick(final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_SAVE: {
        if (mImageFile != null) {
            new SaveImageTask(this, mImageFile).execute();
        }/*from  ww w  .java2 s .c  om*/
        break;
    }
    case MENU_OPEN_IN_BROWSER: {
        final Intent intent = getIntent();
        intent.setExtrasClassLoader(getClassLoader());
        final Uri uri = intent.getData();
        final Uri orig = intent.getParcelableExtra(EXTRA_URI_ORIG);
        final Uri uriPreferred = orig != null ? orig : uri;
        if (uriPreferred == null)
            return false;
        final String scheme = uriPreferred.getScheme();
        if ("http".equals(scheme) || "https".equals(scheme)) {
            final Intent open_intent = new Intent(Intent.ACTION_VIEW, uriPreferred);
            open_intent.addCategory(Intent.CATEGORY_BROWSABLE);
            try {
                startActivity(open_intent);
            } catch (final ActivityNotFoundException e) {
                // Ignore.
            }
        }
        break;
    }
    default: {
        final Intent intent = item.getIntent();
        if (intent != null) {
            try {
                startActivity(intent);
            } catch (final ActivityNotFoundException e) {
                // Ignore.
            }
            return true;
        }
        return false;
    }
    }
    return true;
}

From source file:com.google.android.apps.paco.FeedbackActivity.java

private WebViewClient createWebViewClientThatHandlesFileLinksForCharts(final Feedback feedback) {
    WebViewClient webViewClient = new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            if (uri.getScheme().startsWith("http")) {
                return true; // throw away http requests - we don't want 3rd party javascript sending url requests due to security issues.
            }//w  w w. j  a  va  2 s. c om

            String inputIdStr = uri.getQueryParameter("inputId");
            if (inputIdStr == null) {
                return true;
            }
            long inputId = Long.parseLong(inputIdStr);
            JSONArray results = new JSONArray();
            for (Event event : experiment.getEvents()) {
                JSONArray eventJson = new JSONArray();
                DateTime responseTime = event.getResponseTime();
                if (responseTime == null) {
                    continue; // missed signal;
                }
                eventJson.put(responseTime.getMillis());

                // in this case we are looking for one input from the responses that we are charting.
                for (Output response : event.getResponses()) {
                    if (response.getInputServerId() == inputId) {
                        Input inputById = experiment.getInputById(inputId);
                        if (!inputById.isInvisible() && inputById.isNumeric()) {
                            eventJson.put(response.getDisplayOfAnswer(inputById));
                            results.put(eventJson);
                            continue;
                        }
                    }
                }

            }
            env.put("data", results.toString());
            env.put("inputId", inputIdStr);

            view.loadUrl(stripQuery(url));
            return true;
        }

    };
    return webViewClient;
}

From source file:com.morphoss.acal.service.UpdateTimezones.java

private void refreshTimezoneData() {
    try {//w w  w.  ja v a 2 s . c  o  m
        HashMap<String, Long> currentZones = new HashMap<String, Long>();
        HashMap<String, Long> updatedZones = new HashMap<String, Long>();
        HashMap<String, Long> insertedZones = new HashMap<String, Long>();
        Cursor allZones = cr.query(Timezones.CONTENT_URI,
                new String[] { Timezones.TZID, Timezones.LAST_MODIFIED }, null, null, null);
        Long maxModified = 0L;
        for (allZones.moveToFirst(); !allZones.isAfterLast(); allZones.moveToNext()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found existing zone of '" + allZones.getString(0)
                        + "' modified: " + AcalDateTime.fromMillis(allZones.getLong(1) * 1000L).toString());
            currentZones.put(allZones.getString(0), allZones.getLong(1));
            if (allZones.getLong(1) > maxModified)
                maxModified = allZones.getLong(1);
        }
        AcalDateTime mostRecentChange = AcalDateTime.getUTCInstance().setEpoch(maxModified);
        Log.println(Constants.LOGI, TAG, "Found " + allZones.getCount()
                + " existing timezones, most recent change on " + mostRecentChange.toString());
        if (allZones.getCount() > 350 && mostRecentChange.after(AcalDateTime.getUTCInstance().addDays(-30))) {
            Log.println(Constants.LOGI, TAG, "Skipping update - our database is pretty recent");
            return;
        }

        requestor.interpretUriString(tzUrl("list", null));
        JSONObject root = requestor.doJsonRequest("GET", null, null, null);
        if (requestor.wasRedirected()) {
            Uri tzUri = Uri.parse(requestor.fullUrl());
            String redirectedUrl = tzUri.getScheme() + "://" + tzUri.getAuthority() + tzUri.getPath();
            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Redirected to Timezone Server at " + redirectedUrl);
            tzServerBaseUrl = redirectedUrl;
            AcalApplication.setPreferenceString(PrefNames.tzServerBaseUrl, redirectedUrl);
        }
        if (requestor.getStatusCode() >= 399) {
            Log.println(Constants.LOGI, TAG, "Bad response " + requestor.getStatusCode()
                    + " from Timezone Server at " + tzUrl("list", null));
        }
        if (root == null) {
            Log.println(Constants.LOGI, TAG, "No JSON from GET " + tzUrl("list", null));
            return;
        }

        String tzid;
        String tzData = "";
        long lastModified;
        StringBuilder localNames;
        StringBuilder aliases;
        ContentValues zoneValues = new ContentValues();

        String tzDateStamp = root.getString("dtstamp");
        JSONArray tzArray = root.getJSONArray("timezones");
        for (int i = 0; i < tzArray.length(); i++) {
            JSONObject zoneNode = tzArray.getJSONObject(i);
            tzid = zoneNode.getString("tzid");
            if (updatedZones.containsKey(tzid) || insertedZones.containsKey(tzid))
                continue;

            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Working on " + tzid);

            lastModified = AcalDateTime.fromString(zoneNode.getString("last-modified")).getEpoch();
            if (currentZones.containsKey(tzid) && currentZones.get(tzid) <= lastModified) {
                currentZones.remove(tzid);
                continue;
            }

            tzData = getTimeZone(tzid);
            if (tzData == null)
                continue;

            localNames = new StringBuilder();
            try {
                JSONArray nameNodes = zoneNode.getJSONArray("local_names");
                for (int j = 0; j < nameNodes.length(); j++) {
                    if (localNames.length() > 0)
                        localNames.append("\n");
                    localNames.append(nameNodes.getJSONObject(j).getString("lang")).append('~')
                            .append(nameNodes.getJSONObject(j).getString("lname"));
                }
            } catch (JSONException je) {
            }

            aliases = new StringBuilder();
            try {
                JSONArray aliasNodes = zoneNode.getJSONArray("aliases");
                for (int j = 0; j < aliasNodes.length(); j++) {
                    if (aliases.length() > 0)
                        aliases.append("\n");
                    aliases.append(aliasNodes.getString(j));
                }
            } catch (JSONException je) {
            }

            zoneValues.put(Timezones.TZID, tzid);
            zoneValues.put(Timezones.ZONE_DATA, tzData);
            zoneValues.put(Timezones.LAST_MODIFIED, lastModified);
            zoneValues.put(Timezones.TZ_NAMES, localNames.toString());
            zoneValues.put(Timezones.TZID_ALIASES, aliases.toString());

            Uri tzUri = Uri.withAppendedPath(Timezones.CONTENT_URI,
                    "tzid/" + StaticHelpers.urlescape(tzid, false));

            if (currentZones.containsKey(tzid)) {
                if (cr.update(tzUri, zoneValues, null, null) != 1) {
                    Log.e(TAG, "Failed update for TZID '" + tzid + "'");
                }
                updatedZones.put(tzid, currentZones.get(tzid));
                currentZones.remove(tzid);
            } else {
                if (cr.insert(tzUri, zoneValues) == null)
                    Log.e(TAG, "Failed insert for TZID '" + tzid + "'");
                insertedZones.put(tzid, currentZones.get(tzid));
            }

            if (context.workWaiting()) {
                Log.println(Constants.LOGI, TAG, "Something is waiting - deferring timezone sync until later.");
                deferMe = true;
                break;
            }
            // Let other stuff have a chance
            Thread.sleep(350);
        }
        int removed = 0;

        if (currentZones.size() > 0) {
            StringBuilder s = new StringBuilder();
            for (String tz : currentZones.keySet()) {
                if (s.length() > 0)
                    s.append(',');
                s.append("'").append(tz).append("'");
            }
            removed = cr.delete(Timezones.CONTENT_URI, Timezones.TZID + " IN (" + s + ")", null);
        }

        Log.println(Constants.LOGI, TAG, "Updated data for " + updatedZones.size() + " zones, added data for "
                + insertedZones.size() + " new zones, removed data for " + removed);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.timrae.rikaidroid.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebClient = new WebViewClient() {
        @Override//from w  w  w . java2 s .  c  o m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            if (uri.getScheme().equals("lookup")) {
                String query = uri.getHost();
                Intent i = new Intent(AEDICT_INTENT);
                i.putExtra("kanjis", query);
                i.putExtra("showEntryDetailOnSingleResult", true);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                view.reload();
                return true;
            }

            else {
                view.loadUrl(url);
            }
            return true;
        }
    };
    mWebView.setWebViewClient(mWebClient);
    mEditText = (EditText) findViewById(R.id.search_src_text);
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    if (mProgressBar != null) {
        mProgressBar.setVisibility(View.VISIBLE);
    }

}