下面列出了怎么用io.reactivex.annotations.Nullable的API类实例代码及写法,或者点击链接到github查看源代码。
public static AlertDialog getProgress(Context context,
String title,
@Nullable DialogListener<Boolean> dialogListener){
AlertDialog.Builder builder = new AlertDialog.Builder(context, getTheme(context));
builder.setTitle(title);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 80);
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setLayoutParams(layoutParams);
frameLayout.setPadding(0,50, 0, 50);
ProgressBar progressBar = new ProgressBar(context);
progressBar.setLayoutParams(layoutParams);
frameLayout.addView(progressBar);
builder.setView(frameLayout);
builder.setCancelable(false);
if (dialogListener != null) builder.setNegativeButton("取 消", (dialog, which) -> {
dialogListener.onResult(false);
dialog.dismiss();
});
return builder.create();
}
/**
* Extract StackTrace and filter to show an app-specific entry at its top
*
* @param exception RxJavaAssemblyException to be parsed
* @return StackTrace, filtered so a app-specific line is at the top of it
*/
@NonNull
static StackTraceElement[] parseStackTrace(@NonNull RxJavaAssemblyException exception, @Nullable String[] basePackages) {
String[] lines = exception.stacktrace()
.split(NEW_LINE_REGEX);
List<StackTraceElement> stackTrace = new ArrayList<StackTraceElement>();
boolean filterIn = false;
for (String line : lines) {
filterIn = filterIn
|| basePackages == null
|| basePackages.length == 0
|| startsWithAny(line, basePackages);
if (filterIn) {
StackTraceElement element = parseStackTraceLine(line);
if (element != null) {
stackTrace.add(element);
}
}
}
return stackTrace.toArray(new StackTraceElement[0]);
}
@Nullable
private static Bitmap drawableToBitmap(Drawable drawable) {
try {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
// We ask for the bounds if they have been set as they would be most
// correct, then we check we are > 0
final int width = !drawable.getBounds().isEmpty() ?
drawable.getBounds().width() : drawable.getIntrinsicWidth();
final int height = !drawable.getBounds().isEmpty() ?
drawable.getBounds().height() : drawable.getIntrinsicHeight();
// Now we check we are > 0
final Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
return null;
}
}
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
if (!MultiValueMap.class.isAssignableFrom(clazz)) {
return false;
}
if (mediaType == null) {
return true;
}
for (MediaType supportedMediaType : getSupportedMediaTypes()) {
// We can't read multipart....
if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) {
return true;
}
}
return false;
}
private void writeForm(MultiValueMap<String, String> formData, @Nullable MediaType contentType,
HttpOutputMessage outputMessage) throws IOException {
contentType = getMediaType(contentType);
outputMessage.getHeaders().setContentType(contentType);
Charset charset = contentType.getCharset();
Assert.notNull(charset, "No charset"); // should never occur
final byte[] bytes = serializeForm(formData, charset).getBytes(charset);
outputMessage.getHeaders().setContentLength(bytes.length);
if (outputMessage instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream));
}
else {
StreamUtils.copy(bytes, outputMessage.getBody());
}
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof DownloadBookBean) {
return TextUtils.equals(((DownloadBookBean) obj).getNoteUrl(), this.noteUrl);
}
return super.equals(obj);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof DownloadBookBean) {
return TextUtils.equals(((DownloadBookBean) obj).getNoteUrl(), this.noteUrl);
}
return super.equals(obj);
}
@Override
public void onNext(@Nullable ResponseBody<T> t) {
if(t.getErrorCode()!=0){
onFailure(new Exception(t.getErrorMsg()), t.getErrorMsg());
}else {
onSuccess(t.getData());
}
}
public static boolean isNull(@Nullable Object object) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Objects.isNull(object);
} else {
return object == null;
}
}
public static boolean nonNull(@Nullable Object object) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Objects.nonNull(object);
} else {
return object != null;
}
}
public static boolean equals(@Nullable Object a, @Nullable Object b) {
if (Build.VERSION.SDK_INT >= 19) {
return Objects.equals(a, b);
} else {
return (a == b) || (a != null && a.equals(b));
}
}
public static int hash(@Nullable Object... values) {
if (Build.VERSION.SDK_INT >= 19) {
return Objects.hash(values);
} else {
return Arrays.hashCode(values);
}
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof DownloadBookBean) {
return TextUtils.equals(((DownloadBookBean) obj).getNoteUrl(), this.noteUrl);
}
return super.equals(obj);
}
/**
* Parse string containing a <i>single line</i> of a StackTrace
*
* @param stackTraceLine string containing single line of a StackTrace
* @return parsed StackTraceElement
*/
@Nullable
private static StackTraceElement parseStackTraceLine(@NonNull String stackTraceLine) {
StackTraceElement retVal = null;
Matcher matcher = STACK_TRACE_ELEMENT_PATTERN.matcher(stackTraceLine);
if (matcher.matches()) {
String clazz = matcher.group(1);
String method = matcher.group(2);
String filename = matcher.group(3);
int line = Integer.valueOf(matcher.group(4));
retVal = new StackTraceElement(clazz, method, filename, line);
}
return retVal;
}
/**
* Construct a new instance of SoundData from an identifier string which was
* (hopefully) created by [toString](#tostring).
*
* @param string A non-null identifier string.
* @return A recreated SoundData instance.
*/
@Nullable
public static SoundData fromString(String string) {
if (string.contains(SEPARATOR)) {
String[] data = string.split(SEPARATOR);
if (data.length == 3
&& data[0].length() > 0 && data[1].length() > 0 && data[2].length() > 0)
return new SoundData(data[0], data[1], data[2]);
}
return null;
}
/**
* If the receiver is enabled, this method will:
* <p>
* 1. Invoke the `func` given at the time of creation.
* 2. Multicast the returned observable.
* 3. Send the multicasted observable on {@link #executionObservables()}.
* 4. Subscribe (connect) to the original observable on the main thread.
*
* @param input The input value to pass to the receiver's `func`. This may be null.
* @return the multicasted observable, after subscription. If the receiver is not
* enabled, returns a observable that will send an error.
*/
@MainThread
public final Observable<T> execute(@Nullable Object input) {
boolean enabled = mImmediateEnabled.blockingFirst();
if (!enabled) {
return Observable.error(new IllegalStateException("The command is disabled and cannot be executed"));
}
try {
Observable<T> observable = mFunc.apply(input);
if (observable == null) {
throw new RuntimeException(String.format("null Observable returned from observable func for value %s", input));
}
// This means that `executing` and `enabled` will send updated values before
// the observable actually starts performing work.
final ConnectableObservable<T> connection = observable
.subscribeOn(AndroidSchedulers.mainThread())
.replay();
mAddedExecutionObservableSubject.onNext(connection);
connection.connect();
return connection;
} catch (Exception e) {
e.printStackTrace();
return Observable.error(e);
}
}
@Nullable Permission get(@NonNull final String name) {
for (final Permission permission : permissions) {
if (permission.name().equals(name)) {
return permission;
}
}
return null;
}
/**
* @param emitter
* @param function
* @return
*/
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
@NonNull final SingleEmitter<DataSnapshot> emitter,
@NonNull final Function<MutableData, Transaction.Result> function) {
return new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
try {
return function.apply(mutableData);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void onComplete(@Nullable DatabaseError databaseError,
boolean committed,
@NonNull DataSnapshot dataSnapshot) {
if (!emitter.isDisposed()) {
if (null == databaseError) {
emitter.onSuccess(dataSnapshot);
} else {
emitter.onError(databaseError.toException());
}
}
}
};
}
/**
* @param emitter
* @param function
* @return
*/
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
@NonNull final SingleEmitter<DataSnapshot> emitter,
@NonNull final Function<MutableData, Transaction.Result> function) {
return new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
try {
return function.apply(mutableData);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void onComplete(@Nullable DatabaseError databaseError,
boolean committed,
@NonNull DataSnapshot dataSnapshot) {
if (!emitter.isDisposed()) {
if (null == databaseError) {
emitter.onSuccess(dataSnapshot);
} else {
emitter.onError(databaseError.toException());
}
}
}
};
}
/**
* @see StorageReference#putFile(Uri, StorageMetadata, Uri)
*/
@CheckReturnValue
@NonNull
public static Single<UploadTask.TaskSnapshot> putFile(
@NonNull final StorageReference ref,
@NonNull final Uri uri,
@Nullable final StorageMetadata storageMetadata,
@Nullable final Uri existingUploadUri) {
return RxTask.single(new Callable<Task<UploadTask.TaskSnapshot>>() {
@Override
public Task<UploadTask.TaskSnapshot> call() throws Exception {
return ref.putFile(uri, storageMetadata, existingUploadUri);
}
});
}
@Override
public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
if (!MultiValueMap.class.isAssignableFrom(clazz)) {
return false;
}
if (mediaType == null || MediaType.ALL.equals(mediaType)) {
return true;
}
for (MediaType supportedMediaType : getSupportedMediaTypes()) {
if (supportedMediaType.isCompatibleWith(mediaType)) {
return true;
}
}
return false;
}
@Override
@SuppressWarnings("unchecked")
public void write(MultiValueMap<String, ?> map, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
if (!isMultipart(map, contentType)) {
writeForm((MultiValueMap<String, String>) map, contentType, outputMessage);
}
else {
writeMultipart((MultiValueMap<String, Object>) map, outputMessage);
}
}
private boolean isMultipart(MultiValueMap<String, ?> map, @Nullable MediaType contentType) {
if (contentType != null) {
return MediaType.MULTIPART_FORM_DATA.includes(contentType);
}
for (String name : map.keySet()) {
for (Object value : map.get(name)) {
if (value != null && !(value instanceof String)) {
return true;
}
}
}
return false;
}
private MediaType getMediaType(@Nullable MediaType mediaType) {
if (mediaType == null) {
return DEFAULT_FORM_DATA_MEDIA_TYPE;
}
else if (mediaType.getCharset() == null) {
return new MediaType(mediaType, this.charset);
}
else {
return mediaType;
}
}
/**
* Return the filename of the given multipart part. This value will be used for the
* {@code Content-Disposition} header.
* <p>The default implementation returns {@link Resource#getFilename()} if the part is a
* {@code Resource}, and {@code null} in other cases. Can be overridden in subclasses.
* @param part the part to determine the file name for
* @return the filename, or {@code null} if not known
*/
@Nullable
protected String getFilename(Object part) {
if (part instanceof Resource) {
Resource resource = (Resource) part;
String filename = resource.getFilename();
if (filename != null && this.multipartCharset != null) {
filename = MimeDelegate.encode(filename, this.multipartCharset.name());
}
return filename;
}
else {
return null;
}
}
private DownloadManager.Request createRequest(@NonNull String url,
@NonNull String filename,
@Nullable String destinationPath,
@NonNull String mimeType,
boolean inPublicDir,
boolean showCompletedNotification) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription(filename);
request.setMimeType(mimeType);
if (destinationPath == null) {
destinationPath = Environment.DIRECTORY_DOWNLOADS;
}
File destinationFolder = inPublicDir
? Environment.getExternalStoragePublicDirectory(destinationPath)
: new File(context.getFilesDir(), destinationPath);
createFolderIfNeeded(destinationFolder);
removeDuplicateFileIfExist(destinationFolder, filename);
if (inPublicDir) {
request.setDestinationInExternalPublicDir(destinationPath, filename);
} else {
request.setDestinationInExternalFilesDir(context, destinationPath, filename);
}
request.setNotificationVisibility(showCompletedNotification
? DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
: DownloadManager.Request.VISIBILITY_VISIBLE);
return request;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
setTitle(R.string.filter_keywords);
setHasOptionsMenu(false);
mFilterKeywordsManager = FilterKeywordsManagerImpl.getInstance();
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return responseConverter();
}
@Nullable
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
public static int hashCode(@Nullable Object o) {
return o != null ? o.hashCode() : 0;
}