Java Code Examples for android.text.TextUtils#isDigitsOnly()

The following examples show how to use android.text.TextUtils#isDigitsOnly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XulPropParser.java    From starcor.xul with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Object doParse(XulAttr prop) {
	xulParsedAttr_Img_FadeIn val = new xulParsedAttr_Img_FadeIn();
	String stringValue = prop.getStringValue();
	if ("true".equals(stringValue) || "enabled".equals(stringValue)) {
		val.enabled = true;
		val.duration = 300;
	} else if (TextUtils.isEmpty(stringValue) || "disabled".equals(stringValue) || "false".equals(stringValue)) {
		val.enabled = false;
		val.duration = 0;
	} else if (TextUtils.isDigitsOnly(stringValue)) {
		val.enabled = true;
		val.duration = XulUtils.tryParseInt(stringValue, 300);
	} else {
		val.enabled = false;
		val.duration = 300;
	}
	return val;
}
 
Example 2
Source File: ConfigFragment.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Integer doInBackground(String... strings) {
    // return version code
    byte[] codeByte = LightNetwork.LightHttpDownload(strings[0]);
    if (codeByte == null) return -1;
    String code = new String(codeByte).trim();
    Log.d("MewX", "version code: " + code);
    if (code.isEmpty() || !TextUtils.isDigitsOnly(code)) return -1;
    else return Integer.parseInt(code);
}
 
Example 3
Source File: HiSettingsHelper.java    From hipda with GNU General Public License v2.0 5 votes vote down vote up
public Date getLastUpdateCheckTime() {
    String millis = mSharedPref.getString(PERF_LAST_UPDATE_CHECK, "");
    if (!TextUtils.isEmpty(millis) && TextUtils.isDigitsOnly(millis)) {
        try {
            return new Date(Long.parseLong(millis));
        } catch (Exception ignored) {
        }
    }
    return null;
}
 
Example 4
Source File: ContactsActivity.java    From BaldPhone with Apache License 2.0 5 votes vote down vote up
@Override
protected Cursor getCursorForFilter(String filter, boolean favorite) {
    if (!TextUtils.isEmpty(filter) && TextUtils.isDigitsOnly(filter)) {
        return getContactsByNumberFilter(filter, favorite);
    } else {
        return getContactsByNameFilter(filter, favorite);
    }
}
 
Example 5
Source File: PreferenceUtil.java    From Android-Application-ZJB with Apache License 2.0 5 votes vote down vote up
public static int getInt(String key, int defaultValue) {
    String origin = getString(key);
    if (!TextUtils.isEmpty(origin) && TextUtils.isDigitsOnly(origin)) {
        return Integer.valueOf(origin);
    }
    return defaultValue;
}
 
Example 6
Source File: SnoozeNoteReceiver.java    From pin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Called from {@link PinboardService} when this receiver's onReceive method was called and passed an appropriate intent.
 * This cannot be called directly as the snoozeDuration setting is needed which is held by the service and can only be obtained through binding.
 * Binding a service is not possible in a BroadcastReceiver so just start the service and let it take care of the work (and call this method)
 * @return number of updated pins
 */
public static int onSnoozePins(Context context, long snoozeDuration, Uri data) {
    ContentValues cv = new ContentValues();
    long snoozed = System.currentTimeMillis();

    //cv.put(NotesProvider.Notes.SNOOZED, snoozed);
    cv.put(NotesProvider.Notes.MODIFIED, snoozed);

    cv.put(NotesProvider.Notes.WAKE_UP, snoozed + snoozeDuration);

    switch(mUris.match(data)) {
        case NOTES_ITEM:
            //Check if last path segment is really just a valid id (probably redundant)
            String idstring = data.getLastPathSegment();

            if(TextUtils.isEmpty(idstring) || !TextUtils.isDigitsOnly(idstring)) {
                Log.e("SnoozeNoteReceiver", String.format("Could not snooze note item: invalid id '%s' in uri '%s'", idstring, data.toString()));
                return 0;
            }
            //continue to next
        case NOTES_LIST:
            int rows = context.getContentResolver().update(data, cv, "text IS NOT NULL", null);//snooze either on note item or all notes which are not marked as deleted (text is not null)
            Log.d("SnoozeNoteReceiver", String.format("Snoozed %d rows", rows));

            //show a toast if the user had dismissed this pin to indicate that this note will pop up again after some delay
            Toast.makeText(context, context.getResources().getString(R.string.toast_pin_dismissed, new Timespan(context, snoozeDuration).toString()), Toast.LENGTH_SHORT).show();

            return rows;
        default:
            Log.e("SnoozeNoteReceiver", String.format("Could not snooze note: invalid uri '%s'", data.toString()));
            return 0;
    }
}
 
Example 7
Source File: RepliesDialog.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public static RepliesDialog newInstance(@Nullable ChanThread thread, String id) {

        if (thread != null && thread.getPosts() != null && thread.getPosts().size() > 0 && !TextUtils.isEmpty(id)) {
            final String boardName = thread.getBoardName();
            final RepliesDialog dialog = new RepliesDialog();
            final Bundle args = new Bundle();
            final ArrayList<String> postNumbers = new ArrayList<>();

            for (ChanPost post : thread.getPosts()) {
                if (id.equals(post.getId())) {
                    postNumbers.add(String.valueOf(post.getNo()));
                }
            }

            args.putString(Extras.EXTRAS_BOARD_NAME, boardName);

            if (TextUtils.isDigitsOnly(id)) {
                args.putLong(Extras.EXTRAS_POST_ID, Long.valueOf(id));
            }

            args.putStringArrayList(Extras.EXTRAS_POST_LIST, postNumbers);
            args.putLong(Extras.EXTRAS_THREAD_ID, thread.getThreadId());

            ThreadRegistry.getInstance().setPosts(thread.getThreadId(), thread.getPosts());
            dialog.setArguments(args);
            return dialog;
        }

        return null;
    }
 
Example 8
Source File: ProxySettingActivity.java    From v9porn with MIT License 5 votes vote down vote up
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bt_proxy_setting_test:
            if (presenter.isSetPorn91VideoAddress()) {
                Logger.t(TAG).d("木有设置地址呀");
                showNeedSetAddressFirstDialog();
                return;
            }
            isTestSuccess = false;
            String proxyIpAddress = etDialogProxySettingIpAddress.getIpAddressStr();
            String portStr = etDialogProxySettingPort.getText().toString().trim();
            if (TextUtils.isEmpty(portStr) || TextUtils.isEmpty(proxyIpAddress) || !TextUtils.isDigitsOnly(portStr)) {
                showMessage("端口号或IP地址不正确", TastyToast.WARNING);
                return;
            }
            int proxyPort = Integer.parseInt(portStr);
            presenter.testProxy(proxyIpAddress, proxyPort);
            QMUIKeyboardHelper.hideKeyboard(v);
            break;
        case R.id.bt_proxy_setting_reset:
            etDialogProxySettingIpAddress.setIpAddressStr("");
            etDialogProxySettingPort.setText("");
            View view = getCurrentFocus();
            if (view instanceof AppCompatEditText || view instanceof EditText) {
                QMUIKeyboardHelper.showKeyboard((EditText) view, QMUIKeyboardHelper.SHOW_KEYBOARD_DELAY_TIME);
            }
            break;
        default:
    }
}
 
Example 9
Source File: SkiaImageRegionDecoder.java    From RxTools-master with Apache License 2.0 4 votes vote down vote up
@Override
public Point init(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            decoder = BitmapRegionDecoder.newInstance(inputStream, false);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }
        }
    }
    return new Point(decoder.getWidth(), decoder.getHeight());
}
 
Example 10
Source File: SkiaImageDecoder.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
@Override
public Bitmap decode(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }
    return bitmap;
}
 
Example 11
Source File: WizardNewPaymentStepFragment.java    From leanback-showcase with Apache License 2.0 4 votes vote down vote up
private static boolean isCardNumberValid(CharSequence number) {
    return (TextUtils.isDigitsOnly(number) && number.length() == 16);
}
 
Example 12
Source File: Parse99Mm.java    From v9porn with MIT License 4 votes vote down vote up
public static BaseResult<List<Mm99>> parse99MmList(String html, int page) {
    BaseResult<List<Mm99>> baseResult = new BaseResult<>();
    baseResult.setTotalPage(1);
    Logger.t(TAG).d(html);
    Document doc = Jsoup.parse(html);
    Element ul = doc.getElementById("piclist");
    Elements lis = ul.select("li");
    List<Mm99> mm99List = new ArrayList<>();
    for (Element li : lis) {
        Mm99 mm99 = new Mm99();
        Element a = li.selectFirst("dt").selectFirst("a");
        String contentUrl = "http://www.99mm.me" + a.attr("href");
        mm99.setContentUrl(contentUrl);

        int startIndex = contentUrl.lastIndexOf("/");
        int endIndex = contentUrl.lastIndexOf(".");
        String idStr = StringUtils.subString(contentUrl, startIndex + 1, endIndex);

        if (!TextUtils.isEmpty(idStr) && TextUtils.isDigitsOnly(idStr)) {
            mm99.setId(Integer.parseInt(idStr));
        } else {
            Logger.t(TAG).d(idStr);
        }

        Element img = a.selectFirst("img");
        String title = img.attr("alt");
        mm99.setTitle(title);
        String imgUrl = img.attr("src");
        HttpUrl httpUrl = HttpUrl.parse(imgUrl);
        if (httpUrl == null) {
            imgUrl = img.attr("data-img");
        }
        Logger.t(TAG).d("图片链接::" + imgUrl);
        mm99.setImgUrl(imgUrl);
        int imgWidth = Integer.parseInt(img.attr("width"));
        mm99.setImgWidth(imgWidth);

        mm99List.add(mm99);
    }

    if (page == 1) {
        Element pageElement = doc.getElementsByClass("all").first();
        if (pageElement != null) {
            String pageStr = pageElement.text().replace("...", "").trim();
            if (!TextUtils.isEmpty(pageStr) && TextUtils.isDigitsOnly(pageStr)) {
                baseResult.setTotalPage(Integer.parseInt(pageStr));
            } else {
                Logger.t(TAG).d(pageStr);
            }
        }
    }

    baseResult.setData(mm99List);
    return baseResult;
}
 
Example 13
Source File: XContentResolver.java    From XPrivacy with GNU General Public License v3.0 4 votes vote down vote up
@SuppressLint("DefaultLocale")
private void handleUriBefore(XParam param) throws Throwable {
	// Check URI
	if (param.args.length > 1 && param.args[0] instanceof Uri) {
		String uri = ((Uri) param.args[0]).toString().toLowerCase();
		String[] projection = (param.args[1] instanceof String[] ? (String[]) param.args[1] : null);

		if (uri.startsWith("content://com.android.contacts/contacts/name_phone_or_email")) {
			// Do nothing

		} else if (uri.startsWith("content://com.android.contacts/")
				&& !uri.equals("content://com.android.contacts/")) {
			String[] components = uri.replace("content://com.android.", "").split("/");
			String methodName = components[0] + "/" + components[1].split("\\?")[0];
			if (methodName.equals("contacts/contacts") || methodName.equals("contacts/data")
					|| methodName.equals("contacts/phone_lookup") || methodName.equals("contacts/raw_contacts"))
				if (isRestrictedExtra(param, PrivacyManager.cContacts, methodName, uri)) {
					// Get ID from URL if any
					int urlid = -1;
					if ((methodName.equals("contacts/contacts") || methodName.equals("contacts/phone_lookup"))
							&& components.length > 2 && TextUtils.isDigitsOnly(components[2]))
						urlid = Integer.parseInt(components[2]);

					// Modify projection
					boolean added = false;
					if (projection != null && urlid < 0) {
						List<String> listProjection = new ArrayList<String>();
						listProjection.addAll(Arrays.asList(projection));
						String cid = getIdForUri(uri);
						if (cid != null && !listProjection.contains(cid)) {
							added = true;
							listProjection.add(cid);
						}
						param.args[1] = listProjection.toArray(new String[0]);
					}
					if (added)
						param.setObjectExtra("column_added", added);
				}
		}
	}
}
 
Example 14
Source File: SkiaImageRegionDecoder.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
@Override
public Point init(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            decoder = BitmapRegionDecoder.newInstance(inputStream, false);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
            }
        }
    }
    return new Point(decoder.getWidth(), decoder.getHeight());
}
 
Example 15
Source File: SkiaImageDecoder.java    From RxTools-master with Apache License 2.0 4 votes vote down vote up
@Override
public Bitmap decode(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }
    return bitmap;
}
 
Example 16
Source File: SkiaImageRegionDecoder.java    From BlogDemo with Apache License 2.0 4 votes vote down vote up
@Override
@NonNull
public Point init(Context context, @NonNull Uri uri) throws Exception {
    String uriString = uri.toString();
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            decoder = BitmapRegionDecoder.newInstance(inputStream, false);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
            }
        }
    }
    return new Point(decoder.getWidth(), decoder.getHeight());
}
 
Example 17
Source File: SkiaImageRegionDecoder.java    From pdfview-android with Apache License 2.0 4 votes vote down vote up
@Override
@NonNull
public Point init(Context context, @NonNull Uri uri) throws Exception {
    String uriString = uri.toString();
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            decoder = BitmapRegionDecoder.newInstance(inputStream, false);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
            }
        }
    }
    return new Point(decoder.getWidth(), decoder.getHeight());
}
 
Example 18
Source File: PostFragment.java    From hipda with GNU General Public License v2.0 4 votes vote down vote up
private boolean isValidImgId(String imgId) {
    return !TextUtils.isEmpty(imgId)
            && TextUtils.isDigitsOnly(imgId)
            && imgId.length() > 1;
}
 
Example 19
Source File: SkiaImageDecoder.java    From edx-app-android with Apache License 2.0 4 votes vote down vote up
@Override
public Bitmap decode(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }
    return bitmap;
}
 
Example 20
Source File: SkiaImageDecoder.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
@Override
public Bitmap decode(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = bitmapConfig;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }
    return bitmap;
}