fixing lint problems

This commit is contained in:
Mariotaku Lee 2017-08-27 22:28:44 +08:00
parent 51f05c0f68
commit b69f89df8b
No known key found for this signature in database
GPG Key ID: 15C10F89D7C33535
67 changed files with 237 additions and 221 deletions

View File

@ -18,6 +18,7 @@
package org.mariotaku.microblog.library.twitter.auth;
import android.support.annotation.NonNull;
import android.util.Base64;
import org.mariotaku.restfu.RestRequest;
@ -38,7 +39,7 @@ public final class BasicAuthorization implements Authorization {
}
@Override
public String getHeader(Endpoint endpoint, RestRequest info) {
public String getHeader(@NonNull Endpoint endpoint, @NonNull RestRequest info) {
if (!hasAuthorization()) return null;
return "Basic " + Base64.encodeToString((user + ":" + password).getBytes(), Base64.NO_WRAP);
}

View File

@ -18,6 +18,8 @@
package org.mariotaku.microblog.library.twitter.auth;
import android.support.annotation.NonNull;
import org.mariotaku.restfu.RestRequest;
import org.mariotaku.restfu.http.Authorization;
import org.mariotaku.restfu.http.Endpoint;
@ -34,7 +36,7 @@ public class BearerAuthorization implements Authorization {
@Override
public String getHeader(Endpoint endpoint, RestRequest info) {
public String getHeader(@NonNull Endpoint endpoint, @NonNull RestRequest info) {
return "Bearer " + accessToken;
}

View File

@ -18,6 +18,8 @@
package org.mariotaku.microblog.library.twitter.auth;
import android.support.annotation.NonNull;
import org.mariotaku.restfu.RestRequest;
import org.mariotaku.restfu.http.Authorization;
import org.mariotaku.restfu.http.Endpoint;
@ -28,7 +30,7 @@ import org.mariotaku.restfu.http.Endpoint;
public final class EmptyAuthorization implements Authorization {
@Override
public String getHeader(Endpoint endpoint, RestRequest info) {
public String getHeader(@NonNull Endpoint endpoint, @NonNull RestRequest info) {
return null;
}

View File

@ -18,6 +18,8 @@
package org.mariotaku.microblog.library.twitter.model;
import android.support.annotation.NonNull;
import com.bluelinelabs.logansquare.LoganSquare;
import com.fasterxml.jackson.core.JsonGenerator;
@ -49,15 +51,16 @@ public class CardDataMap implements ValueMap {
}
@Override
public boolean has(String key) {
public boolean has(@NonNull String key) {
return map.containsKey(key);
}
@Override
public Object get(String key) {
public Object get(@NonNull String key) {
return map.get(key);
}
@NonNull
@Override
public String[] keys() {
final Set<String> keySet = map.keySet();
@ -72,8 +75,9 @@ public class CardDataMap implements ValueMap {
}
public static class BodyConverter implements RestConverter<CardDataMap, Body, MicroBlogException> {
@NonNull
@Override
public Body convert(CardDataMap obj) throws ConvertException, IOException, MicroBlogException {
public Body convert(@NonNull CardDataMap obj) throws ConvertException, IOException, MicroBlogException {
final StringWriter sw = new StringWriter();
final JsonGenerator generator = LoganSquare.JSON_FACTORY.createGenerator(sw);
generator.writeStartObject();

View File

@ -20,6 +20,7 @@ package org.mariotaku.microblog.library.twitter.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
@ -100,17 +101,18 @@ public class GeoLocation implements ValueMap, Parcelable {
}
@Override
public boolean has(String key) {
public boolean has(@NonNull String key) {
return "lat".equals(key) || "long".equals(key);
}
@Override
public Object get(String key) {
public Object get(@NonNull String key) {
if ("lat".equals(key)) return latitude;
if ("long".equals(key)) return longitude;
return null;
}
@NonNull
@Override
public String[] keys() {
return new String[]{"lat", "long"};

View File

@ -18,6 +18,8 @@
package org.mariotaku.microblog.library.twitter.model;
import android.support.annotation.NonNull;
import org.mariotaku.restfu.http.ValueMap;
@ -162,7 +164,7 @@ public final class GeoQuery implements ValueMap {
}
@Override
public boolean has(String key) {
public boolean has(@NonNull String key) {
switch (key) {
case "lat":
case "long": {
@ -185,7 +187,7 @@ public final class GeoQuery implements ValueMap {
}
@Override
public String get(String key) {
public String get(@NonNull String key) {
switch (key) {
case "lat": {
if (location == null) return null;

View File

@ -20,12 +20,12 @@ package org.mariotaku.twidere.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import org.jetbrains.annotations.Nullable;
import org.mariotaku.commons.objectcursor.LoganSquareCursorFieldConverter;
import org.mariotaku.library.objectcursor.annotation.CursorField;
import org.mariotaku.library.objectcursor.annotation.CursorObject;

View File

@ -38,8 +38,11 @@ import java.util.List;
@ParcelablePlease
public class UserKey implements Comparable<UserKey>, Parcelable {
@NonNull
private static final String ID_PLACEHOLDER = "#placeholder";
@NonNull
public static final UserKey SELF = new UserKey("#self#", "#self#");
@NonNull
public static final UserKey INVALID = new UserKey("#invalid#", "#invalid#");
public static final Creator<UserKey> CREATOR = new Creator<UserKey>() {

View File

@ -25,8 +25,6 @@ import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import org.mariotaku.microblog.library.twitter.model.DMResponse;
/**
* Created by mariotaku on 2017/2/13.
*/

View File

@ -13,11 +13,11 @@ public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
final WatchViewStub stub = findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
mTextView = stub.findViewById(R.id.text);
}
});
}

View File

@ -21,6 +21,7 @@ package org.mariotaku.twidere.util;
import android.app.Application;
import android.os.Build;
import android.support.annotation.NonNull;
import android.webkit.WebView;
import com.facebook.stetho.DumperPluginsProvider;
@ -56,7 +57,7 @@ public class DebugModeUtils {
builder.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
public Response intercept(@NonNull Chain chain) throws IOException {
if (chain.request().tag() == NoIntercept.INSTANCE) {
return chain.proceed(chain.request());
}

View File

@ -316,12 +316,10 @@ class AccountsDumperPlugin(val context: Context) : DumperPlugin {
return JsonPath.parse(JsonSerializer.serialize(details), configuration)
}
private fun Any.prettyPrint() = if (this is JSONObject) {
toString(4)
} else if (this is JSONArray) {
toString(4)
} else {
toString()
private fun Any.prettyPrint() = when {
this is JSONObject -> toString(4)
this is JSONArray -> toString(4)
else -> toString()
}
}

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!--suppress XmlUnboundNsPrefix -->
<android>
<config>
<overridenavbar />

View File

@ -26,6 +26,7 @@ package io.nayuki.qrcodegen;
import android.support.annotation.NonNull;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@ -36,9 +37,9 @@ import java.util.List;
* from 1 to 40, all 4 error correction levels, and only 3 character encoding modes.</p>
*/
public final class QrCode {
/*---- Public static factory functions ----*/
/**
* Returns a QR Code symbol representing the specified Unicode text string at the specified error correction level.
* As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer Unicode
@ -54,8 +55,8 @@ public final class QrCode {
List<QrSegment> segs = QrSegment.makeSegments(text);
return encodeSegments(segs, ecl);
}
/**
* Returns a QR Code symbol representing the specified binary data string at the specified error correction level.
* This function always encodes using the binary segment mode, not any text mode. The maximum number of
@ -69,10 +70,10 @@ public final class QrCode {
*/
public static QrCode encodeBinary(@NonNull byte[] data, @NonNull Ecc ecl) {
QrSegment seg = QrSegment.makeBytes(data);
return encodeSegments(Arrays.asList(seg), ecl);
return encodeSegments(Collections.singletonList(seg), ecl);
}
/**
* Returns a QR Code symbol representing the specified data segments at the specified error correction
* level or higher. The smallest possible QR Code version is automatically chosen for the output.
@ -88,8 +89,8 @@ public final class QrCode {
public static QrCode encodeSegments(List<QrSegment> segs, Ecc ecl) {
return encodeSegments(segs, ecl, 1, 40, -1, true);
}
/**
* Returns a QR Code symbol representing the specified data segments with the specified encoding parameters.
* The smallest possible QR Code version within the specified range is automatically chosen for the output.
@ -110,7 +111,7 @@ public final class QrCode {
public static QrCode encodeSegments(@NonNull List<QrSegment> segs, @NonNull Ecc ecl, int minVersion, int maxVersion, int mask, boolean boostEcl) {
if (!(1 <= minVersion && minVersion <= maxVersion && maxVersion <= 40) || mask < -1 || mask > 7)
throw new IllegalArgumentException("Invalid value");
// Find the minimal version number to use
int version, dataUsedBits;
for (version = minVersion; ; version++) {
@ -123,13 +124,13 @@ public final class QrCode {
}
if (dataUsedBits == -1)
throw new AssertionError();
// Increase the error correction level while the data still fits in the current version number
for (Ecc newEcl : Ecc.values()) {
if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
ecl = newEcl;
}
// Create the data bit string by concatenating all segments
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;
BitBuffer bb = new BitBuffer();
@ -138,17 +139,17 @@ public final class QrCode {
bb.appendBits(seg.numChars, seg.mode.numCharCountBits(version));
bb.appendData(seg);
}
// Add terminator and pad up to a byte if applicable
bb.appendBits(0, Math.min(4, dataCapacityBits - bb.bitLength()));
bb.appendBits(0, (8 - bb.bitLength() % 8) % 8);
// Pad with alternate bytes until data capacity is reached
for (int padByte = 0xEC; bb.bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
bb.appendBits(padByte, 8);
if (bb.bitLength() % 8 != 0)
throw new AssertionError();
// Create the QR Code symbol
return new QrCode(version, ecl, bb.getBytes(), mask);
}
@ -156,24 +157,24 @@ public final class QrCode {
/*---- Instance fields ----*/
// Public immutable scalar parameters
/** This QR Code symbol's version number, which is always between 1 and 40 (inclusive). */
public final int version;
/** The width and height of this QR Code symbol, measured in modules.
* Always equal to version &times; 4 + 17, in the range 21 to 177. */
public final int size;
/** The error correction level used in this QR Code symbol. Never {@code null}. */
public final Ecc errorCorrectionLevel;
/** The mask pattern used in this QR Code symbol, in the range 0 to 7 (i.e. unsigned 3-bit integer).
* Note that even if a constructor was called with automatic masking requested
* (mask = -1), the resulting object will still have a mask value between 0 and 7. */
public final int mask;
// Private grids of modules/pixels (conceptually immutable)
private boolean[][] modules; // The modules of this QR Code symbol (false = white, true = black)
private boolean[][] isFunction; // Indicates function modules that are not subjected to masking
@ -181,7 +182,7 @@ public final class QrCode {
/*---- Constructors ----*/
/**
* Creates a new QR Code symbol with the specified version number, error correction level, binary data array, and mask number.
* <p>This is a cumbersome low-level constructor that should not be invoked directly by the user.
@ -204,15 +205,15 @@ public final class QrCode {
errorCorrectionLevel = ecl;
modules = new boolean[size][size]; // Entirely white grid
isFunction = new boolean[size][size];
// Draw function patterns, draw all codewords, do masking
drawFunctionPatterns();
byte[] allCodewords = appendErrorCorrection(dataCodewords);
drawCodewords(allCodewords);
this.mask = handleConstructorMasking(mask);
}
/**
* Creates a new QR Code symbol based on the specified existing object, but with a potentially
* different mask pattern. The version, error correction level, codewords, etc. of the newly
@ -226,18 +227,18 @@ public final class QrCode {
// Check arguments
if (mask < -1 || mask > 7)
throw new IllegalArgumentException("Mask value out of range");
// Copy scalar fields
version = qr.version;
size = qr.size;
errorCorrectionLevel = qr.errorCorrectionLevel;
// Handle grid fields
isFunction = qr.isFunction; // Shallow copy because the data is read-only
modules = qr.modules.clone(); // Deep copy
for (int i = 0; i < modules.length; i++)
modules[i] = modules[i].clone();
// Handle masking
applyMask(qr.mask); // Undo old mask
this.mask = handleConstructorMasking(mask);
@ -246,7 +247,7 @@ public final class QrCode {
/*---- Public instance methods ----*/
/**
* Returns the color of the module (pixel) at the specified coordinates, which is either 0 for white or 1 for black. The top
* left corner has the coordinates (x=0, y=0). If the specified coordinates are out of bounds, then 0 (white) is returned.
@ -262,19 +263,19 @@ public final class QrCode {
}
/*---- Private helper methods for constructor: Drawing function modules ----*/
private void drawFunctionPatterns() {
// Draw horizontal and vertical timing patterns
for (int i = 0; i < size; i++) {
setFunctionModule(6, i, i % 2 == 0);
setFunctionModule(i, 6, i % 2 == 0);
}
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
drawFinderPattern(3, 3);
drawFinderPattern(size - 4, 3);
drawFinderPattern(3, size - 4);
// Draw numerous alignment patterns
int[] alignPatPos = getAlignmentPatternPositions(version);
int numAlign = alignPatPos.length;
@ -286,13 +287,13 @@ public final class QrCode {
drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
}
}
// Draw configuration data
drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
drawVersion();
}
// Draws two copies of the format bits (with its own error correction code)
// based on the given mask and this object's error correction level field.
private void drawFormatBits(int mask) {
@ -305,7 +306,7 @@ public final class QrCode {
data ^= 0x5412; // uint15
if (data >>> 15 != 0)
throw new AssertionError();
// Draw first copy
for (int i = 0; i <= 5; i++)
setFunctionModule(8, i, ((data >>> i) & 1) != 0);
@ -314,7 +315,7 @@ public final class QrCode {
setFunctionModule(7, 8, ((data >>> 8) & 1) != 0);
for (int i = 9; i < 15; i++)
setFunctionModule(14 - i, 8, ((data >>> i) & 1) != 0);
// Draw second copy
for (int i = 0; i <= 7; i++)
setFunctionModule(size - 1 - i, 8, ((data >>> i) & 1) != 0);
@ -322,14 +323,14 @@ public final class QrCode {
setFunctionModule(8, size - 15 + i, ((data >>> i) & 1) != 0);
setFunctionModule(8, size - 8, true);
}
// Draws two copies of the version bits (with its own error correction code),
// based on this object's version field (which only has an effect for 7 <= version <= 40).
private void drawVersion() {
if (version < 7)
return;
// Calculate error correction code and pack bits
int rem = version; // version is uint6, in the range [7, 40]
for (int i = 0; i < 12; i++)
@ -337,7 +338,7 @@ public final class QrCode {
int data = version << 12 | rem; // uint18
if (data >>> 18 != 0)
throw new AssertionError();
// Draw two copies
for (int i = 0; i < 18; i++) {
boolean bit = ((data >>> i) & 1) != 0;
@ -346,8 +347,8 @@ public final class QrCode {
setFunctionModule(b, a, bit);
}
}
// Draws a 9*9 finder pattern including the border separator, with the center module at (x, y).
private void drawFinderPattern(int x, int y) {
for (int i = -4; i <= 4; i++) {
@ -359,8 +360,8 @@ public final class QrCode {
}
}
}
// Draws a 5*5 alignment pattern, with the center module at (x, y).
private void drawAlignmentPattern(int x, int y) {
for (int i = -2; i <= 2; i++) {
@ -368,8 +369,8 @@ public final class QrCode {
setFunctionModule(x + j, y + i, Math.max(Math.abs(i), Math.abs(j)) != 1);
}
}
// Sets the color of a module and marks it as a function module.
// Only used by the constructor. Coordinates must be in range.
private void setFunctionModule(int x, int y, boolean isBlack) {
@ -379,20 +380,20 @@ public final class QrCode {
/*---- Private helper methods for constructor: Codewords and masking ----*/
// Returns a new byte string representing the given data with the appropriate error correction
// codewords appended to it, based on this object's version and error correction level.
private byte[] appendErrorCorrection(byte[] data) {
if (data.length != getNumDataCodewords(version, errorCorrectionLevel))
throw new IllegalArgumentException();
// Calculate parameter numbers
int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[errorCorrectionLevel.ordinal()][version];
int blockEccLen = ECC_CODEWORDS_PER_BLOCK[errorCorrectionLevel.ordinal()][version];
int rawCodewords = getNumRawDataModules(version) / 8;
int numShortBlocks = numBlocks - rawCodewords % numBlocks;
int shortBlockLen = rawCodewords / numBlocks;
// Split data into blocks and append ECC to each block
byte[][] blocks = new byte[numBlocks][];
ReedSolomonGenerator rs = new ReedSolomonGenerator(blockEccLen);
@ -404,7 +405,7 @@ public final class QrCode {
System.arraycopy(ecc, 0, block, block.length - blockEccLen, ecc.length);
blocks[i] = block;
}
// Interleave (not concatenate) the bytes from every block into a single sequence
byte[] result = new byte[rawCodewords];
for (int i = 0, k = 0; i < blocks[0].length; i++) {
@ -418,14 +419,14 @@ public final class QrCode {
}
return result;
}
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
// data area of this QR Code symbol. Function modules need to be marked off before this is called.
private void drawCodewords(@NonNull byte[] data) {
if (data.length != getNumRawDataModules(version) / 8)
throw new IllegalArgumentException();
int i = 0; // Bit index into the data
// Do the funny zigzag scan
for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
@ -448,8 +449,8 @@ public final class QrCode {
if (i != data.length * 8)
throw new AssertionError();
}
// XORs the data modules in this QR Code with the given mask pattern. Due to XOR's mathematical
// properties, calling applyMask(m) twice with the same value is equivalent to no change at all.
// This means it is possible to apply a mask, undo it, and try another mask. Note that a final
@ -475,8 +476,8 @@ public final class QrCode {
}
}
}
// A messy helper function for the constructors. This QR Code must be in an unmasked state when this
// method is called. The given argument is the requested mask, which is -1 for auto or 0 to 7 for fixed.
// This method applies and returns the actual mask chosen, from 0 to 7.
@ -500,13 +501,13 @@ public final class QrCode {
applyMask(mask); // Apply the final choice of mask
return mask; // The caller shall assign this value to the final-declared field
}
// Calculates and returns the penalty score based on state of this QR Code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private int getPenaltyScore() {
int result = 0;
// Adjacent modules in row having same color
for (int y = 0; y < size; y++) {
boolean colorX = false;
@ -539,7 +540,7 @@ public final class QrCode {
}
}
}
// 2*2 blocks of modules having same color
for (int y = 0; y < size - 1; y++) {
for (int x = 0; x < size - 1; x++) {
@ -550,7 +551,7 @@ public final class QrCode {
result += PENALTY_N2;
}
}
// Finder-like pattern in rows
for (int y = 0; y < size; y++) {
for (int x = 0, bits = 0; x < size; x++) {
@ -567,7 +568,7 @@ public final class QrCode {
result += PENALTY_N3;
}
}
// Balance of black and white modules
int black = 0;
for (boolean[] row : modules) {
@ -586,7 +587,7 @@ public final class QrCode {
/*---- Private static helper functions ----*/
// Returns a set of positions of the alignment patterns in ascending order. These positions are
// used on both the x and y axes. Each value in the resulting array is in the range [0, 177).
// This stateless pure function could be implemented as table of 40 variable-length lists of unsigned bytes.
@ -602,7 +603,7 @@ public final class QrCode {
step = (ver * 4 + numAlign * 2 + 1) / (2 * numAlign - 2) * 2; // ceil((size - 13) / (2*numAlign - 2)) * 2
else // C-C-C-Combo breaker!
step = 26;
int[] result = new int[numAlign];
int size = ver * 4 + 17;
result[0] = 6;
@ -611,15 +612,15 @@ public final class QrCode {
return result;
}
}
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
private static int getNumRawDataModules(int ver) {
if (ver < 1 || ver > 40)
throw new IllegalArgumentException("Version number out of range");
int size = ver * 4 + 17;
int result = size * size; // Number of modules in the whole QR symbol square
result -= 64 * 3; // Subtract the three finders with separators
@ -636,8 +637,8 @@ public final class QrCode {
}
return result;
}
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
// QR Code of the given version number and error correction level, with remainder bits discarded.
// This stateless pure function could be implemented as a (40*4)-cell lookup table.
@ -649,14 +650,14 @@ public final class QrCode {
/*---- Private tables of constants ----*/
// For use in getPenaltyScore(), when evaluating which mask is best.
private static final int PENALTY_N1 = 3;
private static final int PENALTY_N2 = 3;
private static final int PENALTY_N3 = 40;
private static final int PENALTY_N4 = 10;
private static final byte[][] ECC_CODEWORDS_PER_BLOCK = {
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
@ -665,7 +666,7 @@ public final class QrCode {
{-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile
{-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High
};
private static final byte[][] NUM_ERROR_CORRECTION_BLOCKS = {
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
@ -678,7 +679,7 @@ public final class QrCode {
/*---- Public helper enumeration ----*/
/**
* Represents the error correction level used in a QR Code symbol.
*/
@ -686,12 +687,12 @@ public final class QrCode {
// These enum constants must be declared in ascending order of error protection,
// for the sake of the implicit ordinal() method and values() function.
LOW(1), MEDIUM(0), QUARTILE(3), HIGH(2);
// In the range 0 to 3 (unsigned 2-bit integer).
final int formatBits;
// Constructor.
private Ecc(int fb) {
Ecc(int fb) {
formatBits = fb;
}
}
@ -699,7 +700,7 @@ public final class QrCode {
/*---- Private helper class ----*/
/**
* Computes the Reed-Solomon error correction codewords for a sequence of data codewords
* at a given degree. Objects are immutable, and the state only depends on the degree.
@ -708,14 +709,14 @@ public final class QrCode {
private static final class ReedSolomonGenerator {
/*-- Immutable field --*/
// Coefficients of the divisor polynomial, stored from highest to lowest power, excluding the leading term which
// is always 1. For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}.
private final byte[] coefficients;
/*-- Constructor --*/
/**
* Creates a Reed-Solomon ECC generator for the specified degree. This could be implemented
* as a lookup table over all possible parameter values, instead of as an algorithm.
@ -725,11 +726,11 @@ public final class QrCode {
public ReedSolomonGenerator(int degree) {
if (degree < 1 || degree > 255)
throw new IllegalArgumentException("Degree out of range");
// Start with the monomial x^0
coefficients = new byte[degree];
coefficients[degree - 1] = 1;
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
// drop the highest term, and store the rest of the coefficients in order of descending powers.
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
@ -747,7 +748,7 @@ public final class QrCode {
/*-- Method --*/
/**
* Computes and returns the Reed-Solomon error correction codewords for the specified sequence of data codewords.
* The returned object is always a new byte array. This method does not alter this object's state (because it is immutable).
@ -770,7 +771,7 @@ public final class QrCode {
/*-- Static function --*/
// Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
// are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
private static int multiply(int x, int y) {
@ -786,7 +787,7 @@ public final class QrCode {
throw new AssertionError();
return z;
}
}
}

View File

@ -254,7 +254,7 @@ public final class QrSegment {
/*-- Constructor --*/
private Mode(int mode, int... ccbits) {
Mode(int mode, int... ccbits) {
this.modeBits = mode;
numBitsCharCount = ccbits;
}

View File

@ -68,7 +68,7 @@ public class SavedSearchesAdapter extends BaseAdapter {
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View view = convertView != null ? convertView : mInflater.inflate(
android.R.layout.simple_list_item_1, null);
final TextView text = (TextView) view.findViewById(android.R.id.text1);
final TextView text = view.findViewById(android.R.id.text1);
text.setText(getItem(position).getName());
return view;
}

View File

@ -20,8 +20,6 @@ import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
@ -114,7 +112,7 @@ public class ExtendedDividerItemDecoration extends RecyclerView.ItemDecoration {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin +
Math.round(ViewCompat.getTranslationY(child));
Math.round(child.getTranslationY());
final int bottom = top + mDivider.getIntrinsicHeight();
if (mPadding != null && mPadding.get(childPos, mPaddingRect)) {
mDivider.setBounds(left + mPaddingRect.left, top + mPaddingRect.top, right - mPaddingRect.right,
@ -145,7 +143,7 @@ public class ExtendedDividerItemDecoration extends RecyclerView.ItemDecoration {
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin +
Math.round(ViewCompat.getTranslationX(child));
Math.round(child.getTranslationX());
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left + mPaddingRect.left, top + mPaddingRect.top, right - mPaddingRect.right,

View File

@ -200,7 +200,7 @@ public final class DataExportImportTypeSelectorDialogFragment extends BaseDialog
@Override
public View getView(final int position, @Nullable final View convertView, final ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
final TextView text1 = (TextView) view.findViewById(android.R.id.text1);
final TextView text1 = view.findViewById(android.R.id.text1);
text1.setText(getItem(position).title);
view.setEnabled(isEnabled(position));
return view;

View File

@ -20,8 +20,6 @@ import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.ListPreference;
import org.mariotaku.twidere.util.TwidereArrayUtils;
public class ThemedListPreferenceDialogFragmentCompat extends ThemedPreferenceDialogFragmentCompat {
private int mClickedDialogEntryIndex;

View File

@ -28,6 +28,7 @@ import org.mariotaku.twidere.annotation.AccountType;
import org.mariotaku.twidere.model.util.UserKeyCursorFieldConverter;
import org.mariotaku.twidere.provider.TwidereDataStore.Accounts;
@SuppressWarnings("DeprecatedIsStillUsed")
@CursorObject
@Deprecated
public class ParcelableAccount {

View File

@ -28,6 +28,7 @@ import org.mariotaku.twidere.provider.TwidereDataStore.Accounts;
/**
* Created by mariotaku on 15/5/26.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@CursorObject
@Deprecated
public class ParcelableCredentials extends ParcelableAccount {

View File

@ -21,10 +21,10 @@ package org.mariotaku.twidere.model.pagination;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import org.jetbrains.annotations.Nullable;
import org.mariotaku.microblog.library.twitter.model.Paging;
/**

View File

@ -21,10 +21,10 @@ package org.mariotaku.twidere.model.pagination;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import org.jetbrains.annotations.Nullable;
import org.mariotaku.microblog.library.twitter.model.Paging;
/**

View File

@ -209,13 +209,13 @@ public class SeekBarDialogPreference extends DialogPreference implements IDialog
super.onBindDialogView(view);
final SeekBarDialogPreference preference = (SeekBarDialogPreference) getPreference();
final CharSequence message = preference.getDialogMessage();
final TextView dialogMessageText = (TextView) view.findViewById(R.id.text_dialog_message);
final TextView dialogMessageText = view.findViewById(R.id.text_dialog_message);
dialogMessageText.setText(message);
dialogMessageText.setVisibility(TextUtils.isEmpty(message) ? View.GONE : View.VISIBLE);
mProgressText = (TextView) view.findViewById(R.id.text_progress);
mProgressText = view.findViewById(R.id.text_progress);
mSeekBar = (SeekBar) view.findViewById(R.id.seek_bar);
mSeekBar = view.findViewById(R.id.seek_bar);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {

View File

@ -184,7 +184,7 @@ public class ThemeBackgroundPreference extends DialogPreference implements Const
final View view = inflater.inflate(R.layout.dialog_theme_background_preference, listViewParent);
((ViewGroup) view.findViewById(R.id.list_container)).addView(listView);
mAlphaContainer = view.findViewById(R.id.alpha_container);
mAlphaSlider = (SeekBar) view.findViewById(R.id.alpha_slider);
mAlphaSlider = view.findViewById(R.id.alpha_slider);
mAlphaSlider.setMax(MAX_ALPHA - MIN_ALPHA);
mAlphaSlider.setProgress(preferences.getInt(KEY_THEME_BACKGROUND_ALPHA, DEFAULT_THEME_BACKGROUND_ALPHA) - MIN_ALPHA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

View File

@ -94,7 +94,7 @@ public class MicroBlogAPIFactory implements TwidereConstants {
@NonNull
public static String getApiBaseUrl(@NonNull String format, @Nullable final String domain) {
final Matcher matcher = Pattern.compile("\\[(\\.?)DOMAIN(\\.?)\\]", Pattern.CASE_INSENSITIVE).matcher(format);
final Matcher matcher = Pattern.compile("\\[(\\.?)DOMAIN(\\.?)]", Pattern.CASE_INSENSITIVE).matcher(format);
final String baseUrl;
if (!matcher.find()) {
// For backward compatibility

View File

@ -22,7 +22,6 @@ package org.mariotaku.twidere.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.view.MotionEventCompat;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.View;
@ -75,7 +74,7 @@ public class MouseScrollDirectionDecider {
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) == 0) {
return false;
}
if (event.getAction() != MotionEventCompat.ACTION_SCROLL) return false;
if (event.getAction() != MotionEvent.ACTION_SCROLL) return false;
verticalScroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
horizontalScroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
verticalView.onGenericMotionEvent(event);

View File

@ -24,7 +24,6 @@ import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import java.util.HashMap;

View File

@ -1,5 +1,7 @@
package org.mariotaku.twidere.util.net;
import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
@ -11,12 +13,12 @@ public final class SimpleCookieJar implements CookieJar {
private final List<Cookie> allCookies = new ArrayList<>();
@Override
public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
public synchronized void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
allCookies.addAll(cookies);
}
@Override
public synchronized List<Cookie> loadForRequest(HttpUrl url) {
public synchronized List<Cookie> loadForRequest(@NonNull HttpUrl url) {
List<Cookie> result = new ArrayList<>();
for (Cookie cookie : allCookies) {
if (cookie.matches(url)) {

View File

@ -25,7 +25,6 @@ import android.content.res.TypedArray;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ScrollerCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.GestureDetector;
@ -34,6 +33,7 @@ import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.OverScroller;
import org.mariotaku.twidere.R;
import org.mariotaku.twidere.util.TwidereMathUtils;
@ -46,7 +46,7 @@ import org.mariotaku.twidere.util.TwidereMathUtils;
public class HeaderDrawerLayout extends ViewGroup {
private final ViewDragHelper mDragHelper;
private final ScrollerCompat mScroller;
private final OverScroller mScroller;
private final GestureDetector mGestureDetector;
private final InternalContainer mContainer;
@ -70,7 +70,7 @@ public class HeaderDrawerLayout extends ViewGroup {
a.recycle();
mDragHelper = ViewDragHelper.create(this, mDragCallback = new DragCallback(this));
mGestureDetector = new GestureDetector(context, new GestureListener(this));
mScroller = ScrollerCompat.create(context);
mScroller = new OverScroller(context);
}
public HeaderDrawerLayout(Context context, AttributeSet attrs) {

View File

@ -25,7 +25,6 @@ import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
@ -213,11 +212,11 @@ public class LinePageIndicator extends View implements PagerIndicator {
}
@Override
public boolean onTouchEvent(@NonNull final android.view.MotionEvent ev) {
public boolean onTouchEvent(@NonNull final MotionEvent ev) {
if (super.onTouchEvent(ev)) return true;
if (mViewPager == null || mViewPager.getAdapter().getCount() == 0) return false;
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
final int action = ev.getAction() & MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getPointerId(0);
@ -273,21 +272,21 @@ public class LinePageIndicator extends View implements PagerIndicator {
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = ev.getActionIndex();
mLastMotionX = ev.getX(index);
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
case MotionEvent.ACTION_POINTER_UP:
final int pointerIndex = ev.getActionIndex();
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
}
mLastMotionX = MotionEventCompat.getX(ev, ev.findPointerIndex(mActivePointerId));
mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId));
break;
}

View File

@ -410,9 +410,9 @@ public class TabPagerIndicator extends RecyclerView implements PagerIndicator, C
public void addTab(int icon, CharSequence label, int unread, boolean isCurrent) {
final ItemLayout layout = (ItemLayout) inflater.inflate(R.layout.layout_tab_item, this, false);
final ImageView tabIcon = (ImageView) layout.findViewById(R.id.tab_icon);
final BadgeView badgeView = (BadgeView) layout.findViewById(R.id.unread_indicator);
final TextView tabLabel = (TextView) layout.findViewById(R.id.tab_label);
final ImageView tabIcon = layout.findViewById(R.id.tab_icon);
final BadgeView badgeView = layout.findViewById(R.id.unread_indicator);
final TextView tabLabel = layout.findViewById(R.id.tab_label);
layout.setStripColor(stripColor);
layout.setStripHeight(stripHeight);
@ -500,9 +500,9 @@ public class TabPagerIndicator extends RecyclerView implements PagerIndicator, C
this.itemView = (ItemLayout) itemView;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
iconView = (ImageView) itemView.findViewById(R.id.tab_icon);
labelView = (TextView) itemView.findViewById(R.id.tab_label);
badgeView = (BadgeView) itemView.findViewById(R.id.unread_indicator);
iconView = itemView.findViewById(R.id.tab_icon);
labelView = itemView.findViewById(R.id.tab_label);
badgeView = itemView.findViewById(R.id.unread_indicator);
}
@Override

View File

@ -60,13 +60,14 @@ class BrowserSignInActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_browser_sign_in)
webView.setWebChromeClient(AuthorizationWebChromeClient(this))
webView.setWebViewClient(AuthorizationWebViewClient(this))
webView.webChromeClient = AuthorizationWebChromeClient(this)
webView.webViewClient = AuthorizationWebViewClient(this)
webView.isVerticalScrollBarEnabled = false
webView.addJavascriptInterface(InjectorJavaScriptInterface(this), "injector")
val webSettings = webView.settings
webSettings.applyDefault()
webSettings.setSupportMultipleWindows(true)
webView.settings.apply {
applyDefault()
setSupportMultipleWindows(true)
}
webView.loadUrl(intent.dataString)
}

View File

@ -22,6 +22,7 @@ package org.mariotaku.twidere.activity
import android.accounts.AccountManager
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
@ -953,6 +954,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
return false
}
@SuppressLint("SetTextI18n")
private fun handleMentionIntent(user: ParcelableUser?): Boolean {
if (user == null || user.key == null) return false
val accountScreenName = DataStoreUtils.getAccountScreenName(this, user.account_key)
@ -2051,7 +2053,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
private class DeleteMediaTask(
activity: ComposeActivity,
val media: Array<ParcelableMediaUpdate>
media: Array<ParcelableMediaUpdate>
) : AbsDeleteMediaTask<((BooleanArray) -> Unit)?>(activity, media.mapToArray { Uri.parse(it.uri) }) {
override fun beforeExecute() {

View File

@ -21,7 +21,7 @@ package org.mariotaku.twidere.extension
import android.net.Uri
fun Uri.withAppendedPath(path: String) = Uri.withAppendedPath(this, path)
fun Uri.withAppendedPath(path: String): Uri = Uri.withAppendedPath(this, path)
fun Uri.Builder.appendQueryParameterIgnoreNull(key: String, value: String?) {
if (value == null) return

View File

@ -165,7 +165,7 @@ fun FiltersData.parse(parser: XmlPullParser) {
}
fun FiltersData.addAll(data: FiltersData, ignoreDuplicates: Boolean = false): Boolean {
var changed: Boolean = false
var changed = false
initFields()
if (data.users != null) {
changed = changed or this.users.addAllEnhanced(collection = data.users, ignoreDuplicates = ignoreDuplicates)

View File

@ -39,7 +39,7 @@ fun User.getProfileImageOfSize(size: String): String {
if (larger != null) return larger
}
val profileImage = profileImageUrlHttps ?: profileImageUrl
return Utils.getTwitterProfileImageOfSize(profileImage, size) ?: profileImage
return Utils.getTwitterProfileImageOfSize(profileImage, size)
}

View File

@ -25,8 +25,9 @@ import org.mariotaku.twidere.util.HtmlEscapeHelper
/**
* Created by mariotaku on 2017/4/19.
*/
val Application.sourceHtml: String get() {
val name = this.name ?: return ""
val website = this.website ?: return name.let(HtmlEscapeHelper::escape).orEmpty()
return "<a href='${HtmlEscapeHelper.escape(website)}'>${HtmlEscapeHelper.escape(name)}</a>"
}
val Application.sourceHtml: String
get() {
val name = this.name ?: return ""
val website = this.website ?: return name.let(HtmlEscapeHelper::escape)
return "<a href='${HtmlEscapeHelper.escape(website)}'>${HtmlEscapeHelper.escape(name)}</a>"
}

View File

@ -37,12 +37,13 @@ open class BaseWebViewFragment : BaseFragment() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val view = webView
view!!.setWebViewClient(createWebViewClient())
val settings = view.settings
settings.builtInZoomControls = true
settings.javaScriptEnabled = true
WebSettingsSupport.setAllowUniversalAccessFromFileURLs(settings, true)
val view = webView!!
view.webViewClient = createWebViewClient()
view.settings.apply {
builtInZoomControls = true
javaScriptEnabled = true
WebSettingsSupport.setAllowUniversalAccessFromFileURLs(this, true)
}
}

View File

@ -1723,7 +1723,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
fun getItemType(position: Int): Int {
var typeStart = 0
for (type in 0..ITEM_TYPES_SUM - 1) {
for (type in 0 until ITEM_TYPES_SUM) {
val typeCount = getTypeCount(type)
val typeEnd = typeStart + typeCount
if (position in typeStart until typeEnd) return type
@ -1734,7 +1734,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
fun getItemTypeStart(position: Int): Int {
var typeStart = 0
for (type in 0..ITEM_TYPES_SUM - 1) {
for (type in 0 until ITEM_TYPES_SUM) {
val typeCount = getTypeCount(type)
val typeEnd = typeStart + typeCount
if (position in typeStart until typeEnd) return typeStart
@ -1814,7 +1814,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
fun getFirstPositionOfItem(itemIdx: Int): Int {
var position = 0
for (i in 0..ITEM_TYPES_SUM - 1) {
for (i in 0 until ITEM_TYPES_SUM) {
if (itemIdx == i) return position
position += getTypeCount(i)
}

View File

@ -79,7 +79,7 @@ class TrendsSuggestionsFragment : AbsContentListViewFragment<TrendsAdapter>(), L
val uri = CachedTrends.Local.CONTENT_URI
val loaderWhere = Expression.and(Expression.equalsArgs(CachedTrends.ACCOUNT_KEY),
Expression.equalsArgs(CachedTrends.WOEID)).sql
val loaderWhereArgs = arrayOf(accountKey?.toString()?.orEmpty(), woeId.toString())
val loaderWhereArgs = arrayOf(accountKey?.toString().orEmpty(), woeId.toString())
return CursorLoader(activity, uri, CachedTrends.COLUMNS, loaderWhere, loaderWhereArgs, CachedTrends.TREND_ORDER)
}

View File

@ -325,6 +325,7 @@ class MessageNewConversationFragment : BaseFragment(), LoaderCallbacks<List<Parc
Expression.equalsArgs(Conversations.PARTICIPANT_KEYS)).sql
val whereArgs = arrayOf(accountKey.toString(), participantKeys.sorted().joinToString(","))
val cur = resolver.query(Conversations.CONTENT_URI, Conversations.COLUMNS, where, whereArgs, null) ?: return null
@Suppress("ConvertTryFinallyToUseCall")
try {
if (cur.moveToFirst()) {
val indices = ObjectCursor.indicesFrom(cur, ParcelableMessageConversation::class.java)

View File

@ -121,6 +121,7 @@ class ParcelableUserLoader(
}
resolver.query(CachedUsers.CONTENT_URI, CachedUsers.COLUMNS, where.sql,
whereArgs, null)?.let { cur ->
@Suppress("ConvertTryFinallyToUseCall")
try {
cur.moveToFirst()
val indices = ObjectCursor.indicesFrom(cur, ParcelableUser::class.java)

View File

@ -78,12 +78,12 @@ abstract class BaseGroupsLoader(
nextPagination = CursorPagination.valueOf(listLoaded.nextCursor)
prevPagination = CursorPagination.valueOf(listLoaded.previousCursor)
val dataSize = data.size
for (i in 0..listSize - 1) {
for (i in 0 until listSize) {
val group = listLoaded[i]
data.add(ParcelableGroupUtils.from(group, accountKey, dataSize + i, isMember(group)))
}
} else {
for (i in 0..listSize - 1) {
for (i in 0 until listSize) {
val list = listLoaded[i]
data.add(ParcelableGroupUtils.from(listLoaded[i], accountKey, i, isMember(list)))
}

View File

@ -97,13 +97,13 @@ abstract class BaseUserListsLoader(
nextPagination = CursorPagination.valueOf(listLoaded.nextCursor)
prevPagination = CursorPagination.valueOf(listLoaded.previousCursor)
val dataSize = data.size
for (i in 0..listSize - 1) {
for (i in 0 until listSize) {
val list = listLoaded[i]
data.add(list.toParcelable(accountKey, (dataSize + i).toLong(),
isFollowing(list), profileImageSize))
}
} else {
for (i in 0..listSize - 1) {
for (i in 0 until listSize) {
val list = listLoaded[i]
data.add(listLoaded[i].toParcelable(accountKey, i.toLong(),
isFollowing(list), profileImageSize))

View File

@ -6,7 +6,6 @@ import android.content.Intent
import android.view.ActionProvider
import android.view.Menu
import android.view.SubMenu
import android.view.View
import org.mariotaku.twidere.TwidereConstants
import org.mariotaku.twidere.constant.IntentConstants.EXTRA_ACCOUNT
import org.mariotaku.twidere.model.AccountDetails
@ -25,10 +24,6 @@ class AccountActionProvider(
return true
}
override fun onCreateActionView(): View? {
return null
}
override fun onPrepareSubMenu(subMenu: SubMenu) {
subMenu.removeGroup(MENU_GROUP)
if (accounts == null) return
@ -51,6 +46,9 @@ class AccountActionProvider(
}
}
@Suppress("OverridingDeprecatedMember")
override fun onCreateActionView() = null
companion object {
val MENU_GROUP = 201

View File

@ -20,7 +20,7 @@ class ItemCounts(counts: Int) {
}
fun getItemStartPosition(countIndex: Int): Int {
return (0..countIndex - 1).sumBy { data[it] }
return (0 until countIndex).sumBy { data[it] }
}
val itemCount: Int get() = data.sum()

View File

@ -12,11 +12,11 @@ import org.mariotaku.twidere.model.UserKey
object ParcelableActivityUtils {
/**
* @param activity Activity for processing
* @param sources Source users
* *
* @param filtered Those ids will be removed from source_ids.
* *
* @param followingOnly Limit following users in sources
* @param followingOnly Limit following users in sources
* *
* @return true if source ids changed, false otherwise
*/

View File

@ -55,7 +55,7 @@ abstract class ComponentPickerPreference(context: Context, attrs: AttributeSet?
val values = arrayOfNulls<CharSequence>(infoListSize + 1)
entries[0] = noneEntry
values[0] = ""
for (i in 0..infoListSize - 1) {
for (i in 0 until infoListSize) {
val info = infoList[i]
entries[i + 1] = info.loadLabel(packageManager)
values[i + 1] = getComponentName(info).flattenToString()

View File

@ -338,7 +338,7 @@ class LengthyOperationsService : BaseIntentService("lengthy_operations") {
val stream = body.stream()
var response = upload.initUploadMedia(mediaType, length, null, null)
val segments = if (length == 0L) 0 else (length / BULK_SIZE + 1).toInt()
for (segmentIndex in 0..segments - 1) {
for (segmentIndex in 0 until segments) {
val currentBulkSize = Math.min(BULK_SIZE, length - segmentIndex * BULK_SIZE).toInt()
val bulk = SimpleBody(ContentType.OCTET_STREAM, null, currentBulkSize.toLong(),
stream)

View File

@ -404,7 +404,7 @@ class StreamingService : BaseService() {
}
override fun onDisconnectNotice(code: Int, reason: String?): Boolean {
disconnect();
disconnect()
return true
}

View File

@ -193,7 +193,7 @@ class UpdateStatusTask(
}
val sharedMedia = HashMap<UserKey, MediaUploadResult>()
for (i in 0..pending.length - 1) {
for (i in 0 until pending.length) {
val account = update.accounts[i]
// Skip upload if shared media found
val accountKey = account.key
@ -357,7 +357,7 @@ class UpdateStatusTask(
val ownerIds = ownersList.map {
it.id
}.toTypedArray()
for (i in 0..pendingUpdate.length - 1) {
for (i in 0 until pendingUpdate.length) {
val account = update.accounts[i]
val mediaIds: Array<String>?
when (account.type) {
@ -472,7 +472,7 @@ class UpdateStatusTask(
private fun statusShortenCallback(shortener: StatusShortenerInterface?,
pendingUpdate: PendingStatusUpdate, updateResult: UpdateStatusResult) {
if (shortener == null || !shortener.waitForService()) return
for (i in 0..pendingUpdate.length - 1) {
for (i in 0 until pendingUpdate.length) {
val shortenResult = pendingUpdate.statusShortenResults[i]
val status = updateResult.statuses[i]
if (shortenResult == null || status == null) continue
@ -483,7 +483,7 @@ class UpdateStatusTask(
private fun mediaUploadCallback(uploader: MediaUploaderInterface?,
pendingUpdate: PendingStatusUpdate, updateResult: UpdateStatusResult) {
if (uploader == null || !uploader.waitForService()) return
for (i in 0..pendingUpdate.length - 1) {
for (i in 0 until pendingUpdate.length) {
val uploadResult = pendingUpdate.mediaUploadResults[i]
val status = updateResult.statuses[i]
if (uploadResult == null || status == null) continue
@ -845,7 +845,7 @@ class UpdateStatusTask(
val stream = body.stream()
var response = upload.initUploadMedia(mediaType, length, mediaCategory, ownerIds)
val segments = if (length == 0L) 0 else (length / BULK_SIZE + 1).toInt()
for (segmentIndex in 0..segments - 1) {
for (segmentIndex in 0 until segments) {
val currentBulkSize = Math.min(BULK_SIZE.toLong(), length - segmentIndex * BULK_SIZE).toInt()
val bulk = SimpleBody(ContentType.OCTET_STREAM, null, currentBulkSize.toLong(),
stream)

View File

@ -122,6 +122,7 @@ class MarkMessageReadTask(
@SuppressLint("Recycle")
val cur = query(Messages.CONTENT_URI, Messages.COLUMNS,
where, whereArgs, OrderBy(Messages.LOCAL_TIMESTAMP, false).sql) ?: return null
@Suppress("ConvertTryFinallyToUseCall")
try {
if (cur.moveToFirst()) {
val indices = ObjectCursor.indicesFrom(cur, ParcelableMessage::class.java)

View File

@ -28,11 +28,7 @@ import android.text.style.DynamicDrawableSpan
* Created by mariotaku on 15/12/22.
*/
class EmojiSpan(private val drawable: Drawable) : DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BOTTOM) {
private val fontMetrics: Paint.FontMetrics
init {
this.fontMetrics = Paint.FontMetrics()
}
private val fontMetrics: Paint.FontMetrics = Paint.FontMetrics()
override fun getDrawable(): Drawable? {
return drawable

View File

@ -24,7 +24,9 @@ import org.mariotaku.twidere.provider.TwidereDataStore.Accounts
*/
@Suppress("deprecation")
fun migrateAccounts(am: AccountManager, db: SQLiteDatabase) {
val cur = db.query(Accounts.TABLE_NAME, Accounts.COLUMNS, null, null, null, null, null) ?: return
val cur = db.query(Accounts.TABLE_NAME, Accounts.COLUMNS, null, null,
null, null, null) ?: return
@Suppress("ConvertTryFinallyToUseCall")
try {
val indices = ObjectCursor.indicesFrom(cur, ParcelableCredentials::class.java)
cur.moveToFirst()

View File

@ -154,7 +154,7 @@ open class ContentScrollHandler<A>(
fun post(runnable: Runnable)
}
interface ContentListSupport<A> {
interface ContentListSupport<out A> {
val adapter: A?

View File

@ -621,6 +621,7 @@ object DataStoreUtils {
val where = Expression.equalsArgs(Filters.Users.USER_KEY)
val c = cr.query(Filters.Users.CONTENT_URI, arrayOf(SQLFunctions.COUNT()),
where.sql, arrayOf(userKey), null) ?: return false
@Suppress("ConvertTryFinallyToUseCall")
try {
if (c.moveToFirst()) {
return c.getLong(0) > 0
@ -812,6 +813,7 @@ object DataStoreUtils {
fun queryCount(cr: ContentResolver, uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val projection = arrayOf(SQLFunctions.COUNT())
val cur = cr.query(uri, projection, selection, selectionArgs, null) ?: return -1
@Suppress("ConvertTryFinallyToUseCall")
try {
if (cur.moveToFirst()) {
return cur.getInt(0)
@ -909,6 +911,7 @@ object DataStoreUtils {
val whereArgs = arrayOf(accountKey.toString(), statusId)
for (uri in DataStoreUtils.STATUSES_URIS) {
val cur = resolver.query(uri, Statuses.COLUMNS, where, whereArgs, null) ?: continue
@Suppress("ConvertTryFinallyToUseCall")
try {
if (cur.moveToFirst()) {
val indices = ObjectCursor.indicesFrom(cur, ParcelableStatus::class.java)
@ -956,6 +959,7 @@ object DataStoreUtils {
Expression.equalsArgs(Conversations.CONVERSATION_ID)).sql
val whereArgs = arrayOf(accountKey.toString(), conversationId)
val cur = resolver.query(Conversations.CONTENT_URI, Conversations.COLUMNS, where, whereArgs, null) ?: return null
@Suppress("ConvertTryFinallyToUseCall")
try {
if (cur.moveToFirst()) {
val indices = ObjectCursor.indicesFrom(cur, ParcelableMessageConversation::class.java)

View File

@ -62,7 +62,7 @@ class HtmlBuilder(
val sb = StringBuilder()
val linksSize = spanSpecs.size
val items = arrayOfNulls<SpanItem>(linksSize)
for (i in 0..linksSize - 1) {
for (i in 0 until linksSize) {
val spec = spanSpecs[i]
val start = spec.start
val end = spec.end

View File

@ -33,7 +33,7 @@ import org.mariotaku.twidere.model.util.ParcelableMediaUtils
/**
* Created by mariotaku on 15/4/6.
*/
class StatusAdapterLinkClickHandler<D>(context: Context, preferences: SharedPreferences) :
class StatusAdapterLinkClickHandler<out D>(context: Context, preferences: SharedPreferences) :
OnLinkClickHandler(context, null, preferences), Constants {
private var adapter: IStatusesAdapter<D>? = null

View File

@ -245,7 +245,7 @@ object Utils {
if (projection == null) return AllColumns()
val length = projection.size
val columns = arrayOfNulls<Column>(length)
for (i in 0..length - 1) {
for (i in 0 until length) {
columns[i] = Column(projection[i])
}
return Columns(*columns)

View File

@ -47,6 +47,7 @@ object FilterQueryBuilder {
textPlain, quotedTextPlain, spans, quotedSpans, source, quotedSource, retweetedByKey,
quotedUserKey, true)
val cur = cr.rawQuery(query.first, query.second) ?: return false
@Suppress("ConvertTryFinallyToUseCall")
try {
return cur.moveToFirst() && cur.getInt(0) != 0
} finally {

View File

@ -144,7 +144,7 @@ class TwidereDns(context: Context, private val preferences: SharedPreferences) :
private fun addLogSplit(logger: TimingLogger, host: String, message: String, depth: Int) {
if (BuildConfig.DEBUG) return
val sb = StringBuilder()
for (i in 0..depth - 1) {
for (i in 0 until depth) {
sb.append(">")
}
sb.append(" ")

View File

@ -272,6 +272,7 @@ class ContentNotificationManager(
val unreadHaving = Expression.greaterThan(Conversations.UNREAD_COUNT, 0)
val cur = cr.getUnreadMessagesEntriesCursor(projection, arrayOf(accountKey),
extraHaving = unreadHaving) ?: return
@Suppress("ConvertTryFinallyToUseCall")
try {
if (cur.isEmpty) return

View File

@ -43,6 +43,7 @@ abstract class FileBasedDraftsSyncAction<RemoteFileInfo>(val context: Context) :
val localDrafts = run {
val cur = context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, null, null, null)!!
@Suppress("ConvertTryFinallyToUseCall")
try {
val indices = ObjectCursor.indicesFrom(cur, Draft::class.java)
return@run cur.map(indices)
@ -157,6 +158,7 @@ abstract class FileBasedDraftsSyncAction<RemoteFileInfo>(val context: Context) :
snapshotsListFile.writer().use { writer ->
val cur = context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, null, null, null)!!
@Suppress("ConvertTryFinallyToUseCall")
try {
val indices = ObjectCursor.indicesFrom(cur, Draft::class.java)
cur.map(indices).map { it.unique_id_non_null }.forEach { line ->

View File

@ -121,7 +121,7 @@ class CardPollViewController : ContainerView.ViewController() {
val hasChoice = selectedChoice != -1
val isMyPoll = status.account_key == status.user_key
val showResult = countsAreFinal || isMyPoll || hasChoice
for (i in 0..choicesCount - 1) {
for (i in 0 until choicesCount) {
val choiceIndex = i + 1
votesSum += card.getAsInteger("choice${choiceIndex}_count", 0)
}
@ -178,7 +178,7 @@ class CardPollViewController : ContainerView.ViewController() {
val color = ContextCompat.getColor(context, R.color.material_light_blue_a200)
val radius = context.resources.getDimension(R.dimen.element_spacing_small)
for (i in 0..choicesCount - 1) {
for (i in 0 until choicesCount) {
val pollItem = view.pollContainer.getChildAt(i)
val choicePercentView: TextView = pollItem.findViewById(R.id.choice_percent)

View File

@ -42,25 +42,17 @@ class UserListViewHolder(
private val adapter: IUserListsAdapter<*>
) : ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener {
private val itemContent: ColorLabelRelativeLayout
private val profileImageView: ProfileImageView
private val nameView: TextView
private val createdByView: TextView
private val descriptionView: TextView
private val membersCountView: TextView
private val subscribersCountView: TextView
private val itemContent: ColorLabelRelativeLayout = itemView.itemContent
private val profileImageView: ProfileImageView = itemView.profileImage
private val nameView: TextView = itemView.name
private val createdByView: TextView = itemView.createdBy
private val descriptionView: TextView = itemView.description
private val membersCountView: TextView = itemView.membersCount
private val subscribersCountView: TextView = itemView.subscribersCount
private var userListClickListener: IUserListsAdapter.UserListClickListener? = null
init {
itemContent = itemView.itemContent
profileImageView = itemView.profileImage
nameView = itemView.name
createdByView = itemView.createdBy
descriptionView = itemView.description
membersCountView = itemView.membersCount
subscribersCountView = itemView.subscribersCount
profileImageView.style = adapter.profileImageStyle
}

View File

@ -79,7 +79,7 @@ class MessageViewHolder(itemView: View, adapter: MessagesConversationAdapter) :
var nonSpaceCount = 0
var curPos = 0
message.spans?.forEach { span ->
nonSpaceCount += text.nonSpaceCount(curPos..span.start - 1)
nonSpaceCount += text.nonSpaceCount(curPos until span.start)
if (message.media?.firstOrNull { media -> span.link == media.url } != null) {
// Skip if span is hidden
span.type = SpanItem.SpanType.HIDE