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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -38,8 +38,11 @@ import java.util.List;
@ParcelablePlease @ParcelablePlease
public class UserKey implements Comparable<UserKey>, Parcelable { public class UserKey implements Comparable<UserKey>, Parcelable {
@NonNull
private static final String ID_PLACEHOLDER = "#placeholder"; private static final String ID_PLACEHOLDER = "#placeholder";
@NonNull
public static final UserKey SELF = new UserKey("#self#", "#self#"); public static final UserKey SELF = new UserKey("#self#", "#self#");
@NonNull
public static final UserKey INVALID = new UserKey("#invalid#", "#invalid#"); public static final UserKey INVALID = new UserKey("#invalid#", "#invalid#");
public static final Creator<UserKey> CREATOR = new Creator<UserKey>() { 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.bluelinelabs.logansquare.annotation.JsonObject;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease; import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import org.mariotaku.microblog.library.twitter.model.DMResponse;
/** /**
* Created by mariotaku on 2017/2/13. * Created by mariotaku on 2017/2/13.
*/ */

View File

@ -13,11 +13,11 @@ public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); 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() { stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override @Override
public void onLayoutInflated(WatchViewStub stub) { 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.app.Application;
import android.os.Build; import android.os.Build;
import android.support.annotation.NonNull;
import android.webkit.WebView; import android.webkit.WebView;
import com.facebook.stetho.DumperPluginsProvider; import com.facebook.stetho.DumperPluginsProvider;
@ -56,7 +57,7 @@ public class DebugModeUtils {
builder.addNetworkInterceptor(new Interceptor() { builder.addNetworkInterceptor(new Interceptor() {
@Override @Override
public Response intercept(Chain chain) throws IOException { public Response intercept(@NonNull Chain chain) throws IOException {
if (chain.request().tag() == NoIntercept.INSTANCE) { if (chain.request().tag() == NoIntercept.INSTANCE) {
return chain.proceed(chain.request()); return chain.proceed(chain.request());
} }

View File

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

View File

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

View File

@ -26,6 +26,7 @@ package io.nayuki.qrcodegen;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; 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> * from 1 to 40, all 4 error correction levels, and only 3 character encoding modes.</p>
*/ */
public final class QrCode { public final class QrCode {
/*---- Public static factory functions ----*/ /*---- Public static factory functions ----*/
/** /**
* Returns a QR Code symbol representing the specified Unicode text string at the specified error correction level. * 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 * 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); List<QrSegment> segs = QrSegment.makeSegments(text);
return encodeSegments(segs, ecl); return encodeSegments(segs, ecl);
} }
/** /**
* Returns a QR Code symbol representing the specified binary data string at the specified error correction level. * 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 * 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) { public static QrCode encodeBinary(@NonNull byte[] data, @NonNull Ecc ecl) {
QrSegment seg = QrSegment.makeBytes(data); 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 * 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. * 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) { public static QrCode encodeSegments(List<QrSegment> segs, Ecc ecl) {
return encodeSegments(segs, ecl, 1, 40, -1, true); return encodeSegments(segs, ecl, 1, 40, -1, true);
} }
/** /**
* Returns a QR Code symbol representing the specified data segments with the specified encoding parameters. * 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. * 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) { 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) if (!(1 <= minVersion && minVersion <= maxVersion && maxVersion <= 40) || mask < -1 || mask > 7)
throw new IllegalArgumentException("Invalid value"); throw new IllegalArgumentException("Invalid value");
// Find the minimal version number to use // Find the minimal version number to use
int version, dataUsedBits; int version, dataUsedBits;
for (version = minVersion; ; version++) { for (version = minVersion; ; version++) {
@ -123,13 +124,13 @@ public final class QrCode {
} }
if (dataUsedBits == -1) if (dataUsedBits == -1)
throw new AssertionError(); throw new AssertionError();
// Increase the error correction level while the data still fits in the current version number // Increase the error correction level while the data still fits in the current version number
for (Ecc newEcl : Ecc.values()) { for (Ecc newEcl : Ecc.values()) {
if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8)
ecl = newEcl; ecl = newEcl;
} }
// Create the data bit string by concatenating all segments // Create the data bit string by concatenating all segments
int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; int dataCapacityBits = getNumDataCodewords(version, ecl) * 8;
BitBuffer bb = new BitBuffer(); BitBuffer bb = new BitBuffer();
@ -138,17 +139,17 @@ public final class QrCode {
bb.appendBits(seg.numChars, seg.mode.numCharCountBits(version)); bb.appendBits(seg.numChars, seg.mode.numCharCountBits(version));
bb.appendData(seg); bb.appendData(seg);
} }
// Add terminator and pad up to a byte if applicable // Add terminator and pad up to a byte if applicable
bb.appendBits(0, Math.min(4, dataCapacityBits - bb.bitLength())); bb.appendBits(0, Math.min(4, dataCapacityBits - bb.bitLength()));
bb.appendBits(0, (8 - bb.bitLength() % 8) % 8); bb.appendBits(0, (8 - bb.bitLength() % 8) % 8);
// Pad with alternate bytes until data capacity is reached // Pad with alternate bytes until data capacity is reached
for (int padByte = 0xEC; bb.bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11) for (int padByte = 0xEC; bb.bitLength() < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
bb.appendBits(padByte, 8); bb.appendBits(padByte, 8);
if (bb.bitLength() % 8 != 0) if (bb.bitLength() % 8 != 0)
throw new AssertionError(); throw new AssertionError();
// Create the QR Code symbol // Create the QR Code symbol
return new QrCode(version, ecl, bb.getBytes(), mask); return new QrCode(version, ecl, bb.getBytes(), mask);
} }
@ -156,24 +157,24 @@ public final class QrCode {
/*---- Instance fields ----*/ /*---- Instance fields ----*/
// Public immutable scalar parameters // Public immutable scalar parameters
/** This QR Code symbol's version number, which is always between 1 and 40 (inclusive). */ /** This QR Code symbol's version number, which is always between 1 and 40 (inclusive). */
public final int version; public final int version;
/** The width and height of this QR Code symbol, measured in modules. /** 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. */ * Always equal to version &times; 4 + 17, in the range 21 to 177. */
public final int size; public final int size;
/** The error correction level used in this QR Code symbol. Never {@code null}. */ /** The error correction level used in this QR Code symbol. Never {@code null}. */
public final Ecc errorCorrectionLevel; 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). /** 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 * 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. */ * (mask = -1), the resulting object will still have a mask value between 0 and 7. */
public final int mask; public final int mask;
// Private grids of modules/pixels (conceptually immutable) // Private grids of modules/pixels (conceptually immutable)
private boolean[][] modules; // The modules of this QR Code symbol (false = white, true = black) 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 private boolean[][] isFunction; // Indicates function modules that are not subjected to masking
@ -181,7 +182,7 @@ public final class QrCode {
/*---- Constructors ----*/ /*---- Constructors ----*/
/** /**
* Creates a new QR Code symbol with the specified version number, error correction level, binary data array, and mask number. * 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. * <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; errorCorrectionLevel = ecl;
modules = new boolean[size][size]; // Entirely white grid modules = new boolean[size][size]; // Entirely white grid
isFunction = new boolean[size][size]; isFunction = new boolean[size][size];
// Draw function patterns, draw all codewords, do masking // Draw function patterns, draw all codewords, do masking
drawFunctionPatterns(); drawFunctionPatterns();
byte[] allCodewords = appendErrorCorrection(dataCodewords); byte[] allCodewords = appendErrorCorrection(dataCodewords);
drawCodewords(allCodewords); drawCodewords(allCodewords);
this.mask = handleConstructorMasking(mask); this.mask = handleConstructorMasking(mask);
} }
/** /**
* Creates a new QR Code symbol based on the specified existing object, but with a potentially * 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 * different mask pattern. The version, error correction level, codewords, etc. of the newly
@ -226,18 +227,18 @@ public final class QrCode {
// Check arguments // Check arguments
if (mask < -1 || mask > 7) if (mask < -1 || mask > 7)
throw new IllegalArgumentException("Mask value out of range"); throw new IllegalArgumentException("Mask value out of range");
// Copy scalar fields // Copy scalar fields
version = qr.version; version = qr.version;
size = qr.size; size = qr.size;
errorCorrectionLevel = qr.errorCorrectionLevel; errorCorrectionLevel = qr.errorCorrectionLevel;
// Handle grid fields // Handle grid fields
isFunction = qr.isFunction; // Shallow copy because the data is read-only isFunction = qr.isFunction; // Shallow copy because the data is read-only
modules = qr.modules.clone(); // Deep copy modules = qr.modules.clone(); // Deep copy
for (int i = 0; i < modules.length; i++) for (int i = 0; i < modules.length; i++)
modules[i] = modules[i].clone(); modules[i] = modules[i].clone();
// Handle masking // Handle masking
applyMask(qr.mask); // Undo old mask applyMask(qr.mask); // Undo old mask
this.mask = handleConstructorMasking(mask); this.mask = handleConstructorMasking(mask);
@ -246,7 +247,7 @@ public final class QrCode {
/*---- Public instance methods ----*/ /*---- 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 * 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. * 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 helper methods for constructor: Drawing function modules ----*/
private void drawFunctionPatterns() { private void drawFunctionPatterns() {
// Draw horizontal and vertical timing patterns // Draw horizontal and vertical timing patterns
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
setFunctionModule(6, i, i % 2 == 0); setFunctionModule(6, i, i % 2 == 0);
setFunctionModule(i, 6, i % 2 == 0); setFunctionModule(i, 6, i % 2 == 0);
} }
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
drawFinderPattern(3, 3); drawFinderPattern(3, 3);
drawFinderPattern(size - 4, 3); drawFinderPattern(size - 4, 3);
drawFinderPattern(3, size - 4); drawFinderPattern(3, size - 4);
// Draw numerous alignment patterns // Draw numerous alignment patterns
int[] alignPatPos = getAlignmentPatternPositions(version); int[] alignPatPos = getAlignmentPatternPositions(version);
int numAlign = alignPatPos.length; int numAlign = alignPatPos.length;
@ -286,13 +287,13 @@ public final class QrCode {
drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
} }
} }
// Draw configuration data // Draw configuration data
drawFormatBits(0); // Dummy mask value; overwritten later in the constructor drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
drawVersion(); drawVersion();
} }
// Draws two copies of the format bits (with its own error correction code) // 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. // based on the given mask and this object's error correction level field.
private void drawFormatBits(int mask) { private void drawFormatBits(int mask) {
@ -305,7 +306,7 @@ public final class QrCode {
data ^= 0x5412; // uint15 data ^= 0x5412; // uint15
if (data >>> 15 != 0) if (data >>> 15 != 0)
throw new AssertionError(); throw new AssertionError();
// Draw first copy // Draw first copy
for (int i = 0; i <= 5; i++) for (int i = 0; i <= 5; i++)
setFunctionModule(8, i, ((data >>> i) & 1) != 0); setFunctionModule(8, i, ((data >>> i) & 1) != 0);
@ -314,7 +315,7 @@ public final class QrCode {
setFunctionModule(7, 8, ((data >>> 8) & 1) != 0); setFunctionModule(7, 8, ((data >>> 8) & 1) != 0);
for (int i = 9; i < 15; i++) for (int i = 9; i < 15; i++)
setFunctionModule(14 - i, 8, ((data >>> i) & 1) != 0); setFunctionModule(14 - i, 8, ((data >>> i) & 1) != 0);
// Draw second copy // Draw second copy
for (int i = 0; i <= 7; i++) for (int i = 0; i <= 7; i++)
setFunctionModule(size - 1 - i, 8, ((data >>> i) & 1) != 0); 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 - 15 + i, ((data >>> i) & 1) != 0);
setFunctionModule(8, size - 8, true); setFunctionModule(8, size - 8, true);
} }
// Draws two copies of the version bits (with its own error correction code), // 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). // based on this object's version field (which only has an effect for 7 <= version <= 40).
private void drawVersion() { private void drawVersion() {
if (version < 7) if (version < 7)
return; return;
// Calculate error correction code and pack bits // Calculate error correction code and pack bits
int rem = version; // version is uint6, in the range [7, 40] int rem = version; // version is uint6, in the range [7, 40]
for (int i = 0; i < 12; i++) for (int i = 0; i < 12; i++)
@ -337,7 +338,7 @@ public final class QrCode {
int data = version << 12 | rem; // uint18 int data = version << 12 | rem; // uint18
if (data >>> 18 != 0) if (data >>> 18 != 0)
throw new AssertionError(); throw new AssertionError();
// Draw two copies // Draw two copies
for (int i = 0; i < 18; i++) { for (int i = 0; i < 18; i++) {
boolean bit = ((data >>> i) & 1) != 0; boolean bit = ((data >>> i) & 1) != 0;
@ -346,8 +347,8 @@ public final class QrCode {
setFunctionModule(b, a, bit); setFunctionModule(b, a, bit);
} }
} }
// Draws a 9*9 finder pattern including the border separator, with the center module at (x, y). // Draws a 9*9 finder pattern including the border separator, with the center module at (x, y).
private void drawFinderPattern(int x, int y) { private void drawFinderPattern(int x, int y) {
for (int i = -4; i <= 4; i++) { 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). // Draws a 5*5 alignment pattern, with the center module at (x, y).
private void drawAlignmentPattern(int x, int y) { private void drawAlignmentPattern(int x, int y) {
for (int i = -2; i <= 2; i++) { 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); 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. // Sets the color of a module and marks it as a function module.
// Only used by the constructor. Coordinates must be in range. // Only used by the constructor. Coordinates must be in range.
private void setFunctionModule(int x, int y, boolean isBlack) { 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 ----*/ /*---- Private helper methods for constructor: Codewords and masking ----*/
// Returns a new byte string representing the given data with the appropriate error correction // 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. // codewords appended to it, based on this object's version and error correction level.
private byte[] appendErrorCorrection(byte[] data) { private byte[] appendErrorCorrection(byte[] data) {
if (data.length != getNumDataCodewords(version, errorCorrectionLevel)) if (data.length != getNumDataCodewords(version, errorCorrectionLevel))
throw new IllegalArgumentException(); throw new IllegalArgumentException();
// Calculate parameter numbers // Calculate parameter numbers
int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[errorCorrectionLevel.ordinal()][version]; int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[errorCorrectionLevel.ordinal()][version];
int blockEccLen = ECC_CODEWORDS_PER_BLOCK[errorCorrectionLevel.ordinal()][version]; int blockEccLen = ECC_CODEWORDS_PER_BLOCK[errorCorrectionLevel.ordinal()][version];
int rawCodewords = getNumRawDataModules(version) / 8; int rawCodewords = getNumRawDataModules(version) / 8;
int numShortBlocks = numBlocks - rawCodewords % numBlocks; int numShortBlocks = numBlocks - rawCodewords % numBlocks;
int shortBlockLen = rawCodewords / numBlocks; int shortBlockLen = rawCodewords / numBlocks;
// Split data into blocks and append ECC to each block // Split data into blocks and append ECC to each block
byte[][] blocks = new byte[numBlocks][]; byte[][] blocks = new byte[numBlocks][];
ReedSolomonGenerator rs = new ReedSolomonGenerator(blockEccLen); ReedSolomonGenerator rs = new ReedSolomonGenerator(blockEccLen);
@ -404,7 +405,7 @@ public final class QrCode {
System.arraycopy(ecc, 0, block, block.length - blockEccLen, ecc.length); System.arraycopy(ecc, 0, block, block.length - blockEccLen, ecc.length);
blocks[i] = block; blocks[i] = block;
} }
// Interleave (not concatenate) the bytes from every block into a single sequence // Interleave (not concatenate) the bytes from every block into a single sequence
byte[] result = new byte[rawCodewords]; byte[] result = new byte[rawCodewords];
for (int i = 0, k = 0; i < blocks[0].length; i++) { for (int i = 0, k = 0; i < blocks[0].length; i++) {
@ -418,14 +419,14 @@ public final class QrCode {
} }
return result; return result;
} }
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire // 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. // data area of this QR Code symbol. Function modules need to be marked off before this is called.
private void drawCodewords(@NonNull byte[] data) { private void drawCodewords(@NonNull byte[] data) {
if (data.length != getNumRawDataModules(version) / 8) if (data.length != getNumRawDataModules(version) / 8)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
int i = 0; // Bit index into the data int i = 0; // Bit index into the data
// Do the funny zigzag scan // Do the funny zigzag scan
for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair 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) if (i != data.length * 8)
throw new AssertionError(); throw new AssertionError();
} }
// XORs the data modules in this QR Code with the given mask pattern. Due to XOR's mathematical // 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. // 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 // 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 // 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. // 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. // 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 applyMask(mask); // Apply the final choice of mask
return mask; // The caller shall assign this value to the final-declared field 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. // 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. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private int getPenaltyScore() { private int getPenaltyScore() {
int result = 0; int result = 0;
// Adjacent modules in row having same color // Adjacent modules in row having same color
for (int y = 0; y < size; y++) { for (int y = 0; y < size; y++) {
boolean colorX = false; boolean colorX = false;
@ -539,7 +540,7 @@ public final class QrCode {
} }
} }
} }
// 2*2 blocks of modules having same color // 2*2 blocks of modules having same color
for (int y = 0; y < size - 1; y++) { for (int y = 0; y < size - 1; y++) {
for (int x = 0; x < size - 1; x++) { for (int x = 0; x < size - 1; x++) {
@ -550,7 +551,7 @@ public final class QrCode {
result += PENALTY_N2; result += PENALTY_N2;
} }
} }
// Finder-like pattern in rows // Finder-like pattern in rows
for (int y = 0; y < size; y++) { for (int y = 0; y < size; y++) {
for (int x = 0, bits = 0; x < size; x++) { for (int x = 0, bits = 0; x < size; x++) {
@ -567,7 +568,7 @@ public final class QrCode {
result += PENALTY_N3; result += PENALTY_N3;
} }
} }
// Balance of black and white modules // Balance of black and white modules
int black = 0; int black = 0;
for (boolean[] row : modules) { for (boolean[] row : modules) {
@ -586,7 +587,7 @@ public final class QrCode {
/*---- Private static helper functions ----*/ /*---- Private static helper functions ----*/
// Returns a set of positions of the alignment patterns in ascending order. These positions are // 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). // 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. // 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 step = (ver * 4 + numAlign * 2 + 1) / (2 * numAlign - 2) * 2; // ceil((size - 13) / (2*numAlign - 2)) * 2
else // C-C-C-Combo breaker! else // C-C-C-Combo breaker!
step = 26; step = 26;
int[] result = new int[numAlign]; int[] result = new int[numAlign];
int size = ver * 4 + 17; int size = ver * 4 + 17;
result[0] = 6; result[0] = 6;
@ -611,15 +612,15 @@ public final class QrCode {
return result; return result;
} }
} }
// Returns the number of data bits that can be stored in a QR Code of the given version number, after // 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. // 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. // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
private static int getNumRawDataModules(int ver) { private static int getNumRawDataModules(int ver) {
if (ver < 1 || ver > 40) if (ver < 1 || ver > 40)
throw new IllegalArgumentException("Version number out of range"); throw new IllegalArgumentException("Version number out of range");
int size = ver * 4 + 17; int size = ver * 4 + 17;
int result = size * size; // Number of modules in the whole QR symbol square int result = size * size; // Number of modules in the whole QR symbol square
result -= 64 * 3; // Subtract the three finders with separators result -= 64 * 3; // Subtract the three finders with separators
@ -636,8 +637,8 @@ public final class QrCode {
} }
return result; return result;
} }
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any // 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. // 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. // 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 ----*/ /*---- Private tables of constants ----*/
// For use in getPenaltyScore(), when evaluating which mask is best. // For use in getPenaltyScore(), when evaluating which mask is best.
private static final int PENALTY_N1 = 3; private static final int PENALTY_N1 = 3;
private static final int PENALTY_N2 = 3; private static final int PENALTY_N2 = 3;
private static final int PENALTY_N3 = 40; private static final int PENALTY_N3 = 40;
private static final int PENALTY_N4 = 10; private static final int PENALTY_N4 = 10;
private static final byte[][] ECC_CODEWORDS_PER_BLOCK = { private static final byte[][] ECC_CODEWORDS_PER_BLOCK = {
// Version: (note that index 0 is for padding, and is set to an illegal value) // 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 //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, 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 {-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 = { private static final byte[][] NUM_ERROR_CORRECTION_BLOCKS = {
// Version: (note that index 0 is for padding, and is set to an illegal value) // 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 //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 ----*/ /*---- Public helper enumeration ----*/
/** /**
* Represents the error correction level used in a QR Code symbol. * 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, // These enum constants must be declared in ascending order of error protection,
// for the sake of the implicit ordinal() method and values() function. // for the sake of the implicit ordinal() method and values() function.
LOW(1), MEDIUM(0), QUARTILE(3), HIGH(2); LOW(1), MEDIUM(0), QUARTILE(3), HIGH(2);
// In the range 0 to 3 (unsigned 2-bit integer). // In the range 0 to 3 (unsigned 2-bit integer).
final int formatBits; final int formatBits;
// Constructor. // Constructor.
private Ecc(int fb) { Ecc(int fb) {
formatBits = fb; formatBits = fb;
} }
} }
@ -699,7 +700,7 @@ public final class QrCode {
/*---- Private helper class ----*/ /*---- Private helper class ----*/
/** /**
* Computes the Reed-Solomon error correction codewords for a sequence of data codewords * 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. * 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 { private static final class ReedSolomonGenerator {
/*-- Immutable field --*/ /*-- Immutable field --*/
// Coefficients of the divisor polynomial, stored from highest to lowest power, excluding the leading term which // 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}. // 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; private final byte[] coefficients;
/*-- Constructor --*/ /*-- Constructor --*/
/** /**
* Creates a Reed-Solomon ECC generator for the specified degree. This could be implemented * 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. * 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) { public ReedSolomonGenerator(int degree) {
if (degree < 1 || degree > 255) if (degree < 1 || degree > 255)
throw new IllegalArgumentException("Degree out of range"); throw new IllegalArgumentException("Degree out of range");
// Start with the monomial x^0 // Start with the monomial x^0
coefficients = new byte[degree]; coefficients = new byte[degree];
coefficients[degree - 1] = 1; coefficients[degree - 1] = 1;
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-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. // 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). // 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 --*/ /*-- Method --*/
/** /**
* Computes and returns the Reed-Solomon error correction codewords for the specified sequence of data codewords. * 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). * 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 --*/ /*-- Static function --*/
// Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result // 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. // 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) { private static int multiply(int x, int y) {
@ -786,7 +787,7 @@ public final class QrCode {
throw new AssertionError(); throw new AssertionError();
return z; return z;
} }
} }
} }

View File

@ -254,7 +254,7 @@ public final class QrSegment {
/*-- Constructor --*/ /*-- Constructor --*/
private Mode(int mode, int... ccbits) { Mode(int mode, int... ccbits) {
this.modeBits = mode; this.modeBits = mode;
numBitsCharCount = ccbits; 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) { public View getView(final int position, final View convertView, final ViewGroup parent) {
final View view = convertView != null ? convertView : mInflater.inflate( final View view = convertView != null ? convertView : mInflater.inflate(
android.R.layout.simple_list_item_1, null); 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()); text.setText(getItem(position).getName());
return view; return view;
} }

View File

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

View File

@ -200,7 +200,7 @@ public final class DataExportImportTypeSelectorDialogFragment extends BaseDialog
@Override @Override
public View getView(final int position, @Nullable final View convertView, final ViewGroup parent) { public View getView(final int position, @Nullable final View convertView, final ViewGroup parent) {
final View view = super.getView(position, convertView, 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); text1.setText(getItem(position).title);
view.setEnabled(isEnabled(position)); view.setEnabled(isEnabled(position));
return view; return view;

View File

@ -20,8 +20,6 @@ import android.os.Bundle;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.preference.ListPreference; import android.support.v7.preference.ListPreference;
import org.mariotaku.twidere.util.TwidereArrayUtils;
public class ThemedListPreferenceDialogFragmentCompat extends ThemedPreferenceDialogFragmentCompat { public class ThemedListPreferenceDialogFragmentCompat extends ThemedPreferenceDialogFragmentCompat {
private int mClickedDialogEntryIndex; 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.model.util.UserKeyCursorFieldConverter;
import org.mariotaku.twidere.provider.TwidereDataStore.Accounts; import org.mariotaku.twidere.provider.TwidereDataStore.Accounts;
@SuppressWarnings("DeprecatedIsStillUsed")
@CursorObject @CursorObject
@Deprecated @Deprecated
public class ParcelableAccount { public class ParcelableAccount {

View File

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

View File

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

View File

@ -209,13 +209,13 @@ public class SeekBarDialogPreference extends DialogPreference implements IDialog
super.onBindDialogView(view); super.onBindDialogView(view);
final SeekBarDialogPreference preference = (SeekBarDialogPreference) getPreference(); final SeekBarDialogPreference preference = (SeekBarDialogPreference) getPreference();
final CharSequence message = preference.getDialogMessage(); 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.setText(message);
dialogMessageText.setVisibility(TextUtils.isEmpty(message) ? View.GONE : View.VISIBLE); 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() { mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override @Override
public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) { 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); final View view = inflater.inflate(R.layout.dialog_theme_background_preference, listViewParent);
((ViewGroup) view.findViewById(R.id.list_container)).addView(listView); ((ViewGroup) view.findViewById(R.id.list_container)).addView(listView);
mAlphaContainer = view.findViewById(R.id.alpha_container); 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.setMax(MAX_ALPHA - MIN_ALPHA);
mAlphaSlider.setProgress(preferences.getInt(KEY_THEME_BACKGROUND_ALPHA, DEFAULT_THEME_BACKGROUND_ALPHA) - MIN_ALPHA); mAlphaSlider.setProgress(preferences.getInt(KEY_THEME_BACKGROUND_ALPHA, DEFAULT_THEME_BACKGROUND_ALPHA) - MIN_ALPHA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

View File

@ -94,7 +94,7 @@ public class MicroBlogAPIFactory implements TwidereConstants {
@NonNull @NonNull
public static String getApiBaseUrl(@NonNull String format, @Nullable final String domain) { 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; final String baseUrl;
if (!matcher.find()) { if (!matcher.find()) {
// For backward compatibility // For backward compatibility

View File

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

View File

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

View File

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

View File

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

View File

@ -25,7 +25,6 @@ import android.os.Parcel;
import android.os.Parcelable; import android.os.Parcelable;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat; import android.support.v4.content.ContextCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.MotionEvent; import android.view.MotionEvent;
@ -213,11 +212,11 @@ public class LinePageIndicator extends View implements PagerIndicator {
} }
@Override @Override
public boolean onTouchEvent(@NonNull final android.view.MotionEvent ev) { public boolean onTouchEvent(@NonNull final MotionEvent ev) {
if (super.onTouchEvent(ev)) return true; if (super.onTouchEvent(ev)) return true;
if (mViewPager == null || mViewPager.getAdapter().getCount() == 0) return false; 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) { switch (action) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getPointerId(0); mActivePointerId = ev.getPointerId(0);
@ -273,21 +272,21 @@ public class LinePageIndicator extends View implements PagerIndicator {
} }
break; break;
case MotionEventCompat.ACTION_POINTER_DOWN: { case MotionEvent.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev); final int index = ev.getActionIndex();
mLastMotionX = ev.getX(index); mLastMotionX = ev.getX(index);
mActivePointerId = ev.getPointerId(index); mActivePointerId = ev.getPointerId(index);
break; break;
} }
case MotionEventCompat.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_UP:
final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerIndex = ev.getActionIndex();
final int pointerId = ev.getPointerId(pointerIndex); final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) { if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0; final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = ev.getPointerId(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex);
} }
mLastMotionX = MotionEventCompat.getX(ev, ev.findPointerIndex(mActivePointerId)); mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId));
break; 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) { 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 ItemLayout layout = (ItemLayout) inflater.inflate(R.layout.layout_tab_item, this, false);
final ImageView tabIcon = (ImageView) layout.findViewById(R.id.tab_icon); final ImageView tabIcon = layout.findViewById(R.id.tab_icon);
final BadgeView badgeView = (BadgeView) layout.findViewById(R.id.unread_indicator); final BadgeView badgeView = layout.findViewById(R.id.unread_indicator);
final TextView tabLabel = (TextView) layout.findViewById(R.id.tab_label); final TextView tabLabel = layout.findViewById(R.id.tab_label);
layout.setStripColor(stripColor); layout.setStripColor(stripColor);
layout.setStripHeight(stripHeight); layout.setStripHeight(stripHeight);
@ -500,9 +500,9 @@ public class TabPagerIndicator extends RecyclerView implements PagerIndicator, C
this.itemView = (ItemLayout) itemView; this.itemView = (ItemLayout) itemView;
itemView.setOnClickListener(this); itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this); itemView.setOnLongClickListener(this);
iconView = (ImageView) itemView.findViewById(R.id.tab_icon); iconView = itemView.findViewById(R.id.tab_icon);
labelView = (TextView) itemView.findViewById(R.id.tab_label); labelView = itemView.findViewById(R.id.tab_label);
badgeView = (BadgeView) itemView.findViewById(R.id.unread_indicator); badgeView = itemView.findViewById(R.id.unread_indicator);
} }
@Override @Override

View File

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

View File

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

View File

@ -21,7 +21,7 @@ package org.mariotaku.twidere.extension
import android.net.Uri 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?) { fun Uri.Builder.appendQueryParameterIgnoreNull(key: String, value: String?) {
if (value == null) return if (value == null) return

View File

@ -165,7 +165,7 @@ fun FiltersData.parse(parser: XmlPullParser) {
} }
fun FiltersData.addAll(data: FiltersData, ignoreDuplicates: Boolean = false): Boolean { fun FiltersData.addAll(data: FiltersData, ignoreDuplicates: Boolean = false): Boolean {
var changed: Boolean = false var changed = false
initFields() initFields()
if (data.users != null) { if (data.users != null) {
changed = changed or this.users.addAllEnhanced(collection = data.users, ignoreDuplicates = ignoreDuplicates) 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 if (larger != null) return larger
} }
val profileImage = profileImageUrlHttps ?: profileImageUrl 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. * Created by mariotaku on 2017/4/19.
*/ */
val Application.sourceHtml: String get() { val Application.sourceHtml: String
val name = this.name ?: return "" get() {
val website = this.website ?: return name.let(HtmlEscapeHelper::escape).orEmpty() val name = this.name ?: return ""
return "<a href='${HtmlEscapeHelper.escape(website)}'>${HtmlEscapeHelper.escape(name)}</a>" 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?) { override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState) super.onActivityCreated(savedInstanceState)
val view = webView val view = webView!!
view!!.setWebViewClient(createWebViewClient()) view.webViewClient = createWebViewClient()
val settings = view.settings view.settings.apply {
settings.builtInZoomControls = true builtInZoomControls = true
settings.javaScriptEnabled = true javaScriptEnabled = true
WebSettingsSupport.setAllowUniversalAccessFromFileURLs(settings, true) WebSettingsSupport.setAllowUniversalAccessFromFileURLs(this, true)
}
} }

View File

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

View File

@ -79,7 +79,7 @@ class TrendsSuggestionsFragment : AbsContentListViewFragment<TrendsAdapter>(), L
val uri = CachedTrends.Local.CONTENT_URI val uri = CachedTrends.Local.CONTENT_URI
val loaderWhere = Expression.and(Expression.equalsArgs(CachedTrends.ACCOUNT_KEY), val loaderWhere = Expression.and(Expression.equalsArgs(CachedTrends.ACCOUNT_KEY),
Expression.equalsArgs(CachedTrends.WOEID)).sql 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) 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 Expression.equalsArgs(Conversations.PARTICIPANT_KEYS)).sql
val whereArgs = arrayOf(accountKey.toString(), participantKeys.sorted().joinToString(",")) val whereArgs = arrayOf(accountKey.toString(), participantKeys.sorted().joinToString(","))
val cur = resolver.query(Conversations.CONTENT_URI, Conversations.COLUMNS, where, whereArgs, null) ?: return null val cur = resolver.query(Conversations.CONTENT_URI, Conversations.COLUMNS, where, whereArgs, null) ?: return null
@Suppress("ConvertTryFinallyToUseCall")
try { try {
if (cur.moveToFirst()) { if (cur.moveToFirst()) {
val indices = ObjectCursor.indicesFrom(cur, ParcelableMessageConversation::class.java) 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, resolver.query(CachedUsers.CONTENT_URI, CachedUsers.COLUMNS, where.sql,
whereArgs, null)?.let { cur -> whereArgs, null)?.let { cur ->
@Suppress("ConvertTryFinallyToUseCall")
try { try {
cur.moveToFirst() cur.moveToFirst()
val indices = ObjectCursor.indicesFrom(cur, ParcelableUser::class.java) val indices = ObjectCursor.indicesFrom(cur, ParcelableUser::class.java)

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@ class ItemCounts(counts: Int) {
} }
fun getItemStartPosition(countIndex: Int): 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() val itemCount: Int get() = data.sum()

View File

@ -12,11 +12,11 @@ import org.mariotaku.twidere.model.UserKey
object ParcelableActivityUtils { object ParcelableActivityUtils {
/** /**
* @param activity Activity for processing * @param sources Source users
* * * *
* @param filtered Those ids will be removed from source_ids. * @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 * @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) val values = arrayOfNulls<CharSequence>(infoListSize + 1)
entries[0] = noneEntry entries[0] = noneEntry
values[0] = "" values[0] = ""
for (i in 0..infoListSize - 1) { for (i in 0 until infoListSize) {
val info = infoList[i] val info = infoList[i]
entries[i + 1] = info.loadLabel(packageManager) entries[i + 1] = info.loadLabel(packageManager)
values[i + 1] = getComponentName(info).flattenToString() values[i + 1] = getComponentName(info).flattenToString()

View File

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

View File

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

View File

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

View File

@ -122,6 +122,7 @@ class MarkMessageReadTask(
@SuppressLint("Recycle") @SuppressLint("Recycle")
val cur = query(Messages.CONTENT_URI, Messages.COLUMNS, val cur = query(Messages.CONTENT_URI, Messages.COLUMNS,
where, whereArgs, OrderBy(Messages.LOCAL_TIMESTAMP, false).sql) ?: return null where, whereArgs, OrderBy(Messages.LOCAL_TIMESTAMP, false).sql) ?: return null
@Suppress("ConvertTryFinallyToUseCall")
try { try {
if (cur.moveToFirst()) { if (cur.moveToFirst()) {
val indices = ObjectCursor.indicesFrom(cur, ParcelableMessage::class.java) 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. * Created by mariotaku on 15/12/22.
*/ */
class EmojiSpan(private val drawable: Drawable) : DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BOTTOM) { class EmojiSpan(private val drawable: Drawable) : DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BOTTOM) {
private val fontMetrics: Paint.FontMetrics private val fontMetrics: Paint.FontMetrics = Paint.FontMetrics()
init {
this.fontMetrics = Paint.FontMetrics()
}
override fun getDrawable(): Drawable? { override fun getDrawable(): Drawable? {
return drawable return drawable

View File

@ -24,7 +24,9 @@ import org.mariotaku.twidere.provider.TwidereDataStore.Accounts
*/ */
@Suppress("deprecation") @Suppress("deprecation")
fun migrateAccounts(am: AccountManager, db: SQLiteDatabase) { 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 { try {
val indices = ObjectCursor.indicesFrom(cur, ParcelableCredentials::class.java) val indices = ObjectCursor.indicesFrom(cur, ParcelableCredentials::class.java)
cur.moveToFirst() cur.moveToFirst()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -47,6 +47,7 @@ object FilterQueryBuilder {
textPlain, quotedTextPlain, spans, quotedSpans, source, quotedSource, retweetedByKey, textPlain, quotedTextPlain, spans, quotedSpans, source, quotedSource, retweetedByKey,
quotedUserKey, true) quotedUserKey, true)
val cur = cr.rawQuery(query.first, query.second) ?: return false val cur = cr.rawQuery(query.first, query.second) ?: return false
@Suppress("ConvertTryFinallyToUseCall")
try { try {
return cur.moveToFirst() && cur.getInt(0) != 0 return cur.moveToFirst() && cur.getInt(0) != 0
} finally { } 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) { private fun addLogSplit(logger: TimingLogger, host: String, message: String, depth: Int) {
if (BuildConfig.DEBUG) return if (BuildConfig.DEBUG) return
val sb = StringBuilder() val sb = StringBuilder()
for (i in 0..depth - 1) { for (i in 0 until depth) {
sb.append(">") sb.append(">")
} }
sb.append(" ") sb.append(" ")

View File

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

View File

@ -43,6 +43,7 @@ abstract class FileBasedDraftsSyncAction<RemoteFileInfo>(val context: Context) :
val localDrafts = run { val localDrafts = run {
val cur = context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, null, null, null)!! val cur = context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, null, null, null)!!
@Suppress("ConvertTryFinallyToUseCall")
try { try {
val indices = ObjectCursor.indicesFrom(cur, Draft::class.java) val indices = ObjectCursor.indicesFrom(cur, Draft::class.java)
return@run cur.map(indices) return@run cur.map(indices)
@ -157,6 +158,7 @@ abstract class FileBasedDraftsSyncAction<RemoteFileInfo>(val context: Context) :
snapshotsListFile.writer().use { writer -> snapshotsListFile.writer().use { writer ->
val cur = context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, null, null, null)!! val cur = context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, null, null, null)!!
@Suppress("ConvertTryFinallyToUseCall")
try { try {
val indices = ObjectCursor.indicesFrom(cur, Draft::class.java) val indices = ObjectCursor.indicesFrom(cur, Draft::class.java)
cur.map(indices).map { it.unique_id_non_null }.forEach { line -> 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 hasChoice = selectedChoice != -1
val isMyPoll = status.account_key == status.user_key val isMyPoll = status.account_key == status.user_key
val showResult = countsAreFinal || isMyPoll || hasChoice val showResult = countsAreFinal || isMyPoll || hasChoice
for (i in 0..choicesCount - 1) { for (i in 0 until choicesCount) {
val choiceIndex = i + 1 val choiceIndex = i + 1
votesSum += card.getAsInteger("choice${choiceIndex}_count", 0) 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 color = ContextCompat.getColor(context, R.color.material_light_blue_a200)
val radius = context.resources.getDimension(R.dimen.element_spacing_small) 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 pollItem = view.pollContainer.getChildAt(i)
val choicePercentView: TextView = pollItem.findViewById(R.id.choice_percent) val choicePercentView: TextView = pollItem.findViewById(R.id.choice_percent)

View File

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

View File

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