file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
NotFoundException.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/NotFoundException.java | /*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* Thrown when a barcode was not found in the image. It might have been
* partially detected but could not be confirmed.
*
* @author Sean Owen
*/
public final class NotFoundException extends ReaderException {
private static final NotFoundException INSTANCE = new NotFoundException();
static {
INSTANCE.setStackTrace(NO_TRACE); // since it's meaningless
}
private NotFoundException() {
// do nothing
}
public static NotFoundException getNotFoundInstance() {
return INSTANCE;
}
}
| 1,199 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BitMatrixCreator.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/BitMatrixCreator.java | package org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* Uses a very naive threshold: a single fixed black point. As we have good control
* over the lighting conditions, this should be sufficient.
*/
public class BitMatrixCreator {
private static BitMatrix matrix;
public BitMatrixCreator(int width, int height) {
}
// the data has the long dimension as width, and the short dimension as height
public static BitMatrix createBitMatrix(byte[] yDataArray, int rowStride, int dataWidth,
int dataHeight, int hStart, int vStart,
int width, int height) {
if (hStart + width > dataWidth || vStart + height > dataHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
if (rowStride != dataWidth) {
throw new IllegalArgumentException("Row stride not equal to data width");
}
if (matrix == null) {
matrix = new BitMatrix(width, height);
} else {
matrix.clear();
}
if (yDataArray == null) return null;
// lets use the approximate location of the four corners to estimate the black point
int size = (int) Math.round(0.25 * width);
int blackTopLeft = estimateBlackPoint(yDataArray, rowStride, 1, 1, size, size);
int blackTopRight = estimateBlackPoint(yDataArray, rowStride, width - size, 1, width, size);
int blackBottomLeft = estimateBlackPoint(yDataArray, rowStride, 1, height - size, size, height);
int blackBottomRight = estimateBlackPoint(yDataArray, rowStride, width - size, height - size, width, height);
for (int y = 0; y < height / 2; y++) {
int offset = y * rowStride;
for (int x = 0; x < width / 2; x++) {
int pixel = yDataArray[offset + x] & 0xff;
if (pixel < blackTopLeft) {
matrix.set(x, y);
}
}
}
for (int y = height / 2; y < height; y++) {
int offset = y * rowStride;
for (int x = width / 2; x < width; x++) {
int pixel = yDataArray[offset + x] & 0xff;
if (pixel < blackBottomRight) {
matrix.set(x, y);
}
}
}
for (int y = 0; y < height / 2; y++) {
int offset = y * rowStride;
for (int x = width / 2; x < width; x++) {
int pixel = yDataArray[offset + x] & 0xff;
if (pixel < blackTopRight) {
matrix.set(x, y);
}
}
}
for (int y = height / 2; y < height; y++) {
int offset = y * rowStride;
for (int x = 0; x < width / 2; x++) {
int pixel = yDataArray[offset + x] & 0xff;
if (pixel < blackBottomLeft) {
matrix.set(x, y);
}
}
}
return matrix;
}
private static int estimateBlackPoint(byte[] yData, int rowStride,
int xtl, int ytl, int xbr, int ybr) {
int yMax = 0;
int yMin = 1000;
int val;
for (int y = ytl; y <= ybr; y += 2) {
int offset = y * rowStride;
for (int x = xtl; x < xbr; x += 2) {
val = yData[offset + x] & 0xff;
yMax = Math.max(yMax, val);
yMin = Math.min(yMin, val);
}
}
return (int) Math.round(0.33333 * (2 * yMax + yMin));
}
}
| 3,650 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PerspectiveTransform.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/PerspectiveTransform.java | /*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>This class implements a perspective transform in two dimensions. Given four source and four
* destination points, it will compute the transformation implied between them. The code is based
* directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p>
*
* @author Sean Owen
*/
public final class PerspectiveTransform {
private final float a11;
private final float a12;
private final float a13;
private final float a21;
private final float a22;
private final float a23;
private final float a31;
private final float a32;
private final float a33;
private PerspectiveTransform(float a11, float a21, float a31,
float a12, float a22, float a32,
float a13, float a23, float a33) {
this.a11 = a11;
this.a12 = a12;
this.a13 = a13;
this.a21 = a21;
this.a22 = a22;
this.a23 = a23;
this.a31 = a31;
this.a32 = a32;
this.a33 = a33;
}
public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0,
float x1, float y1,
float x2, float y2,
float x3, float y3,
float x0p, float y0p,
float x1p, float y1p,
float x2p, float y2p,
float x3p, float y3p) {
PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
return sToQ.times(qToS);
}
public static PerspectiveTransform squareToQuadrilateral(float x0, float y0,
float x1, float y1,
float x2, float y2,
float x3, float y3) {
float dx3 = x0 - x1 + x2 - x3;
float dy3 = y0 - y1 + y2 - y3;
if (dx3 == 0.0f && dy3 == 0.0f) {
// Affine
return new PerspectiveTransform(x1 - x0, x2 - x1, x0,
y1 - y0, y2 - y1, y0,
0.0f, 0.0f, 1.0f);
} else {
float dx1 = x1 - x2;
float dx2 = x3 - x2;
float dy1 = y1 - y2;
float dy2 = y3 - y2;
float denominator = dx1 * dy2 - dx2 * dy1;
float a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
float a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0,
y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0,
a13, a23, 1.0f);
}
}
public static PerspectiveTransform quadrilateralToSquare(float x0, float y0,
float x1, float y1,
float x2, float y2,
float x3, float y3) {
// Here, the adjoint serves as the inverse:
return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();
}
public void transformPoints(float[] points) {
int max = points.length;
float a11 = this.a11;
float a12 = this.a12;
float a13 = this.a13;
float a21 = this.a21;
float a22 = this.a22;
float a23 = this.a23;
float a31 = this.a31;
float a32 = this.a32;
float a33 = this.a33;
for (int i = 0; i < max; i += 2) {
float x = points[i];
float y = points[i + 1];
float denominator = a13 * x + a23 * y + a33;
points[i] = (a11 * x + a21 * y + a31) / denominator;
points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
}
}
public void transformPoints(float[] xValues, float[] yValues) {
int n = xValues.length;
for (int i = 0; i < n; i++) {
float x = xValues[i];
float y = yValues[i];
float denominator = a13 * x + a23 * y + a33;
xValues[i] = (a11 * x + a21 * y + a31) / denominator;
yValues[i] = (a12 * x + a22 * y + a32) / denominator;
}
}
PerspectiveTransform buildAdjoint() {
// Adjoint is the transpose of the cofactor matrix:
return new PerspectiveTransform(a22 * a33 - a23 * a32,
a23 * a31 - a21 * a33,
a21 * a32 - a22 * a31,
a13 * a32 - a12 * a33,
a11 * a33 - a13 * a31,
a12 * a31 - a11 * a32,
a12 * a23 - a13 * a22,
a13 * a21 - a11 * a23,
a11 * a22 - a12 * a21);
}
PerspectiveTransform times(PerspectiveTransform other) {
return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13,
a11 * other.a21 + a21 * other.a22 + a31 * other.a23,
a11 * other.a31 + a21 * other.a32 + a31 * other.a33,
a12 * other.a11 + a22 * other.a12 + a32 * other.a13,
a12 * other.a21 + a22 * other.a22 + a32 * other.a23,
a12 * other.a31 + a22 * other.a32 + a32 * other.a33,
a13 * other.a11 + a23 * other.a12 + a33 * other.a13,
a13 * other.a21 + a23 * other.a22 + a33 * other.a23,
a13 * other.a31 + a23 * other.a32 + a33 * other.a33);
}
}
| 6,563 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DefaultGridSampler.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/DefaultGridSampler.java | /*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* @author Sean Owen
*/
public final class DefaultGridSampler extends GridSampler {
@Override
public BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
float p1ToX, float p1ToY,
float p2ToX, float p2ToY,
float p3ToX, float p3ToY,
float p4ToX, float p4ToY,
float p1FromX, float p1FromY,
float p2FromX, float p2FromY,
float p3FromX, float p3FromY,
float p4FromX, float p4FromY) throws NotFoundException {
PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(
p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY,
p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
return sampleGrid(image, dimensionX, dimensionY, transform);
}
@Override
public BitMatrix sampleGrid(BitMatrix image,
int dimensionX,
int dimensionY,
PerspectiveTransform transform) throws NotFoundException {
if (dimensionX <= 0 || dimensionY <= 0) {
throw NotFoundException.getNotFoundInstance();
}
BitMatrix bits = new BitMatrix(dimensionX, dimensionY);
float[] points = new float[2 * dimensionX];
for (int y = 0; y < dimensionY; y++) {
int max = points.length;
float iValue = (float) y + 0.5f;
for (int x = 0; x < max; x += 2) {
points[x] = (float) (x / 2) + 0.5f;
points[x + 1] = iValue;
}
transform.transformPoints(points);
// Quick check to see if points transformed to something inside the image;
// sufficient to check the endpoints
checkAndNudgePoints(image, points);
//noinspection SpellCheckingInspection
try {
for (int x = 0; x < max; x += 2) {
if (image.get((int) points[x], (int) points[x + 1])) {
// Black(-ish) pixel
bits.set(x / 2, y);
}
}
} catch (ArrayIndexOutOfBoundsException aioobe) {
// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
// transform gets "twisted" such that it maps a straight line of points to a set of points
// whose endpoints are in bounds, but others are not. There is probably some mathematical
// way to detect this about the transformation that I don't know yet.
// This results in an ugly runtime exception despite our clever checks above -- can't have
// that. We could check each point's coordinates but that feels duplicative. We settle for
// catching and wrapping ArrayIndexOutOfBoundsException.
throw NotFoundException.getNotFoundInstance();
}
}
return bits;
}
}
| 3,938 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ResultPoint.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/qrdetector/ResultPoint.java | /*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.striptest.qrdetector;
/**
* <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
* would be the location of a finder pattern or the corner of the barcode, for example.</p>
*
* @author Sean Owen
*/
public class ResultPoint {
private final float x;
private final float y;
public ResultPoint(float x, float y) {
this.x = x;
this.y = y;
}
/**
* @param pattern1 first pattern
* @param pattern2 second pattern
* @return distance between two points
*/
public static float distance(ResultPoint pattern1, ResultPoint pattern2) {
return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y);
}
public final float getX() {
return x;
}
public final float getY() {
return y;
}
@Override
public final boolean equals(Object other) {
if (other instanceof ResultPoint) {
ResultPoint otherPoint = (ResultPoint) other;
return x == otherPoint.x && y == otherPoint.y;
}
return false;
}
@Override
public final int hashCode() {
return 31 * Float.floatToIntBits(x) + Float.floatToIntBits(y);
}
@Override
public final String toString() {
return "(" + x + ',' + y + ')';
}
}
| 1,945 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
StriptestHandler.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/ui/StriptestHandler.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.ui;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.TextSwitcher;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.striptest.camera.CameraOperationsManager;
import org.akvo.caddisfly.sensor.striptest.decode.DecodeProcessor;
import org.akvo.caddisfly.sensor.striptest.models.CalibrationCardData;
import org.akvo.caddisfly.sensor.striptest.models.CalibrationCardException;
import org.akvo.caddisfly.sensor.striptest.models.DecodeData;
import org.akvo.caddisfly.sensor.striptest.models.TimeDelayDetail;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPatternInfo;
import org.akvo.caddisfly.sensor.striptest.utils.CalibrationCardUtils;
import org.akvo.caddisfly.sensor.striptest.utils.Constants;
import org.akvo.caddisfly.sensor.striptest.widget.FinderPatternIndicatorView;
import java.util.ArrayList;
import java.util.List;
import timber.log.Timber;
public final class StriptestHandler extends Handler {
public static final int DECODE_IMAGE_CAPTURED_MESSAGE = 2;
public static final int DECODE_SUCCEEDED_MESSAGE = 4;
public static final int DECODE_FAILED_MESSAGE = 5;
public static final int EXPOSURE_OK_MESSAGE = 6;
public static final int CHANGE_EXPOSURE_MESSAGE = 7;
public static final int SHADOW_QUALITY_OK_MESSAGE = 8;
public static final int SHADOW_QUALITY_FAILED_MESSAGE = 9;
public static final int CALIBRATION_DONE_MESSAGE = 10;
public static final int IMAGE_SAVED_MESSAGE = 11;
// Message types
static final int START_PREVIEW_MESSAGE = 1;
private static final DecodeData mDecodeData = new DecodeData();
private static final int DECODE_IMAGE_CAPTURE_FAILED_MESSAGE = 3;
private static final CalibrationCardData mCalCardData = new CalibrationCardData();
private static State mState;
private static int decodeFailedCount = 0;
private static int successCount = 0;
private static int nextPatch;
private static int numPatches;
private static boolean captureNextImage;
private final List<TimeDelayDetail> mPatchTimeDelays = new ArrayList<>();
// camera manager instance
private final CameraOperationsManager mCameraOpsManager;
// finder pattern indicator view
private final FinderPatternIndicatorView mFinderPatternIndicatorView;
private final StripMeasureListener mListener;
private final Context context;
private List<TimeDelayDetail> mPatchTimeDelaysUnfiltered;
// decode processor instance
private DecodeProcessor mDecodeProcessor;
private StripMeasureFragment mFragment;
private TextSwitcher mTextSwitcher;
private int shadowQualityFailedCount = 0;
private int tiltFailedCount = 0;
private int distanceFailedCount = 0;
private String currentMessage = "";
private String currentShadowMessage = "";
private String newMessage = "";
private String defaultMessage;
private int mQualityScore = 0;
private long startTimeMillis;
private int currentTestStage;
private int totalTestStages = 1;
StriptestHandler(Context context, CameraOperationsManager cameraOpsManager,
FinderPatternIndicatorView finderPatternIndicatorView,
TestInfo testInfo, int currentStage) {
if (StripMeasureActivity.DEBUG) {
Timber.d("in constructor striptestHandler");
}
currentTestStage = currentStage;
mListener = (StripMeasureListener) context;
this.mCameraOpsManager = cameraOpsManager;
this.mFinderPatternIndicatorView = finderPatternIndicatorView;
// create instance of the decode processor
if (mDecodeProcessor == null) {
mDecodeProcessor = new DecodeProcessor(this);
}
mDecodeData.setTestInfo(testInfo);
if (currentStage == 1) {
mDecodeData.clearImageMap();
}
this.context = context;
}
public static DecodeData getDecodeData() {
return mDecodeData;
}
public static CalibrationCardData getCalCardData() {
return mCalCardData;
}
void setTextSwitcher(TextSwitcher textSwitcher) {
this.mTextSwitcher = textSwitcher;
}
public void setFragment(StripMeasureFragment fragment) {
mFragment = fragment;
mFragment.setState(mState);
}
void setTestData(List<TimeDelayDetail> timeDelays) {
mPatchTimeDelaysUnfiltered = timeDelays;
}
void setStatus(State state) {
mState = state;
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case START_PREVIEW_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("START_PREVIEW_MESSAGE received in striptest handler");
}
// start the image capture request.
mCameraOpsManager.startAutofocus();
successCount = 0;
mQualityScore = 0;
startTimeMillis = System.currentTimeMillis();
nextPatch = 0;
mPatchTimeDelays.clear();
for (TimeDelayDetail timeDelayDetail : mPatchTimeDelaysUnfiltered) {
// get only the patches that have to be analyzed at the current stage
if (timeDelayDetail.getTestStage() == currentTestStage) {
mPatchTimeDelays.add(timeDelayDetail);
}
totalTestStages = Math.max(timeDelayDetail.getTestStage(), totalTestStages);
}
numPatches = mPatchTimeDelays.size();
captureNextImage = false;
mCameraOpsManager.setDecodeImageCaptureRequest();
break;
case DECODE_IMAGE_CAPTURED_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("DECODE_IMAGE_CAPTURED_MESSAGE received in striptest handler");
}
// update timer
int secondsLeft = mPatchTimeDelays.get(nextPatch).getTimeDelay() - timeElapsedSeconds();
if (mState.equals(State.MEASURE) && secondsLeft > Constants.MIN_SHOW_TIMER_SECONDS) {
mListener.showTimer();
}
mListener.updateTimer(secondsLeft);
if (timeElapsedSeconds() > mPatchTimeDelays.get(nextPatch).getTimeDelay()) {
captureNextImage = true;
}
// set message shown if there are no problems
if (mState.equals(State.MEASURE)) {
if (secondsLeft > Constants.GET_READY_SECONDS) {
defaultMessage = context.getString(R.string.waiting);
} else if (secondsLeft < 2) {
defaultMessage = context.getString(R.string.taking_photo);
} else {
defaultMessage = context.getString(R.string.ready_for_photo);
}
} else {
defaultMessage = context.getString(R.string.checking_image_quality);
}
// start trying to find finder patterns on decode thread
mDecodeProcessor.startFindPossibleCenters();
break;
case DECODE_IMAGE_CAPTURE_FAILED_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("DECODE_IMAGE_CAPTURE_FAILED_MESSAGE received in striptest handler");
mDecodeData.clearData();
mFinderPatternIndicatorView.clearAll();
mCameraOpsManager.setDecodeImageCaptureRequest();
}
break;
case DECODE_SUCCEEDED_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("DECODE_SUCCEEDED_MESSAGE received in striptest handler");
FinderPatternInfo fpInfo = mDecodeData.getPatternInfo();
if (fpInfo != null) {
Timber.d("found codes:" + fpInfo.getBottomLeft().toString() + "," +
fpInfo.getBottomRight().toString() + "," +
fpInfo.getTopLeft().toString() + "," +
fpInfo.getTopRight().toString() + ",");
}
}
boolean showTiltMessage = false;
boolean showDistanceMessage = false;
decodeFailedCount = 0;
if (mDecodeData.getTilt() != DecodeProcessor.NO_TILT) {
tiltFailedCount = Math.min(8, tiltFailedCount + 1);
if (tiltFailedCount > 4) showTiltMessage = true;
} else {
tiltFailedCount = Math.max(0, tiltFailedCount - 1);
}
if (!mDecodeData.getDistanceOk()) {
distanceFailedCount = Math.min(8, distanceFailedCount + 1);
if (distanceFailedCount > 4) showDistanceMessage = true;
} else {
distanceFailedCount = Math.max(0, distanceFailedCount - 1);
}
if (showTiltMessage) {
newMessage = context.getString(R.string.tilt_camera_in_direction);
showDistanceMessage = false;
} else if (showDistanceMessage) {
newMessage = context.getString(R.string.move_camera_closer);
}
if (!showTiltMessage && !showDistanceMessage) {
newMessage = defaultMessage;
}
if (!newMessage.equals(currentMessage)) {
mTextSwitcher.setText(newMessage);
currentMessage = newMessage;
}
// show patterns
mFinderPatternIndicatorView.showPatterns(mDecodeData.getFinderPatternsFound(),
mDecodeData.getTilt(), showTiltMessage, showDistanceMessage, mDecodeData.getDecodeWidth(), mDecodeData.getDecodeHeight());
// move on to exposure quality check
// if tilt or distance are not ok, start again
if (mDecodeData.getTilt() != DecodeProcessor.NO_TILT || !mDecodeData.getDistanceOk()) {
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
break;
}
// if we are here, all is well and we can proceed
mDecodeProcessor.startExposureQualityCheck();
break;
case DECODE_FAILED_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("DECODE_FAILED_MESSAGE received in striptest handler");
}
decodeFailedCount++;
mDecodeData.clearData();
if (decodeFailedCount > 5) {
mFinderPatternIndicatorView.clearAll();
}
mQualityScore *= 0.9;
mFragment.showQuality(mQualityScore);
mCameraOpsManager.setDecodeImageCaptureRequest();
break;
case CHANGE_EXPOSURE_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("exposure - CHANGE_EXPOSURE_MESSAGE received in striptest handler, with argument:%s", message.arg1);
}
int direction = message.arg1;
// change exposure
mCameraOpsManager.changeExposure(direction);
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
break;
case EXPOSURE_OK_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("exposure - EXPOSURE_OK_MESSAGE received in striptest handler");
}
if (mDecodeData.isCardVersionEstablished()) {
int version = mDecodeData.getMostFrequentVersionNumber();
// if this is the first time we read the card, or if we use a card with a different
// version number
if (mCalCardData.getVersion() != version) {
try {
CalibrationCardUtils.readCalibrationFile(mCalCardData, version);
} catch (CalibrationCardException e) {
// keep going
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
break;
}
}
// if we arrive here, we both have loaded a valid calibration card file,
// and the exposure is ok. So we can proceed to the next step: checking shadows.
mDecodeProcessor.startShadowQualityCheck();
} else {
// start again
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
}
break;
case SHADOW_QUALITY_FAILED_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("SHADOW_QUALITY_FAILED_MESSAGE received in striptest handler");
}
shadowQualityFailedCount = Math.min(8, shadowQualityFailedCount + 1);
String newShadowMessage;
if (shadowQualityFailedCount > 4) {
newShadowMessage = context.getString(R.string.avoid_shadows_on_card);
} else {
newShadowMessage = "";
}
if (!currentShadowMessage.equals(newShadowMessage)) {
mTextSwitcher.setText(newShadowMessage);
currentShadowMessage = newShadowMessage;
}
mFinderPatternIndicatorView.showShadow(mDecodeData.getShadowPoints(),
mDecodeData.getCardToImageTransform());
// start another decode image capture request
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
break;
case SHADOW_QUALITY_OK_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("SHADOW_QUALITY_OK_MESSAGE received in striptest handler");
}
shadowQualityFailedCount = Math.max(0, shadowQualityFailedCount - 1);
if (shadowQualityFailedCount > 4) {
newShadowMessage = context.getString(R.string.avoid_shadows_on_card);
} else {
newShadowMessage = "";
}
if (!currentShadowMessage.equals(newShadowMessage)) {
mTextSwitcher.setText(newShadowMessage);
currentShadowMessage = newShadowMessage;
}
mFinderPatternIndicatorView.showShadow(mDecodeData.getShadowPoints(),
mDecodeData.getCardToImageTransform());
mDecodeProcessor.startCalibration();
break;
case CALIBRATION_DONE_MESSAGE:
if (StripMeasureActivity.DEBUG) {
Timber.d("CALIBRATION_DONE_MESSAGE received in striptest handler");
}
int quality = qualityPercentage(mDecodeData.getDeltaEStats());
if (mFragment != null) {
mFragment.showQuality(quality);
if (mState.equals(State.PREPARE) && quality > Constants.CALIBRATION_PERCENTAGE_LIMIT) {
successCount++;
mFragment.setProgress(successCount);
}
}
if (mState.equals(State.PREPARE) && successCount > Constants.COUNT_QUALITY_CHECK_LIMIT) {
mCameraOpsManager.stopAutofocus();
mListener.moveToInstructions(currentTestStage);
break;
}
if (mState.equals(State.MEASURE) && captureNextImage && quality > Constants.CALIBRATION_PERCENTAGE_LIMIT) {
captureNextImage = false;
mDecodeProcessor.storeImageData(mPatchTimeDelays.get(nextPatch).getTimeDelay());
} else {
// start another decode image capture request
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
}
break;
case IMAGE_SAVED_MESSAGE:
mListener.playSound();
if (nextPatch < numPatches - 1) {
nextPatch++;
// start another decode image capture request
mDecodeData.clearData();
mCameraOpsManager.setDecodeImageCaptureRequest();
} else {
if (currentTestStage < totalTestStages) {
// if all are stages are not completed then show next instructions
currentTestStage++;
mListener.moveToInstructions(currentTestStage);
} else {
if (AppPreferences.isSaveTestImage()) {
mDecodeData.saveCapturedImage();
}
// we are done
mListener.moveToResults();
}
}
break;
default:
}
}
private int qualityPercentage(float[] deltaEStats) {
// we consider anything lower than 2.5 to be good.
// anything higher than 4.5 is red.
double score = 0;
if (deltaEStats != null) {
score = Math.round(100.0 * (1 - Math.min(1.0, (Math.max(0, deltaEStats[1] - 2.5) / 2.0))));
}
// if the quality is improving, we show a high number quickly, if it is
// going down, we go down more slowly.
if (score > mQualityScore) {
mQualityScore = (int) Math.round((mQualityScore + score) / 2.0);
} else {
mQualityScore = (int) Math.round((5 * mQualityScore + score) / 6.0);
}
return mQualityScore;
}
private int timeElapsedSeconds() {
return (int) Math.floor((Constants.MEASURE_TIME_COMPENSATION_MILLIS
+ System.currentTimeMillis() - startTimeMillis) / 1000);
}
void quitSynchronously() {
mDecodeProcessor.stopDecodeThread();
}
public enum State {
PREPARE, MEASURE
}
} | 19,627 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
StripMeasureListener.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/ui/StripMeasureListener.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.ui;
interface StripMeasureListener {
void moveToInstructions(int testStage);
void moveToResults();
void playSound();
void updateTimer(int value);
void showTimer();
}
| 990 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
StripTestActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/ui/StripTestActivity.java | package org.akvo.caddisfly.sensor.striptest.ui;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueUnitString;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.databinding.FragmentInstructionBinding;
import org.akvo.caddisfly.helper.InstructionHelper;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.PageIndex;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.ui.BaseFragment;
import org.akvo.caddisfly.widget.CustomViewPager;
import org.akvo.caddisfly.widget.PageIndicatorView;
import org.akvo.caddisfly.widget.SwipeDirection;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Objects;
public class StripTestActivity extends BaseActivity {
private static final int REQUEST_QUALITY_TEST = 1;
private static final int REQUEST_TEST = 2;
private ImageView imagePageRight;
private ImageView imagePageLeft;
private ResultFragment resultFragment;
private final PageIndex pageIndex = new PageIndex();
private TestInfo testInfo;
private CustomViewPager viewPager;
private FrameLayout resultLayout;
private FrameLayout pagerLayout;
private RelativeLayout footerLayout;
private PageIndicatorView pagerIndicator;
private boolean showSkipMenu = true;
private FirebaseAnalytics mFirebaseAnalytics;
private int resultPageNumber;
private int totalPageCount;
private int skipToPageNumber;
private int currentStage = 1;
private final ArrayList<Instruction> instructionList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_steps);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
viewPager = findViewById(R.id.viewPager);
pagerIndicator = findViewById(R.id.pager_indicator);
resultLayout = findViewById(R.id.resultLayout);
pagerLayout = findViewById(R.id.pagerLayout);
footerLayout = findViewById(R.id.layout_footer);
if (savedInstanceState != null) {
testInfo = savedInstanceState.getParcelable(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
return;
}
InstructionHelper.setupInstructions(testInfo.getInstructions(),
instructionList, pageIndex, false);
int instructionCount = instructionList.size();
totalPageCount = instructionCount + 1;
resultPageNumber = totalPageCount - 1;
skipToPageNumber = resultPageNumber - 1;
if (savedInstanceState == null) {
createFragments();
}
for (int i = 0; i < instructionCount; i++) {
if (instructionList.get(i).testStage > 0) {
skipToPageNumber = i;
break;
}
}
SectionsPagerAdapter mSectionsPagerAdapter =
new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mSectionsPagerAdapter);
pagerIndicator.showDots(true);
pagerIndicator.setPageCount(totalPageCount - 1);
imagePageRight = findViewById(R.id.image_pageRight);
imagePageRight.setOnClickListener(view ->
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1));
imagePageLeft = findViewById(R.id.image_pageLeft);
imagePageLeft.setVisibility(View.INVISIBLE);
imagePageLeft.setOnClickListener(view -> pageBack());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
pagerIndicator.setActiveIndex(position);
if (position < 1) {
imagePageLeft.setVisibility(View.INVISIBLE);
} else {
imagePageLeft.setVisibility(View.VISIBLE);
}
showHideFooter();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
if (savedInstanceState == null) {
Intent intent = new Intent(getBaseContext(), StripMeasureActivity.class);
intent.putExtra(ConstantKey.TEST_INFO, testInfo);
intent.putExtra(ConstantKey.TEST_STAGE, currentStage);
startActivityForResult(intent, REQUEST_QUALITY_TEST);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(ConstantKey.TEST_INFO, testInfo);
super.onSaveInstanceState(outState);
}
@Override
public void onRestoreInstanceState(@NotNull Bundle inState) {
for (int i = 0; i < getSupportFragmentManager().getFragments().size(); i++) {
Fragment fragment = getSupportFragmentManager().getFragments().get(i);
if (fragment instanceof BaseFragment) {
if (((BaseFragment) fragment).getFragmentId() == resultPageNumber) {
resultFragment = (ResultFragment) fragment;
}
}
}
createFragments();
super.onRestoreInstanceState(inState);
}
private void createFragments() {
int resultId = 1;
if (resultFragment == null) {
resultFragment = ResultFragment.newInstance(testInfo, resultId);
resultFragment.setFragmentId(resultPageNumber);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TEST) {
if (resultCode == RESULT_OK) {
if (viewPager.getCurrentItem() != resultPageNumber - 1) {
currentStage++;
skipToPageNumber = resultPageNumber - 1;
}
resultFragment.setDecodeData(StriptestHandler.getDecodeData());
nextPage();
}
} else if (requestCode == REQUEST_QUALITY_TEST) {
if (resultCode != RESULT_OK) {
finish();
}
}
}
private void nextPage() {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
private void showHideFooter() {
if (imagePageLeft == null) {
return;
}
showSkipMenu = false;
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageLeft.setVisibility(View.VISIBLE);
imagePageRight.setVisibility(View.VISIBLE);
pagerIndicator.setVisibility(View.VISIBLE);
footerLayout.setVisibility(View.VISIBLE);
if (viewPager.getCurrentItem() < resultPageNumber - 2) {
showSkipMenu = true;
}
if (viewPager.getCurrentItem() == skipToPageNumber - 1) {
showSkipMenu = false;
}
if (viewPager.getCurrentItem() == resultPageNumber) {
setTitle(R.string.result);
viewPager.setAllowedSwipeDirection(SwipeDirection.none);
footerLayout.setVisibility(View.GONE);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
} else if (viewPager.getCurrentItem() > 0 &&
instructionList.get(viewPager.getCurrentItem() - 1).testStage > 0) {
viewPager.setAllowedSwipeDirection(SwipeDirection.right);
imagePageLeft.setVisibility(View.INVISIBLE);
} else if (instructionList.get(viewPager.getCurrentItem()).testStage > 0) {
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
showSkipMenu = false;
} else if (viewPager.getCurrentItem() == resultPageNumber - 1) {
imagePageRight.setVisibility(View.INVISIBLE);
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
} else {
footerLayout.setVisibility(View.VISIBLE);
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
if (viewPager.getCurrentItem() == 0) {
imagePageLeft.setVisibility(View.INVISIBLE);
}
}
invalidateOptionsMenu();
}
@Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != resultPageNumber) {
if (viewPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
pageBack();
}
}
}
private void pageBack() {
viewPager.setCurrentItem(Math.max(0, viewPager.getCurrentItem() - 1));
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(testInfo.getName());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (showSkipMenu) {
getMenuInflater().inflate(R.menu.menu_instructions, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (viewPager.getCurrentItem() == 0) {
onBackPressed();
} else {
viewPager.setCurrentItem(0);
showHideFooter();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSkipClick(MenuItem item) {
viewPager.setCurrentItem(skipToPageNumber);
showWaitingView();
if (AppPreferences.analyticsEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("InstructionsSkipped", testInfo.getName() +
" (" + testInfo.getBrand() + ")");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Navigation");
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "si_" + testInfo.getUuid());
mFirebaseAnalytics.logEvent("instruction_skipped", bundle);
}
}
private void showWaitingView() {
pagerLayout.setVisibility(View.VISIBLE);
resultLayout.setVisibility(View.INVISIBLE);
showSkipMenu = false;
invalidateOptionsMenu();
}
public void onStartTest(View view) {
Intent intent = new Intent(getBaseContext(), StripMeasureActivity.class);
intent.putExtra(ConstantKey.START_MEASURE, true);
intent.putExtra(ConstantKey.TEST_INFO, testInfo);
intent.putExtra(ConstantKey.TEST_STAGE, currentStage);
startActivityForResult(intent, REQUEST_TEST);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_SHOW_OK = "show_ok";
FragmentInstructionBinding fragmentInstructionBinding;
Instruction instruction;
private boolean showOk;
private LinearLayout resultLayout;
private ViewGroup viewRoot;
/**
* Returns a new instance of this fragment for the given section number.
*
* @param instruction The information to to display
* @return The instance
*/
static PlaceholderFragment newInstance(Instruction instruction, boolean showOkButton) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SECTION_NUMBER, instruction);
args.putBoolean(ARG_SHOW_OK, showOkButton);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentInstructionBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_instruction, container, false);
viewRoot = container;
if (getArguments() != null) {
instruction = getArguments().getParcelable(ARG_SECTION_NUMBER);
showOk = getArguments().getBoolean(ARG_SHOW_OK);
fragmentInstructionBinding.setInstruction(instruction);
}
View view = fragmentInstructionBinding.getRoot();
if (showOk) {
view.findViewById(R.id.buttonStart).setVisibility(View.VISIBLE);
}
resultLayout = view.findViewById(R.id.layout_results);
return view;
}
public void setResult(TestInfo testInfo) {
if (testInfo != null) {
LayoutInflater inflater = (LayoutInflater) Objects.requireNonNull(getActivity())
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resultLayout.removeAllViews();
SparseArray<String> results = new SparseArray<>();
results.put(1, String.valueOf(testInfo.getResults().get(0).getResultValue()));
results.put(2, String.valueOf(testInfo.getResults().get(1).getResultValue()));
for (Result result : testInfo.getResults()) {
String valueString = createValueUnitString(result.getResultValue(), result.getUnit(),
getString(R.string.no_result));
LinearLayout itemResult;
itemResult = (LinearLayout) inflater.inflate(R.layout.item_result,
viewRoot, false);
TextView textTitle = itemResult.findViewById(R.id.text_title);
textTitle.setText(result.getName());
TextView textResult = itemResult.findViewById(R.id.text_result);
textResult.setText(valueString);
resultLayout.addView(itemResult);
}
resultLayout.setVisibility(View.VISIBLE);
}
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position < instructionList.size() &&
instructionList.get(position).testStage > 0) {
return PlaceholderFragment.newInstance(instructionList.get(position),
true);
} else if (position == totalPageCount - 2) {
return PlaceholderFragment.newInstance(instructionList.get(position),
true);
} else if (position == totalPageCount - 1) {
return resultFragment;
} else {
return PlaceholderFragment.newInstance(
instructionList.get(position), false);
}
}
@Override
public int getCount() {
return totalPageCount;
}
}
}
| 16,774 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ResultFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/ui/ResultFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.ui;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.concatTwoBitmaps;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.createResultImageGroup;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.createResultImageSingle;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.createValueBitmap;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueString;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueUnitString;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.roundSignificant;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.ColorItem;
import org.akvo.caddisfly.model.GroupType;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.striptest.models.DecodeData;
import org.akvo.caddisfly.sensor.striptest.models.PatchResult;
import org.akvo.caddisfly.sensor.striptest.utils.ColorUtils;
import org.akvo.caddisfly.sensor.striptest.utils.Constants;
import org.akvo.caddisfly.sensor.striptest.utils.ResultUtils;
import org.akvo.caddisfly.ui.BaseFragment;
import org.akvo.caddisfly.util.MathUtil;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;
import timber.log.Timber;
/**
* Activity that displays the results.
*/
public class ResultFragment extends BaseFragment {
private static final int IMG_WIDTH = 500;
private static final String ARG_TEST_INFO = "test_info";
private static final String ARG_RESULT_ID = "resultId";
private static DecodeData mDecodeData;
private final SparseArray<String> resultStringValues = new SparseArray<>();
private final SparseArray<String> brackets = new SparseArray<>();
private Button buttonSave;
private Bitmap totalImage;
private String totalImageUrl;
private LinearLayout resultLayout;
private TestInfo testInfo;
public static ResultFragment newInstance(TestInfo testInfo, int resultId) {
ResultFragment fragment = new ResultFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_TEST_INFO, testInfo);
args.putInt(ARG_RESULT_ID, resultId);
fragment.setArguments(args);
return fragment;
}
void setDecodeData(DecodeData decodeData) {
mDecodeData = decodeData;
if (resultLayout != null) {
resultLayout.removeAllViews();
}
if (getArguments() != null) {
testInfo = getArguments().getParcelable(ARG_TEST_INFO);
if (testInfo != null) {
List<PatchResult> patchResultList = computeResults(testInfo);
if (resultLayout != null) {
showResults(patchResultList, testInfo);
}
}
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_strip_result, container, false);
resultLayout = rootView.findViewById(R.id.layout_results);
buttonSave = rootView.findViewById(R.id.buttonSubmitResult);
buttonSave.setOnClickListener(v -> {
Intent intent = new Intent();
if (totalImage != null) {
intent.putExtra(SensorConstants.IMAGE, totalImageUrl);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
totalImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
totalImage.recycle();
intent.putExtra(SensorConstants.IMAGE_BITMAP, stream.toByteArray());
} else {
totalImageUrl = "";
}
JSONObject resultJsonObj = TestConfigHelper.getJsonResult(getActivity(), testInfo,
resultStringValues, brackets, totalImageUrl);
intent.putExtra(SensorConstants.RESPONSE, resultJsonObj.toString());
Objects.requireNonNull(getActivity()).setResult(Activity.RESULT_OK, intent);
getActivity().finish();
});
return rootView;
}
private List<PatchResult> computeResults(TestInfo testInfo) {
totalImageUrl = UUID.randomUUID().toString() + ".png";
// TODO: check null mDecodeData here
// get the images for the patches
SparseArray<float[][][]> patchImageMap = mDecodeData.getStripImageMap();
// todo check order of patches
// for display purposes sort the patches by physical position on the strip
List<Result> results = testInfo.getResults();
// compute XYZ colours of patches and store as lab and xyz
List<PatchResult> patchResultList = new ArrayList<>();
for (Result patch : results) {
PatchResult patchResult = new PatchResult(patch.getId());
if (patch.getColors().size() == 0) {
continue;
}
int delay = patch.getTimeDelay();
// check if we have the corresponding image
if (patchImageMap.indexOfKey(delay) < 0) {
Timber.d("patch not found!");
patchResult.setMeasured(false);
continue;
// return null;
}
float[][][] img = patchImageMap.get(delay);
// check if the image is not null
if (img == null) {
patchResult.setMeasured(false);
continue;
// return null;
}
try {
patchResult.setImage(img);
float[] xyz = getPatchColour(patchImageMap.get(delay), patch, testInfo);
float[] lab = ColorUtils.XYZtoLAB(xyz);
patchResult.setXyz(xyz);
patchResult.setLab(lab);
patchResult.setPatch(patch);
} catch (Exception e) {
// failed extracting color from patch. Strip invalid or not place correctly
Timber.e(e);
patchResult.setMeasured(false);
continue;
}
// the patches are sorted by position here
patchResultList.add(patchResult);
}
// compare to known colours, using Lab (as this is perceptually uniform)
// here, we have to distinguish between GROUP and INDIVIDUAL
float value;
int index;
String bracket;
if (testInfo.getGroupingType() == GroupType.GROUP) {
float[] result = ResultUtils.calculateResultGroup(patchResultList, testInfo.getResults());
index = (int) result[0];
value = result[1];
bracket = createBracket(result[2], result[3]);
if (patchResultList.size() > 0) {
// apply formula when present
value = applyFormula(value, patchResultList.get(0));
patchResultList.get(0).setValue(value);
patchResultList.get(0).setIndex(index);
patchResultList.get(0).setBracket(bracket);
resultStringValues.put(patchResultList.get(0).getId(),
Float.isNaN(value) ? ""
: String.valueOf(roundSignificant(value)));
brackets.put(patchResultList.get(0).getId(), bracket);
}
} else {
for (PatchResult patchResult : patchResultList) {
// get colours from strip json description for this patch
List<ColorItem> colors = patchResult.getPatch().getColors();
float[] result = ResultUtils.calculateResultSingle(patchResult.getLab(), colors);
index = (int) result[0];
value = result[1];
bracket = createBracket(result[2], result[3]);
// apply formula when present
value = applyFormula(value, patchResult);
patchResult.setValue(value);
patchResult.setIndex(index);
patchResult.setBracket(bracket);
// Put the result into results list
resultStringValues.put(patchResult.getPatch().getId(),
Float.isNaN(value) ? ""
: String.valueOf(roundSignificant(value)));
brackets.put(patchResultList.get(0).getId(), bracket);
}
}
return patchResultList;
}
// displays results and creates image to send to database
// if patchResultList is null, it means that the strip was not found.
// In that case, we show a default error image.
private void showResults(List<PatchResult> patchResultList, TestInfo testInfo) {
// create empty result image to which everything is concatenated
totalImage = Bitmap.createBitmap(IMG_WIDTH, 1, Bitmap.Config.ARGB_8888);
// create and display view with results
// here, the total result image is also created
createView(testInfo, patchResultList);
// show buttons
buttonSave.setVisibility(View.VISIBLE);
}
private void createView(TestInfo testInfo, List<PatchResult> patchResultList) {
// create view in case the strip was not found
if (patchResultList == null || patchResultList.size() == 0) {
String patchDescription = testInfo.getName();
inflateView(patchDescription, "", null);
}
// else create view in case the strip is of type GROUP
else if (testInfo.getGroupingType() == GroupType.GROUP) {
// handle any calculated result to be displayed
displayCalculatedResults(testInfo, patchResultList);
PatchResult patchResult = patchResultList.get(0);
String patchDescription = patchResult.getPatch().getName();
String unit = patchResult.getPatch().getUnit();
String valueString = createValueUnitString(patchResult.getValue(), unit, getString(R.string.no_result));
if (AppPreferences.isTestMode() && patchResultList.size() == 0) {
patchDescription = testInfo.getResults().get(0).getName();
unit = testInfo.getResults().get(0).getUnit();
valueString = createValueUnitString(0, unit, getString(R.string.no_result));
}
// create image to display on screen
Bitmap resultImage = createResultImageGroup(patchResultList);
inflateView(patchDescription, valueString, resultImage);
Bitmap valueImage = createValueBitmap(patchResult, getString(R.string.no_result));
totalImage = concatTwoBitmaps(valueImage, resultImage);
} else {
// create view in case the strip is of type INDIVIDUAL
// handle any calculated result to be displayed
displayCalculatedResults(testInfo, patchResultList);
if (AppPreferences.isTestMode() && patchResultList.size() == 0) {
String patchDescription = testInfo.getResults().get(0).getName();
String unit = testInfo.getResults().get(0).getUnit();
String valueString = createValueUnitString(0, unit, getString(R.string.no_result));
inflateView(patchDescription, valueString, null);
}
for (PatchResult patchResult : patchResultList) {
// create strings for description, unit, and value
String patchDescription = patchResult.getPatch().getName();
String unit = patchResult.getPatch().getUnit();
String valueString = createValueUnitString(patchResult.getValue(), unit, getString(R.string.no_result));
// create image to display on screen
Bitmap resultImage = createResultImageSingle(patchResult, testInfo);
inflateView(patchDescription, valueString, resultImage);
Bitmap valueImage = createValueBitmap(patchResult, getString(R.string.no_result));
resultImage = concatTwoBitmaps(valueImage, resultImage);
totalImage = concatTwoBitmaps(totalImage, resultImage);
}
}
}
@SuppressLint({"InflateParams"})
private void inflateView(String patchDescription, String valueString, Bitmap resultImage) {
LayoutInflater inflater = (LayoutInflater) Objects.requireNonNull(
getActivity()).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout itemResult;
if (inflater != null) {
itemResult = (LinearLayout) inflater.inflate(R.layout.item_result, null, false);
TextView textTitle = itemResult.findViewById(R.id.text_title);
textTitle.setText(patchDescription);
ImageView imageResult = itemResult.findViewById(R.id.image_result);
imageResult.setImageBitmap(resultImage);
TextView textResult = itemResult.findViewById(R.id.text_result);
if (valueString.isEmpty()) {
TextView text_error = itemResult.findViewById(R.id.text_error);
text_error.setVisibility(View.VISIBLE);
textResult.setVisibility(View.GONE);
} else {
textResult.setText(valueString);
}
resultLayout.addView(itemResult);
}
}
// measure the average colour of a single patch.
private float[] getPatchColour(float[][][] img, Result patch, TestInfo brand) {
// pixels per mm on the strip image
double stripRatio = mDecodeData.getStripPixelWidth() / brand.getStripLength();
double x = patch.getPatchPos() * stripRatio;
double y = 0.5 * patch.getPatchWidth() * stripRatio;
double halfSize = 0.5 * Constants.STRIP_WIDTH_FRACTION * patch.getPatchWidth();
int tlx = (int) Math.round(x - halfSize);
int tly = (int) Math.round(y - halfSize);
int brx = (int) Math.round(x + halfSize);
int bry = (int) Math.round(y + halfSize);
int total = 0;
float X = 0;
float Y = 0;
float Z = 0;
for (int i = tlx; i <= brx; i++) {
for (int j = tly; j <= bry; j++) {
X += img[j][i][0];
Y += img[j][i][1];
Z += img[j][i][2];
total++;
}
}
return new float[]{X / total, Y / total, Z / total};
}
private float applyFormula(float value, PatchResult patchResult) {
// if we don't have a valid result, return the value unchanged
if (value == -1 || Float.isNaN(value)) {
return value;
}
if (!patchResult.getPatch().getFormula().isEmpty()) {
return (float) MathUtil.eval(String.format(Locale.US,
patchResult.getPatch().getFormula(), value));
}
// if we didn't have a formula, return the unchanged value.
return value;
}
/**
* When result item does not have a patch but exists solely to display a calculated result
*
* @param testInfo - the test info
* @param patchResultList - results for the patches
*/
private void displayCalculatedResults(TestInfo testInfo, List<PatchResult> patchResultList) {
// if testInfo has a displayResult items
if (testInfo.getResults() != null) {
for (Result displayResult : testInfo.getResults()) {
// if displayResult formula exists then calculate and display
if (displayResult.getColors().size() == 0 && !displayResult.getFormula().isEmpty()) {
String patchDescription = displayResult.getName();
String unit = displayResult.getUnit();
Object[] results;
if (testInfo.getGroupingType() == GroupType.GROUP) {
results = new Object[1];
results[0] = patchResultList.get(0).getValue();
} else {
// get all the other results for this test
results = new Object[patchResultList.size()];
for (int i = 0; i < patchResultList.size(); i++) {
results[i] = patchResultList.get(i).getValue();
}
}
double calculatedResult;
try {
calculatedResult = MathUtil.eval(String.format(Locale.US,
displayResult.getFormula(), results));
} catch (Exception e) {
inflateView(patchDescription, createValueUnitString(
-1, unit, getString(R.string.no_result)), null);
return;
}
resultStringValues.put(displayResult.getId(), String.valueOf(calculatedResult));
inflateView(patchDescription, createValueUnitString(
(float) calculatedResult, unit, getString(R.string.no_result)), null);
}
}
}
}
private String createBracket(float left, float right) {
return "[" + createValueString(left) + "," + createValueString(right) + "]";
}
} | 18,934 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
StripMeasureFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/ui/StripMeasureFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.ui;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.sensor.striptest.utils.Constants;
import org.akvo.caddisfly.sensor.striptest.utils.MessageUtils;
import org.akvo.caddisfly.sensor.striptest.widget.PercentageMeterView;
public class StripMeasureFragment extends Fragment {
private static final long INITIAL_DELAY_MILLIS = 200;
private static StriptestHandler mStriptestHandler;
private ProgressBar progressBar;
private TextSwitcher textSwitcher;
private PercentageMeterView exposureView;
private StriptestHandler.State currentState;
@NonNull
public static StripMeasureFragment newInstance(StriptestHandler striptestHandler) {
mStriptestHandler = striptestHandler;
return new StripMeasureFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_strip_measure, container, false);
exposureView = rootView.findViewById(R.id.quality_brightness);
return rootView;
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
progressBar = view.findViewById(R.id.progressBar);
if (progressBar != null) {
progressBar.setMax(Constants.COUNT_QUALITY_CHECK_LIMIT);
progressBar.setProgress(0);
}
TextView textBottom = view.findViewById(R.id.text_bottom);
textSwitcher = view.findViewById(R.id.textSwitcher);
if (textSwitcher != null) {
textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
private TextView textView;
private boolean isFirst = true;
@Override
public View makeView() {
if (isFirst) {
isFirst = false;
textView = view.findViewById(R.id.textMessage1);
((ViewGroup) textView.getParent()).removeViewAt(0);
} else {
textView = view.findViewById(R.id.textMessage2);
((ViewGroup) textView.getParent()).removeViewAt(0);
}
return textView;
}
});
new Handler().postDelayed(() -> {
if (isAdded()) {
textSwitcher.setText(getString(R.string.detecting_color_card));
}
}, INITIAL_DELAY_MILLIS);
}
mStriptestHandler.setTextSwitcher(textSwitcher);
if (currentState == StriptestHandler.State.MEASURE) {
textBottom.setText(R.string.measure_instruction);
}
}
@Override
public void onResume() {
super.onResume();
// hand over to state machine
MessageUtils.sendMessage(mStriptestHandler, StriptestHandler.START_PREVIEW_MESSAGE, 0);
}
void showQuality(int value) {
if (exposureView != null) {
exposureView.setPercentage((float) value);
}
}
void setState(StriptestHandler.State state) {
currentState = state;
}
void setProgress(int progress) {
if (progressBar != null) {
progressBar.setProgress(progress);
}
}
}
| 4,709 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
StripMeasureActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/ui/StripMeasureActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.ui;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.helper.SoundPoolPlayer;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.striptest.camera.CameraOperationsManager;
import org.akvo.caddisfly.sensor.striptest.camera.CameraPreview;
import org.akvo.caddisfly.sensor.striptest.models.TimeDelayDetail;
import org.akvo.caddisfly.sensor.striptest.widget.FinderPatternIndicatorView;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.util.ImageUtil;
import org.akvo.caddisfly.widget.TimerView;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import timber.log.Timber;
public class StripMeasureActivity extends BaseActivity implements StripMeasureListener {
public static final boolean DEBUG = false;
// a handler to handle the state machine of the preview, capture, decode, fullCapture cycle
private StriptestHandler mStriptestHandler;
private FinderPatternIndicatorView mFinderPatternIndicatorView;
private TimerView mTimerCountdown;
@Nullable
private WeakReference<Camera> wrCamera;
private Camera mCamera;
private CameraPreview mCameraPreview;
private FrameLayout previewLayout;
private SoundPoolPlayer sound;
private WeakReference<StripMeasureActivity> mActivity;
private StripMeasureFragment stripMeasureFragment;
private List<Result> patches;
// CameraOperationsManager wraps the camera API
private CameraOperationsManager mCameraOpsManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sound = new SoundPoolPlayer(this);
setContentView(R.layout.activity_strip_measure);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mFinderPatternIndicatorView =
findViewById(R.id.finder_indicator);
mTimerCountdown = findViewById(R.id.countdownTimer);
mActivity = new WeakReference<>(this);
}
@Override
public void onResume() {
super.onResume();
TestInfo testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
int currentStage = getIntent().getIntExtra(ConstantKey.TEST_STAGE, 1);
boolean startMeasure = getIntent().getBooleanExtra(ConstantKey.START_MEASURE, false);
if (testInfo != null && testInfo.getUuid() != null) {
setTitle(testInfo.getName());
patches = testInfo.getResults();
if (mCameraOpsManager == null) {
mCameraOpsManager = new CameraOperationsManager(testInfo.getName());
}
} else {
finish();
}
// create striptestHandler
// as this handler is created on the current thread, it is part of the UI thread.
// So we don't want to do actual work on it - just coordinate.
// The camera and the decoder get their own thread.
if (mStriptestHandler == null) {
mStriptestHandler = new StriptestHandler(this,
mCameraOpsManager, mFinderPatternIndicatorView, testInfo, currentStage);
}
mCameraOpsManager.setStriptestHandler(mStriptestHandler);
if (startMeasure) {
mStriptestHandler.setStatus(StriptestHandler.State.MEASURE);
} else {
mStriptestHandler.setStatus(StriptestHandler.State.PREPARE);
}
// we use a set to remove duplicates
Set<int[]> timeDelaySet = new HashSet<>();
double currentPatch = -1;
for (int i = 0; i < patches.size(); i++) {
double nextPatch = patches.get(i).getTimeDelay();
// if item has no colors then it is a calculated result based on formula so don't add it to set
if (patches.get(i).getColors().size() > 0 && Math.abs(nextPatch - currentPatch) > 0.001) {
timeDelaySet.add(new int[]{patches.get(i).getTestStage(), (int) Math.round(nextPatch)});
currentPatch = nextPatch;
}
}
List<TimeDelayDetail> timeDelays = new ArrayList<>();
for (int[] value : timeDelaySet) {
timeDelays.add(new TimeDelayDetail(value[0], value[1]));
}
Collections.sort(timeDelays);
mStriptestHandler.setTestData(timeDelays);
// initialize camera and start camera preview
startCameraPreview();
if (AppPreferences.isTestMode()) {
if (testInfo != null) {
byte[] bytes = ImageUtil.loadImageBytes(testInfo.getName());
if (bytes.length == 0) {
setResult(Activity.RESULT_OK, new Intent());
(new Handler()).postDelayed(this::finish, 4000);
}
}
}
}
private void startCameraPreview() {
previewLayout = findViewById(R.id.camera_preview);
mCameraPreview = mCameraOpsManager.initCamera(this);
mCamera = mCameraPreview.getCamera();
if (mCamera == null) {
Toast.makeText(this.getApplicationContext(), "Could not instantiate the camera",
Toast.LENGTH_SHORT).show();
finish();
} else {
try {
wrCamera = new WeakReference<>(mCamera);
previewLayout.removeAllViews();
if (mCameraPreview != null) {
previewLayout.addView(mCameraPreview);
} else {
finish();
}
} catch (Exception e) {
Timber.e(e);
}
}
}
// started from within camera preview
public void initPreviewFragment() {
try {
if (stripMeasureFragment == null) {
stripMeasureFragment = StripMeasureFragment.newInstance(mStriptestHandler);
mStriptestHandler.setFragment(stripMeasureFragment);
getSupportFragmentManager().beginTransaction().replace(
R.id.layout_cameraPlaceholder, stripMeasureFragment
).commit();
}
} catch (Exception e) {
Timber.e(e);
}
}
@Override
public void moveToInstructions(int testStage) {
Intent resultIntent = new Intent(getIntent());
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
@Override
public void moveToResults() {
Intent resultIntent = new Intent(getIntent());
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
@Override
public void showTimer() {
if (mTimerCountdown.getVisibility() != View.VISIBLE)
mTimerCountdown.setVisibility(View.VISIBLE);
}
@Override
public void playSound() {
sound.playShortResource(R.raw.futurebeep2);
}
@Override
public void updateTimer(int value) {
mTimerCountdown.setProgress(value, 60);
}
@Override
public void onPause() {
releaseResources();
if (!isFinishing()) {
finish();
}
super.onPause();
}
private void releaseResources() {
if (mCamera != null) {
mCameraOpsManager.stopAutofocus();
mCameraOpsManager.stopCamera();
mCamera.setOneShotPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (mStriptestHandler != null) {
mStriptestHandler.quitSynchronously();
mStriptestHandler = null;
}
if (mActivity != null) {
mActivity.clear();
mActivity = null;
}
if (wrCamera != null) {
wrCamera.clear();
wrCamera = null;
}
if (mCameraPreview != null && previewLayout != null) {
previewLayout.removeView(mCameraPreview);
mCameraPreview = null;
}
}
/**
* Store previewLayout info in global properties for later use.
* w: actual size of the preview window
* h: actual size of the preview window
* previewImageWidth: size of image returned from camera
* previewImageHeight: size of image returned from camera
*/
public void setPreviewProperties(int w, int h, int previewImageWidth, int previewImageHeight) {
if (mCamera != null && mCameraPreview != null) {
StriptestHandler.getDecodeData().setDecodeWidth(previewImageWidth);
StriptestHandler.getDecodeData().setDecodeHeight(previewImageHeight);
mFinderPatternIndicatorView.setMeasure(w, h, previewImageWidth, previewImageHeight);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
sound.release();
}
}
| 10,349 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DecodeProcessor.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/decode/DecodeProcessor.java | package org.akvo.caddisfly.sensor.striptest.decode;
import android.os.Handler;
import android.os.HandlerThread;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.sensor.striptest.models.CalibrationCardData;
import org.akvo.caddisfly.sensor.striptest.models.DecodeData;
import org.akvo.caddisfly.sensor.striptest.qrdetector.BitMatrix;
import org.akvo.caddisfly.sensor.striptest.qrdetector.BitMatrixCreator;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPattern;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPatternFinder;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPatternInfo;
import org.akvo.caddisfly.sensor.striptest.qrdetector.PerspectiveTransform;
import org.akvo.caddisfly.sensor.striptest.ui.StriptestHandler;
import org.akvo.caddisfly.sensor.striptest.utils.CalibrationCardUtils;
import org.akvo.caddisfly.sensor.striptest.utils.CalibrationUtils;
import org.akvo.caddisfly.sensor.striptest.utils.ColorUtils;
import org.akvo.caddisfly.sensor.striptest.utils.Constants;
import org.akvo.caddisfly.sensor.striptest.utils.ImageUtils;
import org.akvo.caddisfly.sensor.striptest.utils.MessageUtils;
import org.apache.commons.math3.linear.RealMatrix;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DecodeProcessor {
public static final int NO_TILT = -1;
private static final int DEGREES_90 = 90;
private static final int DEGREES_180 = 180;
private static final int DEGREES_0 = 0;
// holds reference to the striptestHandler, which we need to pass messages
private final StriptestHandler striptestHandler;
/********************************** check exposure ******************************************/
private final Runnable runExposureQualityCheck = () -> {
try {
checkExposureQuality();
} catch (Exception e) {
// TODO find out how we gracefully get out in this case
}
};
/*********************************** check shadow quality ***********************************/
private final Runnable runShadowQualityCheck = () -> {
try {
checkShadowQuality();
} catch (Exception e) {
// TODO find out how we gracefully get out in this case
}
};
/********************************** calibration *********************************************/
private final Runnable runCalibration = () -> {
try {
calibrateCard();
} catch (Exception e) {
// TODO find out how we gracefully get out in this case
}
};
private HandlerThread mDecodeThread;
private Handler mDecodeHandler;
// instance of BitMatrixCreator
private BitMatrixCreator mBitMatrixCreator;
/******************************************* find possible centers **************************/
private final Runnable runFindPossibleCenters = () -> {
try {
findPossibleCenters();
} catch (Exception e) {
// TODO find out how we gracefully get out in this case
//throw new RuntimeException("Can't start finding centers");
}
};
private int mCurrentDelay;
/*********************************** store data *********************************************/
private final Runnable runStoreData = () -> {
try {
storeData();
} catch (Exception e) {
// TODO find out how we gracefully get out in this case
}
};
public DecodeProcessor(StriptestHandler striptestHandler) {
mDecodeThread = new HandlerThread("DecodeProcessor");
mDecodeThread.start();
mDecodeHandler = new Handler(mDecodeThread.getLooper());
this.striptestHandler = striptestHandler;
}
private static float distance(double x1, double y1, double x2, double y2) {
return (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
//method to calculate the amount of perspective, based on the difference of distances at the top and sides
// horizontal and vertical are according to calibration card in landscape view
@Nullable
private static float[] getTilt(@Nullable FinderPatternInfo info) {
if (info == null) {
return null;
}
// compute distances
// in info, we have topLeft, topRight, bottomLeft, bottomRight
float hDistanceTop = distance(info.getBottomLeft().getX(), info.getBottomLeft().getY(),
info.getTopLeft().getX(), info.getTopLeft().getY());
float hDistanceBottom = distance(info.getBottomRight().getX(), info.getBottomRight().getY(),
info.getTopRight().getX(), info.getTopRight().getY());
float vDistanceLeft = distance(info.getBottomLeft().getX(), info.getBottomLeft().getY(),
info.getBottomRight().getX(), info.getBottomRight().getY());
float vDistanceRight = distance(info.getTopRight().getX(), info.getTopRight().getY(),
info.getTopLeft().getX(), info.getTopLeft().getY());
// return ratio of horizontal distances top and bottom and ratio of vertical distances left and right
return new float[]{hDistanceTop / hDistanceBottom, vDistanceLeft / vDistanceRight};
}
@SuppressWarnings("SameParameterValue")
private static float capValue(float val, float min, float max) {
if (val > max) {
return max;
}
return val < min ? min : val;
}
public void startFindPossibleCenters() {
if (mDecodeHandler != null) {
mDecodeHandler.removeCallbacks(runFindPossibleCenters);
mDecodeHandler.post(runFindPossibleCenters);
}
// else {
// TODO find out how we gracefully get out in this case
// throw new RuntimeException("can't find possible centers");
// }
}
private void findPossibleCenters() {
List<FinderPattern> possibleCenters;
FinderPatternInfo patternInfo;
BitMatrix bitMatrix;
DecodeData decodeData = StriptestHandler.getDecodeData();
final int decodeHeight = decodeData.getDecodeHeight();
final int decodeWidth = decodeData.getDecodeWidth();
if (mBitMatrixCreator == null) {
mBitMatrixCreator = new BitMatrixCreator(decodeWidth, decodeHeight);
}
// create a black and white bit matrix from our data. Cut out the part that interests us
try {
bitMatrix = BitMatrixCreator.createBitMatrix(decodeData.getDecodeImageByteArray(),
decodeWidth, decodeWidth, decodeHeight, 0, 0,
(int) Math.round(decodeHeight * Constants.CROP_FINDER_PATTERN_FACTOR),
decodeHeight);
} catch (Exception e) {
MessageUtils.sendMessage(striptestHandler, StriptestHandler.DECODE_FAILED_MESSAGE, 0);
return;
}
// if we have valid data, try to find the finder patterns
if (bitMatrix != null && decodeWidth > 0 && decodeHeight > 0) {
FinderPatternFinder finderPatternFinder = new FinderPatternFinder(bitMatrix);
try {
patternInfo = finderPatternFinder.find(null);
possibleCenters = finderPatternFinder.getPossibleCenters();
//We only get four finder patterns back. If one of them is very small, we know we have
// picked up noise and we should break early.
for (int i = 0; i < possibleCenters.size(); i++) {
if (possibleCenters.get(i).getEstimatedModuleSize() < 2) {
decodeData.setPatternInfo(null);
MessageUtils.sendMessage(striptestHandler, StriptestHandler.DECODE_FAILED_MESSAGE, 0);
return;
}
}
} catch (Exception ignored) {
// patterns where not detected.
decodeData.setPatternInfo(null);
MessageUtils.sendMessage(striptestHandler, StriptestHandler.DECODE_FAILED_MESSAGE, 0);
return;
}
// compute and store tilt and distance check
decodeData.setTilt(getDegrees(Objects.requireNonNull(getTilt(patternInfo))));
decodeData.setDistanceOk(distanceOk(patternInfo, decodeHeight));
// store finder patterns
decodeData.setPatternInfo(patternInfo);
decodeData.setFinderPatternsFound(possibleCenters);
// store decode image size
// decodeData.setDecodeSize(new Size(decodeWidth, decodeHeight));
// get the version number from the barcode printed on the card
if (possibleCenters.size() == 4 && !decodeData.isCardVersionEstablished()) {
int versionNumber = CalibrationCardUtils.decodeCalibrationCardCode(possibleCenters, bitMatrix);
decodeData.addVersionNumber(versionNumber);
}
// send the message that the decoding was successful
MessageUtils.sendMessage(striptestHandler, StriptestHandler.DECODE_SUCCEEDED_MESSAGE, 0);
}
}
public void startExposureQualityCheck() {
if (mDecodeHandler != null) {
mDecodeHandler.removeCallbacks(runExposureQualityCheck);
mDecodeHandler.post(runExposureQualityCheck);
}
// else {
// TODO find out how we gracefully get out in this case
// }
}
/*
* checks exposure of image, by looking at the Y value of the white. It should be as high as
* possible, without being overexposed.
*/
private void checkExposureQuality() {
DecodeData decodeData = StriptestHandler.getDecodeData();
int maxY;
int maxMaxY = 0;
if (decodeData.getFinderPatternsFound() != null) {
for (FinderPattern fp : decodeData.getFinderPatternsFound()) {
maxY = ImageUtils.maxY(decodeData, fp);
if (maxY > maxMaxY) {
maxMaxY = maxY;
}
}
}
if (maxMaxY < Constants.MAX_LUM_LOWER) {
// send the message that the Exposure should be changed upwards
MessageUtils.sendMessage(striptestHandler, StriptestHandler.CHANGE_EXPOSURE_MESSAGE, 2);
return;
}
if (maxMaxY > Constants.MAX_LUM_UPPER) {
// send the message that the Exposure should be changed downwards
MessageUtils.sendMessage(striptestHandler, StriptestHandler.CHANGE_EXPOSURE_MESSAGE, -2);
return;
}
// send the message that the Exposure is ok
MessageUtils.sendMessage(striptestHandler, StriptestHandler.EXPOSURE_OK_MESSAGE, 0);
}
public void startShadowQualityCheck() {
if (mDecodeHandler != null) {
mDecodeHandler.removeCallbacks(runShadowQualityCheck);
mDecodeHandler.post(runShadowQualityCheck);
}
// else {
// TODO find out how we gracefully get out in this case
// }
}
/*
* checks exposure of image, by looking at the homogeneity of the white values.
*/
private void checkShadowQuality() {
DecodeData decodeData = StriptestHandler.getDecodeData();
CalibrationCardData calCardData = StriptestHandler.getCalCardData();
float tlCardX = calCardData.hSize;
float tlCardY = 0f;
float trCardX = calCardData.hSize;
float trCardY = calCardData.vSize;
float blCardX = 0f;
float blCardY = 0;
float brCardX = 0;
float brCardY = calCardData.vSize;
FinderPatternInfo info = decodeData.getPatternInfo();
if (info == null) {
MessageUtils.sendMessage(striptestHandler, StriptestHandler.DECODE_FAILED_MESSAGE, 0);
return;
}
float tlX = info.getTopLeft().getX();
float tlY = info.getTopLeft().getY();
float trX = info.getTopRight().getX();
float trY = info.getTopRight().getY();
float blX = info.getBottomLeft().getX();
float blY = info.getBottomLeft().getY();
float brX = info.getBottomRight().getX();
float brY = info.getBottomRight().getY();
// create transform from picture coordinates to calibration card coordinates
// the calibration card starts with 0,0 in the top left corner, and is measured in mm
PerspectiveTransform cardToImageTransform = PerspectiveTransform.quadrilateralToQuadrilateral(
tlCardX, tlCardY, trCardX, trCardY, blCardX, blCardY, brCardX, brCardY,
tlX, tlY, trX, trY, blX, blY, brX, brY);
decodeData.setCardToImageTransform(cardToImageTransform);
// get white point array
float[][] points = CalibrationCardUtils.createWhitePointArray(decodeData, calCardData);
// store in decodeData
decodeData.setWhitePointArray(points);
if (points.length > 0) {
// select those that are not ok, looking at Y only
float sumY = 0;
float deviation;
for (float[] point : points) {
sumY += point[2];
}
// compute average illumination Y value
float avgY = sumY / points.length;
// take reciprocal for efficiency reasons
float avgYReciprocal = 1.0f / avgY;
int numDev = 0;
List<float[]> badPoints = new ArrayList<>();
for (float[] point : points) {
deviation = Math.abs(point[2] - avgY) * avgYReciprocal;
// count number of points that differ more than CONTRAST_DEVIATION_FRACTION from the average
if (deviation > Constants.CONTRAST_DEVIATION_FRACTION) {
badPoints.add(point);
numDev++;
// extra penalty for points that differ more than CONTRAST_MAX_DEVIATION_FRACTION from the average
if (deviation > Constants.CONTRAST_MAX_DEVIATION_FRACTION) {
numDev += 4;
}
}
}
// store in decodeData, and send message
decodeData.setShadowPoints(badPoints);
// compute percentage of good points
float devPercent = 100f - (100.0f * numDev) / points.length;
// decodeData.setPercentageShadow(Math.min(Math.max(50f, devPercent), 100f));
// if the percentage of good point is under the limit (something like 90%), we fail the test
if (devPercent < Constants.SHADOW_PERCENTAGE_LIMIT) {
MessageUtils.sendMessage(striptestHandler, StriptestHandler.SHADOW_QUALITY_FAILED_MESSAGE, 0);
} else {
MessageUtils.sendMessage(striptestHandler, StriptestHandler.SHADOW_QUALITY_OK_MESSAGE, 0);
}
} else {
MessageUtils.sendMessage(striptestHandler, StriptestHandler.SHADOW_QUALITY_OK_MESSAGE, 0);
}
}
public void storeImageData(int currentDelay) {
if (mDecodeHandler != null) {
mDecodeHandler.removeCallbacks(runStoreData);
mCurrentDelay = currentDelay;
mDecodeHandler.post(runStoreData);
}
// else {
// TODO find out how we gracefully get out in this case
// }
}
private void storeData() {
// subtract black part and put it in a rectangle. Do the calibration at the same time.
// 1) determine size of new image array
// 2) loop over pixels of new image array
// 3) compute location of pixel using card-to-image transform
// 4) apply illumination correction
// 5) apply calibration
// 6) store new array
float[] stripArea = StriptestHandler.getCalCardData().getStripArea();
DecodeData decodeData = StriptestHandler.getDecodeData();
PerspectiveTransform cardToImageTransform = decodeData.getCardToImageTransform();
TestInfo testInfo = decodeData.getTestInfo();
float[] illumination = decodeData.getIlluminationData();
RealMatrix calMatrix = decodeData.getCalMatrix();
// we cut of an edge of 1mm at the edges, to avoid any white space captured at the edge
float tlx = stripArea[0] + Constants.SKIP_MM_EDGE;
float tly = stripArea[1] + Constants.SKIP_MM_EDGE;
float brx = stripArea[2] - Constants.SKIP_MM_EDGE;
float bry = stripArea[3] - Constants.SKIP_MM_EDGE;
float widthMm = brx - tlx;
float heightMm = bry - tly;
float mmPerPixel = 1.0f / Constants.PIXEL_PER_MM;
int widthPixels = Math.round(widthMm * Constants.PIXEL_PER_MM);
int heightPixels = Math.round(heightMm * Constants.PIXEL_PER_MM);
float[][][] XYZ = new float[widthPixels][heightPixels][3];
float[] rowX = new float[widthPixels];
float[] rowY = new float[widthPixels];
byte[] iDataArray = decodeData.getDecodeImageByteArray();
int rowStride = decodeData.getDecodeWidth();
int frameSize = rowStride * decodeData.getDecodeHeight();
int uvPos;
int xIm;
int yIm;
float xCard;
float yCard;
float xCal;
float yCal;
float zCal;
float Y;
float U;
float V;
float[] col;
float[] xyz;
float[] coefficient = new float[16];
float c0c0;
float c1c1;
float c2c2;
float ONE_THIRD = 1.0f / 3.0f;
// we use a lookup table to speed this thing up.
Map<String, float[]> colourMap = new HashMap<>();
String label;
// transform strip area image to calibrated values
for (int yi = 0; yi < heightPixels; yi++) {
// fill a row with card-based coordinates, and transform them to image based coordinates
for (int xi = 0; xi < widthPixels; xi++) {
rowX[xi] = xi * mmPerPixel + tlx;
rowY[xi] = yi * mmPerPixel + tly;
}
cardToImageTransform.transformPoints(rowX, rowY);
// get YUV colours from image
for (int xi = 0; xi < widthPixels; xi++) {
xIm = Math.round(rowX[xi]);
yIm = Math.round(rowY[xi]);
uvPos = frameSize + (yIm >> 1) * rowStride;
Y = (0xff & iDataArray[xIm + yIm * rowStride]);
U = (0xff & ((int) iDataArray[uvPos + (xIm & ~1) + 1])) - 128;
V = (0xff & ((int) iDataArray[uvPos + (xIm & ~1)])) - 128;
xCard = xi * mmPerPixel + tlx;
yCard = yi * mmPerPixel + tly;
//Apply illumination transform
Y = capValue(Y - (illumination[0] * xCard + illumination[1] * yCard +
+illumination[2] * xCard * xCard + illumination[3] * yCard * yCard
+ illumination[4] * xCard * yCard + illumination[5])
+ illumination[6], 0.0f, 255.0f);
// from here on, it is all just colour transforms fixed values.
// therefore, we try to shortcut this by using a hashMap.
label = Math.round(Y) + "|" + Math.round(U) + "|" + Math.round(V);
if (colourMap.containsKey(label)) {
xyz = colourMap.get(label);
XYZ[xi][yi][0] = xyz[0];
XYZ[xi][yi][1] = xyz[1];
XYZ[xi][yi][2] = xyz[2];
} else {
// transform YUV to linear RGB
col = ColorUtils.YUVtoLinearRGB(new float[]{Y, U, V});
// create transformation coefficients
c0c0 = col[0] * col[0];
c1c1 = col[1] * col[1];
c2c2 = col[2] * col[2];
coefficient[0] = col[0];
coefficient[1] = col[1];
coefficient[2] = col[2];
coefficient[3] = (float) Math.sqrt(col[0] * col[1]); // sqrt(R * G)
coefficient[4] = (float) Math.sqrt(col[1] * col[2]); // sqrt(G * B)
coefficient[5] = (float) Math.sqrt(col[0] * col[2]); // sqrt(R * B)
coefficient[6] = (float) Math.pow(col[0] * c1c1, ONE_THIRD); // RGG ^ 1/3
coefficient[7] = (float) Math.pow(col[1] * c2c2, ONE_THIRD); // GBB ^ 1/3
coefficient[8] = (float) Math.pow(col[0] * c2c2, ONE_THIRD); // RBB ^ 1/3
coefficient[9] = (float) Math.pow(col[1] * c0c0, ONE_THIRD); // GRR ^ 1/3
coefficient[10] = (float) Math.pow(col[2] * c1c1, ONE_THIRD); // BGG ^ 1/3
coefficient[11] = (float) Math.pow(col[2] * c0c0, ONE_THIRD); // BRR ^ 1/3
coefficient[12] = (float) Math.pow(col[0] * col[1] * col[2], ONE_THIRD); // RGB ^ 1/3
xCal = 0;
yCal = 0;
zCal = 0;
for (int i = 0; i <= 12; i++) {
xCal += coefficient[i] * calMatrix.getEntry(i, 0);
yCal += coefficient[i] * calMatrix.getEntry(i, 1);
zCal += coefficient[i] * calMatrix.getEntry(i, 2);
}
// store the result in the image
// XYZ is scale 0..100
XYZ[xi][yi][0] = xCal;
XYZ[xi][yi][1] = yCal;
XYZ[xi][yi][2] = zCal;
// store the colour in the hashMap
colourMap.put(label, new float[]{xCal, yCal, zCal});
}
}
}
// get out strip
float ratioPixelPerMm = widthPixels / widthMm;
float[][][] result = ImageUtils.detectStrip(XYZ, widthPixels, heightPixels,
testInfo.getStripLength(), ratioPixelPerMm);
// store image in decodeData object
// NOTE: the image has been transposed in the detectStrip method, so here the rows
// correspond to the vertical dimension.
if (result != null) {
decodeData.addStripImage(result, mCurrentDelay);
decodeData.setStripPixelWidth(result[0].length);
} else {
//todo: check null argument
decodeData.addStripImage(null, mCurrentDelay);
decodeData.setStripPixelWidth(0);
}
MessageUtils.sendMessage(striptestHandler, StriptestHandler.IMAGE_SAVED_MESSAGE, 0);
}
public void startCalibration() {
if (mDecodeHandler != null) {
mDecodeHandler.removeCallbacks(runCalibration);
mDecodeHandler.post(runCalibration);
}
// else {
// TODO find out how we gracefully get out in this case
// }
}
private void calibrateCard() {
// get calibrationPatches as map
CalibrationCardData calCardData = StriptestHandler.getCalCardData();
DecodeData decodeData = StriptestHandler.getDecodeData();
Map<String, float[]> calXYZMap = CalibrationCardUtils.calCardXYZ(calCardData.getCalValues());
// measure patches
// YUV here has full scale: [0..255, -128..128, -128 .. 128]
Map<String, float[]> patchYUVMap = CalibrationCardUtils.measurePatches(calCardData, StriptestHandler.getDecodeData());
// correct inhomogeneity of illumination
Map<String, float[]> patchYUVMapCorrected = CalibrationUtils.correctIllumination(patchYUVMap, decodeData, calCardData);
// color transform: Android YUV (YCbCr) to sRGB D65
Map<String, float[]> patchRGBMap = CalibrationCardUtils.YUVtoLinearRGB(patchYUVMapCorrected);
Map<String, float[]> resultXYZMap;
// float[] deltaE2000Stats2;
// perform 3rd order root-polynomial calibration on RGB -> XYZ data
resultXYZMap = CalibrationUtils.rootPolynomialCalibration(decodeData, calXYZMap, patchRGBMap);
// measure the distance in terms of deltaE2000
float[] deltaE2000Stats = CalibrationCardUtils.deltaE2000stats(calXYZMap, resultXYZMap);
// set deltaE2000 stats
decodeData.setDeltaEStats(deltaE2000Stats);
MessageUtils.sendMessage(striptestHandler, StriptestHandler.CALIBRATION_DONE_MESSAGE, 0);
}
/********************************* utility methods ******************************************/
public void stopDecodeThread() {
mDecodeThread.quitSafely();
try {
mDecodeThread.join();
mDecodeThread = null;
mDecodeHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private boolean distanceOk(@Nullable FinderPatternInfo info, int decodeHeight) {
float leftStop = Constants.MAX_CLOSER_DIFF * decodeHeight;
float rightStop = (1 - Constants.MAX_CLOSER_DIFF) * decodeHeight;
return info != null &&
(info.getBottomLeft().getY() > rightStop &&
info.getTopLeft().getY() < leftStop &&
info.getBottomRight().getY() > rightStop &&
info.getTopRight().getY() < leftStop);
}
private int getDegrees(float[] tiltValues) {
int degrees;
// if the horizontal tilt is too large, indicate it
if (Math.abs(tiltValues[0] - 1) > Constants.MAX_TILT_DIFF) {
degrees = tiltValues[0] - 1 < 0 ? -DEGREES_90 : DEGREES_90;
return degrees;
}
// if the vertical tilt is too large, indicate it
if (Math.abs(tiltValues[1] - 1) > Constants.MAX_TILT_DIFF) {
degrees = tiltValues[1] - 1 < 0 ? DEGREES_180 : DEGREES_0;
return degrees;
}
// we don't have a tilt problem
return NO_TILT;
}
}
| 25,950 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PercentageMeterView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/widget/PercentageMeterView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
/**
* Created by linda on 11/5/15
*/
public class PercentageMeterView extends View {
private static final int NUMBER_OF_BARS = 10;
@NonNull
private final Paint paint;
private float percentage = Float.NaN;
// Red to green colour scale
private final int[][] colours = {{230, 53, 46}, {234, 91, 47}, {240, 132, 45}, {232, 168, 52}, {247, 211, 43}, {212, 216, 57}, {169, 204, 57},
{112, 186, 68}, {58, 171, 75}, {6, 155, 85}};
public PercentageMeterView(@NonNull Context context) {
this(context, null);
}
public PercentageMeterView(@NonNull Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PercentageMeterView(@NonNull Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
paint.setColor(Color.LTGRAY);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
}
@Override
public void onDraw(@NonNull Canvas canvas) {
if (Float.isNaN(percentage)) {
return;
}
canvas.save();
float barWidth = getHeight() / 3.0f;
float gutterWidth = 0.2f * barWidth;
float distHor = 0.5f * (getWidth() - (barWidth + gutterWidth) * NUMBER_OF_BARS);
canvas.translate(distHor, 0);
for (int i = 0; i < NUMBER_OF_BARS; i++) {
// Reset color to gray
paint.setColor(Color.LTGRAY);
if (percentage > 10 * i)
paint.setARGB(255, colours[i][0], colours[i][1], colours[i][2]);
canvas.drawRect(0f, 0f, 20, getHeight(), paint);
// Position next bar
canvas.translate(barWidth + gutterWidth, 0);
}
canvas.restore();
super.onDraw(canvas);
}
public void setPercentage(float percentage) {
this.percentage = percentage;
invalidate();
}
}
| 2,970 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
FinderPatternIndicatorView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/widget/FinderPatternIndicatorView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.sensor.striptest.decode.DecodeProcessor;
import org.akvo.caddisfly.sensor.striptest.qrdetector.FinderPattern;
import org.akvo.caddisfly.sensor.striptest.qrdetector.PerspectiveTransform;
import org.akvo.caddisfly.sensor.striptest.utils.Constants;
import java.util.List;
/**
* Created by linda on 9/9/15
*/
public class FinderPatternIndicatorView extends View {
private static int mGridStepDisplay;
private static int mGridStepImage;
private static double mScore = 0.0f;
private final int GRID_H = 15;
private final int GRID_V = 15;
private final Paint paint;
private final Paint paint2;
private final Bitmap arrowBitmap;
private final Bitmap closerBitmap;
private final Matrix matrix = new Matrix();
private List<FinderPattern> patterns;
private boolean[][] shadowGrid;
private int previewScreenHeight;
private int previewScreenWidth;
private int decodeHeight;
private int decodeWidth;
private int mFinderPatternViewWidth = 0;
private int mFinderPatternViewHeight = 0;
private int tilt = DecodeProcessor.NO_TILT;
private boolean showDistanceMessage = false;
private boolean showTiltMessage;
public FinderPatternIndicatorView(Context context) {
this(context, null);
}
public FinderPatternIndicatorView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FinderPatternIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setAntiAlias(false);
paint2 = new Paint();
paint2.setColor(Color.BLUE);
paint2.setAlpha(125);
paint2.setAntiAlias(false);
arrowBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.level);
closerBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.closer);
}
// Sets the various sizes.
// screenWidth: actual size of the reported preview screen
// screenHeight: actual size of the reported preview screen
// previewWidth: size of the image as taken by the camera
// previewHeight: size of the image as taken by the camera
// The crop factor (CROP_FINDER_PATTERN_FACTOR) is about 0.75
public void setMeasure(int screenWidth, int screenHeight, int previewWidth, int previewHeight) {
this.previewScreenHeight = screenHeight;
this.previewScreenWidth = screenWidth;
this.mFinderPatternViewWidth = screenWidth;
this.decodeWidth = previewWidth;
this.decodeHeight = previewHeight;
this.mFinderPatternViewHeight = (int) Math.round(screenWidth * Constants.CROP_FINDER_PATTERN_FACTOR);
// we divide the previewHeight into a number of parts
mGridStepDisplay = Math.round(screenWidth / GRID_H);
mGridStepImage = Math.round(previewHeight / GRID_H);
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (0 == mFinderPatternViewWidth || 0 == mFinderPatternViewHeight) {
setMeasuredDimension(width, height);
} else {
setMeasuredDimension(mFinderPatternViewWidth, mFinderPatternViewHeight);
}
}
/*
* display finder patterns on screen as green dots.
* height and width are the actual size of the image as it came from the camera
*/
public void showPatterns(List<FinderPattern> patternList, int tilt, boolean showTiltMessage, boolean showDistanceMessage, int width, int height) {
this.patterns = patternList;
this.decodeWidth = width;
this.decodeHeight = height;
this.tilt = tilt;
this.showDistanceMessage = showDistanceMessage;
this.showTiltMessage = showTiltMessage;
invalidate();
}
public void clearAll() {
this.patterns = null;
this.tilt = DecodeProcessor.NO_TILT;
this.showDistanceMessage = false;
this.showTiltMessage = false;
this.shadowGrid = null;
mScore = (4 * mScore) / 5.0;
invalidate();
}
public void showShadow(List<float[]> shadowPoints, PerspectiveTransform cardToImageTransform) {
shadowGrid = new boolean[GRID_H + 5][GRID_V + 5];
int xGrid;
int yGrid;
if (shadowPoints != null) {
// the points are in the coordinate system of the card (mm)
for (float[] point : shadowPoints) {
float[] points = new float[]{point[0], point[1]};
// cardToImageTransform transforms from card coordinates (mm) to camera image coordinates
cardToImageTransform.transformPoints(points);
xGrid = (int) Math.max(0, Math.floor((this.decodeHeight - points[1]) / mGridStepImage));
yGrid = (int) Math.floor(points[0] / mGridStepImage);
shadowGrid[xGrid][yGrid] = true;
}
}
invalidate();
}
// public void setColor(int color) {
// paint.setColor(color);
// }
//
@Override
public void onDraw(@NonNull Canvas canvas) {
if (patterns != null) {
// The canvas has a rotation of 90 degrees with respect to the camera preview
//Camera preview size is in landscape mode, canvas is in portrait mode
//the width of the canvas corresponds to the height of the decodeSize.
//float ratio = 1.0f * canvas.getWidth() / decodeHeight;
float hRatio = 1.0f * previewScreenWidth / decodeHeight;
float vRatio = 1.0f * previewScreenHeight / decodeWidth;
for (int i = 0; i < patterns.size(); i++) {
//The x of the canvas corresponds to the y of the pattern,
//The y of the canvas corresponds to the x of the pattern.
float x = previewScreenWidth - patterns.get(i).getY() * hRatio;
float y = patterns.get(i).getX() * vRatio;
canvas.drawCircle(x, y, 10, paint);
}
}
if (showTiltMessage) {
matrix.reset();
matrix.postTranslate(-arrowBitmap.getWidth() / 2, -arrowBitmap.getHeight() / 2); // Centers image
matrix.postRotate(tilt);
matrix.postTranslate(mFinderPatternViewWidth / 2f, mFinderPatternViewHeight / 2f);
canvas.drawBitmap(arrowBitmap, matrix, null);
}
if (showDistanceMessage) {
matrix.reset();
matrix.postTranslate(-closerBitmap.getWidth() / 2, -closerBitmap.getHeight() / 2); // Centers image
matrix.postTranslate(mFinderPatternViewWidth / 2f, mFinderPatternViewHeight / 2.5f);
canvas.drawBitmap(closerBitmap, matrix, null);
}
if (shadowGrid != null) {
float hRatio = 1.0f * previewScreenWidth / decodeHeight;
float vRatio = 1.0f * previewScreenHeight / decodeWidth;
float ratioRatio = vRatio / hRatio;
int xTop;
int yTop;
for (int i = 0; i < GRID_H; i++) {
for (int j = 0; j < GRID_V; j++) {
if (shadowGrid[i][j]) {
xTop = Math.round(i * mGridStepDisplay);
yTop = Math.round(j * mGridStepDisplay * ratioRatio);
canvas.drawRect(xTop, yTop, xTop + mGridStepDisplay, yTop + mGridStepDisplay, paint2);
}
}
}
}
super.onDraw(canvas);
}
}
| 8,934 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CameraPreview.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/camera/CameraPreview.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.camera;
import android.content.Context;
import android.graphics.Rect;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.common.Constants;
import org.akvo.caddisfly.sensor.striptest.ui.StripMeasureActivity;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import timber.log.Timber;
/**
* Created by linda on 7/7/15
*/
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final int MIN_CAMERA_WIDTH = 1300;
private final Camera mCamera;
private final StripMeasureActivity activity;
private int mPreviewWidth;
private int mPreviewHeight;
public CameraPreview(Context context) {
// create surfaceView
super(context);
// Create an instance of Camera
mCamera = TheCamera.getCameraInstance();
try {
activity = (StripMeasureActivity) context;
} catch (ClassCastException e) {
throw new IllegalArgumentException("must have CameraActivity as Context.", e);
}
// SurfaceHolder callback to track when underlying surface is created and destroyed.
SurfaceHolder mHolder = getHolder();
mHolder.addCallback(this);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
} catch (Exception e) {
Timber.d("Error setting camera preview: %s", e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder.getSurface() == null) {
// preview surface does not exist
return;
}
if (mCamera == null) {
//Camera was released
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or reformatting changes here
Camera.Size bestSize = setupCamera();
if (bestSize == null) return;
try {
mCamera.setPreviewDisplay(holder);
mPreviewWidth = bestSize.width;
mPreviewHeight = bestSize.height;
activity.setPreviewProperties(w, h, mPreviewWidth, mPreviewHeight);
activity.initPreviewFragment();
mCamera.startPreview();
try {
// if we are in FOCUS_MODE_AUTO, we have to start the autofocus here.
if (mCamera.getParameters().getFocusMode().equals(Camera.Parameters.FOCUS_MODE_AUTO)) {
mCamera.autoFocus((success, camera) -> {
// do nothing
});
}
} catch (Exception ignore) {
}
} catch (IOException e) {
Timber.e(e, mPreviewWidth + "x" + mPreviewHeight);
}
}
@Nullable
private Camera.Size setupCamera() {
Camera.Parameters parameters;
try {
parameters = mCamera.getParameters();
} catch (Exception e) {
return null;
}
if (parameters == null) {
return null;
}
Camera.Size bestSize = null;
List<Camera.Size> sizes = mCamera.getParameters().getSupportedPreviewSizes();
int maxWidth = 0;
for (Camera.Size size : sizes) {
if (size.width > MIN_CAMERA_WIDTH) {
continue;
}
if (size.width > maxWidth) {
bestSize = size;
maxWidth = size.width;
}
}
//portrait mode
mCamera.setDisplayOrientation(Constants.DEGREES_90);
//preview size
assert bestSize != null;
parameters.setPreviewSize(bestSize.width, bestSize.height);
Timber.d("Preview size set to:" + bestSize.width + "," + bestSize.height);
// default focus mode
String focusMode = Camera.Parameters.FOCUS_MODE_AUTO;
List<String> supportedFocusModes = parameters.getSupportedFocusModes();
// Select FOCUS_MODE_CONTINUOUS_PICTURE if available
// fall back on FOCUS_MODE_CONTINUOUS_VIDEO if the previous is not available
// fall back on FOCUS_MODE_AUTO if none are available
if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE;
} else if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO;
}
parameters.setFocusMode(focusMode);
Camera.Area cardArea = new Camera.Area(new Rect(-1000, -1000, -167, 1000), 1);
List<Camera.Area> cardAreaList = Collections.singletonList(cardArea);
if (parameters.getMaxNumFocusAreas() > 0) {
parameters.setFocusAreas(cardAreaList);
}
if (parameters.getWhiteBalance() != null) {
parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
}
if (parameters.getMaxNumMeteringAreas() > 0) {
parameters.setMeteringAreas(cardAreaList);
}
if (parameters.getFlashMode() != null) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
try {
mCamera.setParameters(parameters);
} catch (Exception e) {
Timber.e(e);
}
return bestSize;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (0 == mPreviewWidth || 0 == mPreviewHeight) {
setMeasuredDimension(width, height);
} else {
setMeasuredDimension(width, width * mPreviewWidth / mPreviewHeight);
}
}
public Camera getCamera() {
return mCamera;
}
}
| 7,498 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TheCamera.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/camera/TheCamera.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.camera;
import android.hardware.Camera;
/**
* Created by linda on 7/7/15
*/
final class TheCamera {
private TheCamera() {
}
/**
* A safe way to get an instance of the Camera object.
*/
static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
| 1,332 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CameraOperationsManager.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/striptest/camera/CameraOperationsManager.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.striptest.camera;
import android.content.Context;
import android.hardware.Camera;
import android.os.Handler;
import android.os.HandlerThread;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.striptest.ui.StripMeasureActivity;
import org.akvo.caddisfly.sensor.striptest.ui.StriptestHandler;
import org.akvo.caddisfly.sensor.striptest.utils.MessageUtils;
import org.akvo.caddisfly.util.ImageUtil;
import timber.log.Timber;
public class CameraOperationsManager {
private static final long AUTO_FOCUS_DELAY = 5000L;
// A Handler for running camera tasks in the background.
private Handler mCameraHandler;
private Camera mCamera;
private boolean changingExposure = false;
private final Runnable runAutoFocus = new Runnable() {
public void run() {
if (mCamera != null) {
if (!changingExposure) {
// Check the focus. This is mainly needed in order to restart focus that doesn't run anymore,
// which sometimes happens on Samsung devices.
mCamera.autoFocus((success, camera) -> {
// if we are in one of the other modes, we need to run 'cancelAutofocus' in order
// to start the continuous focus again. *sigh*
if (!camera.getParameters().getFocusMode().equals(Camera.Parameters.FOCUS_MODE_AUTO)) {
mCamera.cancelAutoFocus();
}
});
}
if (mCameraHandler != null) {
mCameraHandler.postDelayed(runAutoFocus, AUTO_FOCUS_DELAY);
}
}
}
};
private StriptestHandler mStriptestHandler;
private byte[] bytes;
private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] imageData, Camera camera) {
if (bytes != null && bytes.length > 0 && AppPreferences.isTestMode()) {
// Use test image if we are in test mode
StriptestHandler.getDecodeData().setDecodeImageByteArray(bytes);
} else {
// store image for later use
StriptestHandler.getDecodeData().setDecodeImageByteArray(imageData);
}
MessageUtils.sendMessage(mStriptestHandler,
StriptestHandler.DECODE_IMAGE_CAPTURED_MESSAGE, 0);
}
};
public CameraOperationsManager(String name) {
if (AppPreferences.isTestMode()) {
bytes = ImageUtil.loadImageBytes(name);
}
}
public CameraPreview initCamera(Context context) {
startCameraThread();
// open the camera and create a preview surface for it
CameraPreview cameraPreview = new CameraPreview(context);
mCamera = cameraPreview.getCamera();
return cameraPreview;
}
public void setStriptestHandler(StriptestHandler striptestHandler) {
this.mStriptestHandler = striptestHandler;
}
// TODO add cancel request
public void setDecodeImageCaptureRequest() {
if (mCameraHandler != null && mCamera != null) {
try {
mCameraHandler.post(() -> {
if (mCamera != null) {
mCamera.setOneShotPreviewCallback(previewCallback);
}
});
} catch (Exception ignored) {
// do nothing
}
}
}
///////////////////////////// autofocus handling ////////////////////////////////////////
// TODO check if these boundaries are ok
public void changeExposure(int exposureChange) {
int expComp = mCamera.getParameters().getExposureCompensation();
int newSetting = expComp + exposureChange;
// if we are within bounds, change the capture request
if (newSetting != expComp &&
newSetting <= mCamera.getParameters().getMaxExposureCompensation() &&
newSetting >= mCamera.getParameters().getMinExposureCompensation()) {
changingExposure = true;
mCamera.stopPreview();
mCamera.cancelAutoFocus();
stopAutofocus();
Camera.Parameters cameraParam = mCamera.getParameters();
cameraParam.setExposureCompensation(newSetting);
mCamera.setParameters(cameraParam);
mCamera.startPreview();
changingExposure = false;
startAutofocus();
}
}
public void startAutofocus() {
if (mCameraHandler != null) {
mCameraHandler.removeCallbacks(runAutoFocus);
mCameraHandler.postDelayed(runAutoFocus, AUTO_FOCUS_DELAY);
} else {
throw new UnsupportedOperationException("can't start autofocus");
}
}
public void stopAutofocus() {
if (mCameraHandler != null) {
mCameraHandler.removeCallbacks(runAutoFocus);
}
}
public void stopCamera() {
mCamera = null;
mCameraHandler = null;
}
////////////////////////////////////////// background thread ///////////////////////////////////
/**
* Starts a background thread and its Handler.
*/
private void startCameraThread() {
if (StripMeasureActivity.DEBUG) {
Timber.d("Starting camera background thread");
}
HandlerThread mCameraThread = new HandlerThread("CameraBackground");
mCameraThread.start();
mCameraHandler = new Handler(mCameraThread.getLooper());
}
}
| 6,414 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SwatchSelectFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/SwatchSelectFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.manual;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.ui.BaseFragment;
public class SwatchSelectFragment extends BaseFragment {
private static final String ARG_RESULTS = "results";
private static final String ARG_RANGE = "range";
private static final String RESULT_ARRAY = "result_array";
private OnSwatchSelectListener mListener;
private float[] mResults;
private String range;
public static SwatchSelectFragment newInstance(float[] results, String range) {
SwatchSelectFragment fragment = new SwatchSelectFragment();
Bundle args = new Bundle();
args.putFloatArray(ARG_RESULTS, results);
args.putString(ARG_RANGE, range);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mResults = getArguments().getFloatArray(ARG_RESULTS);
range = getArguments().getString(ARG_RANGE);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putFloatArray(RESULT_ARRAY, mResults);
super.onSaveInstanceState(outState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_swatch_select, container, false);
final SwatchSelectWidget swatchSelect = view.findViewById(R.id.swatch_select);
if (range.contains("6.0")) {
swatchSelect.setRange(2);
}
if (savedInstanceState != null) {
mResults = savedInstanceState.getFloatArray(RESULT_ARRAY);
}
swatchSelect.setResults(mResults);
swatchSelect.setOnClickListener(v -> {
mResults = swatchSelect.getResult();
if (mListener != null) {
mListener.onSwatchSelect(mResults);
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnSwatchSelectListener) {
mListener = (OnSwatchSelectListener) context;
} else {
throw new IllegalArgumentException(context.toString()
+ " must implement OnSwatchSelectListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
boolean isValid() {
return mResults != null && mResults[0] != 0 && mResults[1] != 0;
}
public interface OnSwatchSelectListener {
void onSwatchSelect(float[] key);
}
}
| 3,767 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ResultPhotoFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/ResultPhotoFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.manual;
import static android.app.Activity.RESULT_OK;
import static org.akvo.caddisfly.common.AppConstants.FILE_PROVIDER_AUTHORITY_URI;
import static org.akvo.caddisfly.helper.FileHelper.getFormImagesFolder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import org.akvo.caddisfly.BuildConfig;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.databinding.FragmentResultPhotoBinding;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.ui.BaseFragment;
import org.akvo.caddisfly.util.ImageUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
public class ResultPhotoFragment extends BaseFragment {
private static final String ARG_INSTRUCTION = "resultInstruction";
private static final String ARG_RESULT_NAME = "resultName";
private static final int MANUAL_TEST = 2;
private OnPhotoTakenListener mListener;
private String imageFileName = "";
private String currentPhotoPath = "";
private FragmentResultPhotoBinding b;
/**
* Get the instance.
*
* @param testName : Name of the test
* @param id : fragment id
*/
public static ResultPhotoFragment newInstance(String testName, Instruction instruction, int id) {
ResultPhotoFragment fragment = new ResultPhotoFragment();
fragment.setFragmentId(id);
Bundle args = new Bundle();
args.putParcelable(ARG_INSTRUCTION, instruction);
args.putString(ARG_RESULT_NAME, testName);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
b = DataBindingUtil.inflate(inflater,
R.layout.fragment_result_photo, container, false);
if (savedInstanceState != null) {
currentPhotoPath = savedInstanceState.getString(ConstantKey.CURRENT_PHOTO_PATH);
imageFileName = savedInstanceState.getString(ConstantKey.CURRENT_IMAGE_FILE_NAME);
}
View view = b.getRoot();
if (getArguments() != null) {
Instruction instruction = getArguments().getParcelable(ARG_INSTRUCTION);
b.setInstruction(instruction);
String title = getArguments().getString(ARG_RESULT_NAME);
if (title == null || title.isEmpty()) {
b.textName.setVisibility(View.GONE);
} else {
b.textName.setText(title);
}
}
if (imageFileName != null && !imageFileName.isEmpty()) {
File imgFile = new File(currentPhotoPath);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
b.imageResult.setImageBitmap(myBitmap);
b.imageResult.setBackground(null);
b.takePhoto.setText(R.string.retakePhoto);
}
}
b.takePhoto.setOnClickListener(view1 -> takePhoto());
return view;
}
@Override
public void onSaveInstanceState(@NotNull Bundle outState) {
outState.putString(ConstantKey.CURRENT_PHOTO_PATH, currentPhotoPath);
outState.putString(ConstantKey.CURRENT_IMAGE_FILE_NAME, imageFileName);
super.onSaveInstanceState(outState);
}
private void takePhoto() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (pictureIntent.resolveActivity(Objects.requireNonNull(
getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoUri;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
photoUri = Uri.fromFile(photoFile);
} else {
photoUri = FileProvider.getUriForFile(getActivity(),
FILE_PROVIDER_AUTHORITY_URI,
photoFile);
}
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(pictureIntent, MANUAL_TEST);
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (currentPhotoPath != null) {
ImageUtil.resizeImage(currentPhotoPath, currentPhotoPath, 640);
File imgFile = new File(currentPhotoPath);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
b.imageResult.setImageBitmap(myBitmap);
b.imageResult.setBackground(null);
b.takePhoto.setText(R.string.retakePhoto);
}
}
(new Handler()).postDelayed(() -> mListener.onPhotoTaken(), 600);
}
}
private File createImageFile() throws IOException {
imageFileName = UUID.randomUUID().toString();
File image = File.createTempFile(imageFileName, ".jpg", getFormImagesFolder());
imageFileName += ".jpg";
currentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPhotoTakenListener) {
mListener = (OnPhotoTakenListener) context;
} else {
throw new IllegalArgumentException(context.toString()
+ " must implement OnPhotoTakenListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public boolean isValid() {
return BuildConfig.TEST_RUNNING || (currentPhotoPath != null &&
!currentPhotoPath.isEmpty() && new File(currentPhotoPath).exists());
}
public String getImageFileName() {
return currentPhotoPath;
}
public interface OnPhotoTakenListener {
void onPhotoTaken();
}
}
| 7,863 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SwatchSelectWidget.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/SwatchSelectWidget.java | package org.akvo.caddisfly.sensor.manual;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.core.graphics.ColorUtils;
import org.akvo.caddisfly.model.ColorItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class SwatchSelectWidget extends View {
private final Paint buttonPaint = new Paint();
private final Paint borderPaint = new Paint();
private final Paint textPaint = new Paint();
private final Paint textSelectedPaint = new Paint();
private final Paint backgroundPaint = new Paint();
private final Paint textBoxLeftPaint = new Paint();
private final Paint textBoxRightPaint = new Paint();
private final Paint nameTextPaint = new Paint();
private final Paint trianglePaint = new Paint();
private final Paint subTitlePaint = new Paint();
private final List<ColorItem> clColors = new ArrayList<>();
private final List<ColorItem> phColors = new ArrayList<>();
private final List<Rect> phButtons = new ArrayList<>();
private final List<Rect> clButtons = new ArrayList<>();
private final Paint buttonSelectPaint = new Paint();
private final Paint buttonShadowPaint = new Paint();
private Rect nameBounds = new Rect();
private Path lidPath = new Path();
private Rect rect1;
private int buttonWidth;
private int buttonHeight;
private int textBoxWidth;
private int gutterWidth = 10;
private int radius;
private int activeLeft = -1;
private int activeRight = -1;
public SwatchSelectWidget(Context context, AttributeSet attrs) {
super(context, attrs);
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setColor(Color.rgb(100, 100, 100));
borderPaint.setAntiAlias(true);
borderPaint.setStrokeWidth(5);
backgroundPaint.setStyle(Paint.Style.FILL);
backgroundPaint.setAntiAlias(true);
backgroundPaint.setColor(Color.rgb(130, 130, 130));
trianglePaint.setStyle(Paint.Style.FILL);
trianglePaint.setColor(Color.rgb(80, 80, 80));
trianglePaint.setAntiAlias(true);
textBoxLeftPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textBoxLeftPaint.setColor(Color.rgb(255, 255, 255));
textBoxRightPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textBoxRightPaint.setColor(Color.rgb(255, 255, 255));
nameTextPaint.setStyle(Paint.Style.FILL_AND_STROKE);
nameTextPaint.setColor(Color.rgb(50, 50, 50));
nameTextPaint.setStrokeWidth(2);
nameTextPaint.setAntiAlias(true);
// int sizeInPx = context.getResources().getDimensionPixelSize(R.dimen.cbt_shapes_text_size);
// nameTextPaint.setTextSize(70);
subTitlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
subTitlePaint.setColor(Color.rgb(50, 50, 50));
subTitlePaint.setStrokeWidth(1);
subTitlePaint.setAntiAlias(true);
// int sizeInPx = context.getResources().getDimensionPixelSize(R.dimen.cbt_shapes_text_size);
subTitlePaint.setTextSize(40);
buttonPaint.setStyle(Paint.Style.FILL);
buttonPaint.setAntiAlias(true);
buttonSelectPaint.setStyle(Paint.Style.STROKE);
buttonSelectPaint.setAntiAlias(true);
buttonSelectPaint.setColor(Color.GREEN);
buttonSelectPaint.setStrokeWidth(5);
buttonShadowPaint.setStyle(Paint.Style.STROKE);
buttonShadowPaint.setAntiAlias(true);
buttonShadowPaint.setColor(Color.rgb(50, 50, 50));
buttonShadowPaint.setStrokeWidth(4);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setColor(Color.rgb(110, 110, 110));
// int sizeInPx = context.getResources().getDimensionPixelSize(R.dimen.cbt_shapes_text_size);
// textPaint.setTextSize(sizeInPx);
textSelectedPaint.setStyle(Paint.Style.FILL);
textSelectedPaint.setColor(Color.rgb(0, 0, 0));
textSelectedPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
phColors.add(new ColorItem(8.2, 159, 45, 68));
phColors.add(new ColorItem(7.8, 173, 67, 75));
phColors.add(new ColorItem(7.6, 184, 96, 83));
phColors.add(new ColorItem(7.4, 197, 120, 98));
phColors.add(new ColorItem(7.2, 214, 138, 103));
phColors.add(new ColorItem(7, 198, 150, 102));
phColors.add(new ColorItem(6.8, 198, 162, 101));
clColors.add(new ColorItem(3, 169, 59, 92));
clColors.add(new ColorItem(2, 181, 78, 110));
clColors.add(new ColorItem(1.5, 194, 100, 124));
clColors.add(new ColorItem(1.0, 194, 121, 133));
clColors.add(new ColorItem(0.6, 209, 149, 160));
clColors.add(new ColorItem(0.3, 224, 186, 189));
clColors.add(new ColorItem(0.1, 214, 192, 184));
}
//stackoverflow.com/questions/12166476/android-canvas-drawText-set-font-size-from-width
/**
* Sets the text size for a Paint object so a given string of text will be a
* given width.
*
* @param paint the Paint to set the text size for
* @param desiredWidth the desired width
* @param text the text that should be that width
*/
private static void setTextSizeForWidth(Paint paint, float desiredWidth, String text) {
final float testTextSize = 48f;
// Get the bounds of the text, using our testTextSize.
paint.setTextSize(testTextSize);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
// Calculate the desired size as a proportion of our testTextSize.
float desiredTextSize = testTextSize * desiredWidth / bounds.width();
// Set the paint for that size.
paint.setTextSize(desiredTextSize);
}
// stackoverflow.com/questions/5896234/how-to-use-android-canvas-to-draw-a-rectangle-with-only-topLeft-and-topRight-cor
@SuppressWarnings("SameParameterValue")
private static Path RoundedRect(
float left, float top, float right, float bottom, float rx, float ry,
boolean tl, boolean tr, boolean br, boolean bl
) {
Path path = new Path();
if (rx < 0) rx = 0;
if (ry < 0) ry = 0;
float width = right - left;
float height = bottom - top;
if (rx > width / 2) rx = width / 2;
if (ry > height / 2) ry = height / 2;
float widthMinusCorners = (width - (2 * rx));
float heightMinusCorners = (height - (2 * ry));
path.moveTo(right, top + ry);
if (tr)
path.rQuadTo(0, -ry, -rx, -ry);//top-right corner
else {
path.rLineTo(0, -ry);
path.rLineTo(-rx, 0);
}
path.rLineTo(-widthMinusCorners, 0);
if (tl)
path.rQuadTo(-rx, 0, -rx, ry); //top-left corner
else {
path.rLineTo(-rx, 0);
path.rLineTo(0, ry);
}
path.rLineTo(0, heightMinusCorners);
if (bl)
path.rQuadTo(0, ry, rx, ry);//bottom-left corner
else {
path.rLineTo(0, ry);
path.rLineTo(rx, 0);
}
path.rLineTo(widthMinusCorners, 0);
if (br)
path.rQuadTo(rx, 0, rx, -ry); //bottom-right corner
else {
path.rLineTo(rx, 0);
path.rLineTo(0, -ry);
}
path.rLineTo(0, -heightMinusCorners);
path.close();//Given close, last lineTo can be removed.
return path;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
invalidate();
return true;
} else if (action == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
for (int i = 0; i < phButtons.size(); i++) {
if (phButtons.get(i).contains((int) x, (int) y)) {
activeLeft = i;
break;
}
}
for (int i = 0; i < clButtons.size(); i++) {
if (clButtons.get(i).contains((int) x, (int) y)) {
activeRight = i;
break;
}
}
invalidate();
performClick();
return true;
}
return false;
}
@Override
public boolean performClick() {
// Calls the super implementation, which generates an AccessibilityEvent
// and calls the onClick() listener on the view, if any
super.performClick();
// Handle the action for the custom click here
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int left = 0;
int top = (int) (getMeasuredHeight() * 0.04);
int verticalMargin;
int horizontalMargin = 20;
int right = getWidth();
int bottom = (int) (getHeight() - borderPaint.getStrokeWidth());
buttonWidth = getMeasuredWidth() / 5;
textBoxWidth = getMeasuredWidth() / 6;
buttonHeight = (getMeasuredHeight() - top) / 9;
verticalMargin = (int) (buttonHeight * 0.1);
radius = buttonHeight / 2;
if (rect1 == null) {
rect1 = new Rect(4, top, right - 4, bottom);
}
Path borderPath = RoundedRect(rect1.left, rect1.top, rect1.right, rect1.bottom, 30, 30,
false, false, true, true);
canvas.drawPath(borderPath, borderPaint);
canvas.drawPath(borderPath, backgroundPaint);
lidPath.moveTo(-50, 50);
lidPath.quadTo(getMeasuredWidth() / 4, -50, getMeasuredWidth() / 2, 60);
lidPath.quadTo((getMeasuredWidth() / 4) * 3, -50, getMeasuredWidth() + 50, 60);
canvas.drawPath(lidPath, backgroundPaint);
int triangleSize = (int) (getMeasuredWidth() * 0.03);
drawTriangle((getMeasuredWidth() / 2) - triangleSize / 2, top + verticalMargin, triangleSize,
triangleSize, trianglePaint, canvas);
phButtons.clear();
clButtons.clear();
String name1 = "pH";
setTextSizeForWidth(nameTextPaint, (float) (textBoxWidth * 0.7), name1);
nameTextPaint.getTextBounds(name1, 0, name1.length(), nameBounds);
int titleHeight = nameBounds.height();
canvas.drawText(name1, left + horizontalMargin, top + titleHeight, nameTextPaint);
titleHeight = nameBounds.height() + verticalMargin;
String reagent1 = "Phenol Red";
setTextSizeForWidth(subTitlePaint, (float) (buttonWidth * 1.2), reagent1);
canvas.drawText(reagent1, left + horizontalMargin + nameBounds.right + horizontalMargin,
top + titleHeight, subTitlePaint);
setTextSizeForWidth(textPaint, (float) (textBoxWidth * 0.4), "2.0");
setTextSizeForWidth(textSelectedPaint, (float) (textBoxWidth * 0.5), "2.0");
for (int i = 0; i < 7; i++) {
String valueString = String.format(Locale.US, "%.1f", phColors.get(i).getValue());
drawLeftButton(valueString, phColors.get(i).getRgb(), canvas,
gutterWidth + titleHeight + top + verticalMargin + (i * (buttonHeight + verticalMargin)),
left + horizontalMargin, activeLeft == i);
}
left = getMeasuredWidth() - horizontalMargin - buttonWidth - textBoxWidth - gutterWidth;
canvas.drawText("Cl", left - radius, top + titleHeight, nameTextPaint);
canvas.drawText("DPD", left + nameBounds.right - radius, top + titleHeight, subTitlePaint);
String unit = "mg/l";
subTitlePaint.getTextBounds(unit, 0, unit.length(), nameBounds);
canvas.drawText(unit, getMeasuredWidth() - horizontalMargin - nameBounds.width() - 5, top + titleHeight, subTitlePaint);
for (int i = 0; i < 7; i++) {
String valueString = String.format(Locale.US, "%.1f", clColors.get(i).getValue());
drawRightButton(valueString, clColors.get(i).getRgb(), canvas,
gutterWidth + titleHeight + top + verticalMargin + (i * (buttonHeight + verticalMargin)),
left, activeRight == i);
}
}
private void drawLeftButton(String text, int color, Canvas canvas, int top, int left, boolean isActive) {
Rect textRect = new Rect(left, top, left + textBoxWidth, top + buttonHeight);
Rect buttonRect = new Rect(left + textBoxWidth + gutterWidth, top,
left + textBoxWidth + buttonWidth, top + buttonHeight);
Rect leftRect = new Rect(buttonRect.left - gutterWidth - textBoxWidth, buttonRect.top - 2,
buttonRect.right, buttonRect.bottom + 5);
if (activeLeft > -1) {
textBoxLeftPaint.setColor(phColors.get(activeLeft).getRgb());
textPaint.setColor(getDarkerColor(phColors.get(activeLeft).getRgb()));
} else {
textPaint.setColor(Color.rgb(110, 110, 110));
}
canvas.drawRect(textRect, textBoxLeftPaint);
if (isActive) {
canvas.drawRect(leftRect, buttonShadowPaint);
canvas.drawCircle(left + textBoxWidth + buttonWidth, top + radius,
radius + 3, buttonSelectPaint);
canvas.drawRect(new Rect(buttonRect.left - 3 - gutterWidth - textBoxWidth, buttonRect.top - 3,
buttonRect.right, buttonRect.bottom + 3), buttonSelectPaint);
drawRectText(text, textRect, textSelectedPaint, canvas);
} else {
drawRectText(text, textRect, textPaint, canvas);
}
buttonPaint.setColor(color);
canvas.drawRect(buttonRect, buttonPaint);
canvas.drawCircle(left + textBoxWidth + buttonWidth, top + radius, radius, buttonPaint);
phButtons.add(leftRect);
}
private int getDarkerColor(int color) {
return ColorUtils.blendARGB(color, Color.BLACK, 0.2f);
}
private void drawRightButton(String text, int color, Canvas canvas, int top, int left, boolean isActive) {
Rect textRect = new Rect(left + buttonWidth + gutterWidth, top,
left + buttonWidth + textBoxWidth + gutterWidth, top + buttonHeight);
Rect buttonRect = new Rect(left, top, left + buttonWidth, top + buttonHeight);
Rect rightRect = new Rect(buttonRect.left, buttonRect.top - 2,
buttonRect.right + gutterWidth + textBoxWidth, buttonRect.bottom + 5);
if (activeRight > -1) {
textBoxRightPaint.setColor(clColors.get(activeRight).getRgb());
textPaint.setColor(getDarkerColor(clColors.get(activeRight).getRgb()));
} else {
textPaint.setColor(Color.rgb(110, 110, 110));
}
canvas.drawRect(textRect, textBoxRightPaint);
if (isActive) {
canvas.drawRect(rightRect, buttonShadowPaint);
canvas.drawCircle(left, top + radius,
radius + 3, buttonSelectPaint);
canvas.drawRect(new Rect(buttonRect.left, buttonRect.top - 3,
buttonRect.right + 3 + gutterWidth + textBoxWidth, buttonRect.bottom + 3), buttonSelectPaint);
drawRectText(text, textRect, textSelectedPaint, canvas);
} else {
drawRectText(text, textRect, textPaint, canvas);
}
buttonPaint.setColor(color);
canvas.drawRect(buttonRect, buttonPaint);
canvas.drawCircle(left, top + radius, radius, buttonPaint);
clButtons.add(rightRect);
}
public float[] getResult() {
float[] result = new float[2];
if (activeLeft > -1) {
result[0] = phColors.get(activeLeft).getValue().floatValue();
}
if (activeRight > -1) {
result[1] = clColors.get(activeRight).getValue().floatValue();
}
return result;
}
public void setResults(float[] key) {
if (key != null) {
for (int i = 0; i < phColors.size(); i++) {
if (phColors.get(i).getValue().floatValue() == key[0]) {
activeLeft = i;
}
}
for (int i = 0; i < clColors.size(); i++) {
if (clColors.get(i).getValue().floatValue() == key[1]) {
activeRight = i;
}
}
}
}
private void drawRectText(String text, Rect r, Paint paint, Canvas canvas) {
int cHeight = r.height();
int cWidth = r.width();
paint.setTextAlign(Paint.Align.LEFT);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
float x = r.left + (cWidth / 2f - bounds.width() / 2f - bounds.left);
float y = r.top + (cHeight / 2f + bounds.height() / 2f - bounds.bottom);
canvas.drawText(text, x, y, paint);
}
//stackoverflow.com/questions/3501126/how-to-draw-a-filled-triangle-in-android-canvas
private void drawTriangle(int x, int y, int width, int height,
Paint paint, Canvas canvas) {
Point p1 = new Point(x, y);
int pointX = x + width / 2;
int pointY = y + height;
Point p2 = new Point(pointX, pointY);
Point p3 = new Point(x + width, y);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
path.close();
canvas.drawPath(path, paint);
}
public void setRange(int i) {
if (i == 2){
clColors.clear();
clColors.add(new ColorItem(6, 169, 59, 92));
clColors.add(new ColorItem(5, 181, 78, 110));
clColors.add(new ColorItem(3, 194, 100, 124));
clColors.add(new ColorItem(2, 194, 121, 133));
clColors.add(new ColorItem(1.5, 209, 149, 160));
clColors.add(new ColorItem(1, 224, 186, 189));
clColors.add(new ColorItem(0.5, 214, 192, 184));
}
}
} | 18,331 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
MeasurementInputFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/MeasurementInputFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.manual;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.databinding.FragmentManualInputBinding;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.ui.BaseFragment;
public class MeasurementInputFragment extends BaseFragment {
private static final String ARG_INSTRUCTION = "resultInstruction";
private static final String ARG_TEST_INFO = "testInfo";
private static final String ARG_RESULT_ID = "resultId";
private Float resultFloat;
private OnSubmitResultListener listener;
private Float minValue;
private Float maxValue;
private FragmentManualInputBinding b;
/**
* Get the instance.
*/
public static MeasurementInputFragment newInstance(TestInfo testInfo, int resultId,
Instruction instruction, int id) {
MeasurementInputFragment fragment = new MeasurementInputFragment();
fragment.setFragmentId(id);
Bundle args = new Bundle();
args.putParcelable(ARG_TEST_INFO, testInfo);
args.putInt(ARG_RESULT_ID, resultId);
args.putParcelable(ARG_INSTRUCTION, instruction);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
b = DataBindingUtil.inflate(inflater,
R.layout.fragment_manual_input, container, false);
if (getArguments() != null) {
Instruction instruction = getArguments().getParcelable(ARG_INSTRUCTION);
b.setInstruction(instruction);
TestInfo testInfo = getArguments().getParcelable(ARG_TEST_INFO);
int resultId = getArguments().getInt(ARG_RESULT_ID);
Result testResult;
if (testInfo != null) {
testResult = testInfo.getResults().get(resultId);
b.textName.setText(testResult.getName());
String testResultRange = testResult.getRange();
String displayedRange = testResultRange.isEmpty() ? testInfo.getMinMaxRange() : testResultRange;
if (testResult.getUnit().isEmpty()) {
b.textRange.setText(String.format("(%s)", displayedRange));
} else {
b.textRange.setText(String.format("(%s %s)", displayedRange, testResult.getUnit()));
}
String range = testResultRange.isEmpty() ? testInfo.getRanges(): testResultRange;
String[] ranges = testResultRange.isEmpty() ? range.split(","): range.split("-");
minValue = Float.parseFloat(ranges[0].trim());
maxValue = Float.parseFloat(ranges[1].trim());
String unitChoice = testResult.getUnitChoice();
if (unitChoice == null || unitChoice.isEmpty()) {
b.unitChoice.setVisibility(View.GONE);
} else {
b.unitChoice.setOnCheckedChangeListener((radioGroup, i) -> {
b.editRadioValidation.setError(null);
b.editResult.setActivated(true);
b.editResult.requestFocus();
});
}
b.buttonSubmitResult.setOnClickListener(view1 -> {
if (listener != null) {
resultFloat = isValidResult(true);
if (resultFloat != -1f) {
listener.onSubmitResult(testResult.getId(), String.valueOf(resultFloat));
}
}
});
}
}
return b.getRoot();
}
private Float isValidResult(boolean showEmptyError) {
boolean okToSubmit = true;
Float resultFloat = -1f;
if (b.editResult == null) {
return resultFloat;
}
String result = b.editResult.getText().toString();
if (result.isEmpty()) {
if (showEmptyError) {
b.editResult.setError("Enter result");
}
resultFloat = -1f;
} else {
resultFloat = Float.parseFloat(result);
if (b.unitChoice.getVisibility() == View.VISIBLE) {
int radioButtonId = b.unitChoice.getCheckedRadioButtonId();
if (radioButtonId == -1) {
b.editRadioValidation.setActivated(true);
b.editRadioValidation.requestFocus();
b.editRadioValidation.setError("Select unit");
resultFloat = -1f;
okToSubmit = false;
} else {
RadioButton selectedRadioButton = b.unitChoice.findViewById(radioButtonId);
int index = b.unitChoice.indexOfChild(selectedRadioButton);
if (index == 1) {
resultFloat = resultFloat * 1000;
}
}
}
if (okToSubmit) {
if (resultFloat < minValue || resultFloat > maxValue) {
b.editResult.setError("Invalid result");
resultFloat = -1f;
} else {
hideSoftKeyboard(b.editResult);
}
}
}
return resultFloat;
}
void showSoftKeyboard() {
showSoftKeyboard(b.editResult);
}
private void showSoftKeyboard(View view) {
if (getActivity() != null && view.requestFocus()) {
InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
}
void hideSoftKeyboard() {
hideSoftKeyboard(b.editResult);
if (b.editResult != null) {
b.editResult.setError(null);
}
}
private void hideSoftKeyboard(View view) {
if (getActivity() != null) {
InputMethodManager imm = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
view.setActivated(true);
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnSubmitResultListener) {
listener = (OnSubmitResultListener) context;
} else {
throw new IllegalArgumentException(context.toString()
+ " must implement OnSubmitResultListener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
@SuppressWarnings("SameParameterValue")
boolean isValid(boolean showEmptyError) {
return isValidResult(showEmptyError) != -1f;
}
public String getResult() {
resultFloat = isValidResult(true);
return String.valueOf(resultFloat);
}
public interface OnSubmitResultListener {
void onSubmitResult(Integer id, String key);
}
}
| 8,542 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ManualTestActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/ManualTestActivity.java | package org.akvo.caddisfly.sensor.manual;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.concatTwoBitmapsHorizontal;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.concatTwoBitmapsVertical;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueUnitString;
import static org.akvo.caddisfly.util.ApiUtil.setKeyboardVisibilityListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.databinding.FragmentInstructionBinding;
import org.akvo.caddisfly.helper.InstructionHelper;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.PageIndex;
import org.akvo.caddisfly.model.PageType;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.ui.BaseFragment;
import org.akvo.caddisfly.widget.ButtonType;
import org.akvo.caddisfly.widget.CustomViewPager;
import org.akvo.caddisfly.widget.PageIndicatorView;
import org.akvo.caddisfly.widget.SwipeDirection;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.UUID;
public class ManualTestActivity extends BaseActivity
implements MeasurementInputFragment.OnSubmitResultListener,
ResultPhotoFragment.OnPhotoTakenListener, OnKeyboardVisibilityListener {
private ImageView imagePageRight;
private ImageView imagePageLeft;
private final PageIndex pageIndex = new PageIndex();
private String imageFileName = "";
private TestInfo testInfo;
private CustomViewPager viewPager;
private FrameLayout resultLayout;
private RelativeLayout footerLayout;
private PageIndicatorView pagerIndicator;
private boolean showSkipMenu = true;
private FirebaseAnalytics mFirebaseAnalytics;
private final SparseArray<ResultPhotoFragment> resultPhotoFragment = new SparseArray<>();
private final SparseArray<MeasurementInputFragment> inputFragment = new SparseArray<>();
private int totalPageCount;
// private float scale;
private final ArrayList<Instruction> instructionList = new ArrayList<>();
private PlaceholderFragment submitFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_steps);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
// scale = getResources().getDisplayMetrics().density;
viewPager = findViewById(R.id.viewPager);
pagerIndicator = findViewById(R.id.pager_indicator);
resultLayout = findViewById(R.id.resultLayout);
footerLayout = findViewById(R.id.layout_footer);
if (savedInstanceState != null) {
testInfo = savedInstanceState.getParcelable(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
return;
}
InstructionHelper.setupInstructions(testInfo.getInstructions(),
instructionList, pageIndex, false);
totalPageCount = instructionList.size();
viewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
pagerIndicator.showDots(true);
pagerIndicator.setPageCount(totalPageCount);
imagePageRight = findViewById(R.id.image_pageRight);
imagePageRight.setOnClickListener(view -> nextPage());
imagePageLeft = findViewById(R.id.image_pageLeft);
imagePageLeft.setVisibility(View.INVISIBLE);
imagePageLeft.setOnClickListener(view -> pageBack());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
pagerIndicator.setActiveIndex(position);
showHideFooter();
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (pageIndex.getType(viewPager.getCurrentItem()) == PageType.INPUT
&& !inputFragment.get(viewPager.getCurrentItem()).isValid(false)) {
inputFragment.get(viewPager.getCurrentItem()).showSoftKeyboard();
} else {
if (inputFragment.get(pageIndex.getInputPageIndex(0)) != null) {
inputFragment.get(pageIndex.getInputPageIndex(0)).hideSoftKeyboard();
}
if (inputFragment.get(pageIndex.getInputPageIndex(1)) != null) {
inputFragment.get(pageIndex.getInputPageIndex(1)).hideSoftKeyboard();
}
}
}
}
});
submitFragment = PlaceholderFragment.newInstance(
instructionList.get(totalPageCount - 1), ButtonType.SUBMIT);
setKeyboardVisibilityListener(this);
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
showHideFooter();
}
private void nextPage() {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(ConstantKey.TEST_INFO, testInfo);
super.onSaveInstanceState(outState);
}
@Override
public void onRestoreInstanceState(@NotNull Bundle inState) {
for (int i = 0; i < getSupportFragmentManager().getFragments().size(); i++) {
Fragment fragment = getSupportFragmentManager().getFragments().get(i);
if (fragment instanceof ResultPhotoFragment) {
resultPhotoFragment.put(((BaseFragment) fragment).getFragmentId(),
(ResultPhotoFragment) fragment);
}
if (fragment instanceof MeasurementInputFragment) {
inputFragment.put(((BaseFragment) fragment).getFragmentId(),
(MeasurementInputFragment) fragment);
}
}
super.onRestoreInstanceState(inState);
}
private void showHideFooter() {
if (imagePageLeft == null) {
return;
}
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageLeft.setVisibility(View.VISIBLE);
imagePageRight.setVisibility(View.VISIBLE);
pagerIndicator.setVisibility(View.VISIBLE);
footerLayout.setVisibility(View.VISIBLE);
setTitle(testInfo.getName());
if (viewPager.getCurrentItem() > pageIndex.getSkipToIndex() + 1) {
showSkipMenu = viewPager.getCurrentItem() < pageIndex.getSkipToIndex2() - 1;
} else {
showSkipMenu = viewPager.getCurrentItem() < pageIndex.getSkipToIndex() - 1;
}
switch (pageIndex.getType(viewPager.getCurrentItem())) {
case PHOTO:
if (resultPhotoFragment.get(viewPager.getCurrentItem()) != null) {
if (resultPhotoFragment.get(viewPager.getCurrentItem()).isValid()) {
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageRight.setVisibility(View.VISIBLE);
} else {
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
}
}
break;
case INPUT:
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
break;
case RESULT:
setTitle(R.string.result);
imagePageRight.setVisibility(View.INVISIBLE);
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
break;
case DEFAULT:
if (viewPager.getCurrentItem() > 0 &&
instructionList.get(viewPager.getCurrentItem() - 1).testStage > 0) {
viewPager.setAllowedSwipeDirection(SwipeDirection.right);
imagePageLeft.setVisibility(View.INVISIBLE);
} else if (instructionList.get(viewPager.getCurrentItem()).testStage > 0) {
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
showSkipMenu = false;
} else {
footerLayout.setVisibility(View.VISIBLE);
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
}
break;
}
// Last page
if (viewPager.getCurrentItem() == totalPageCount - 1) {
imagePageRight.setVisibility(View.INVISIBLE);
submitFragment.setResult(testInfo);
}
// First page
if (viewPager.getCurrentItem() == 0) {
imagePageLeft.setVisibility(View.INVISIBLE);
}
invalidateOptionsMenu();
}
@Override
public void onKeyboardVisibilityChanged(boolean visible) {
if (visible) {
footerLayout.setVisibility(View.GONE);
} else {
footerLayout.setVisibility(View.VISIBLE);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(testInfo.getName());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (showSkipMenu) {
getMenuInflater().inflate(R.menu.menu_instructions, menu);
}
return true;
}
private void sendResults() {
SparseArray<String> results = new SparseArray<>();
Intent resultIntent = new Intent();
Bitmap resultBitmap = null;
if (resultPhotoFragment.get(pageIndex.getPhotoPageIndex(0)) != null) {
imageFileName = UUID.randomUUID().toString() + ".jpg";
String resultImagePath = resultPhotoFragment.get(pageIndex.getPhotoPageIndex(0)).getImageFileName();
Bitmap bitmap1 = BitmapFactory.decodeFile(resultImagePath);
if (resultPhotoFragment.get(pageIndex.getPhotoPageIndex(1)) != null) {
String result1ImagePath = resultPhotoFragment.get(pageIndex.getPhotoPageIndex(1)).getImageFileName();
Bitmap bitmap2 = BitmapFactory.decodeFile(result1ImagePath);
if (bitmap1 != null && bitmap2 != null) {
if (Math.abs(bitmap1.getWidth() - bitmap2.getWidth()) > 50) {
bitmap2 = BitmapUtils.RotateBitmap(bitmap2, 90);
}
if (bitmap1.getWidth() > bitmap1.getHeight()) {
resultBitmap = concatTwoBitmapsHorizontal(bitmap1, bitmap2);
} else {
resultBitmap = concatTwoBitmapsVertical(bitmap1, bitmap2);
}
bitmap1.recycle();
bitmap2.recycle();
//noinspection ResultOfMethodCallIgnored
new File(result1ImagePath).delete();
//noinspection ResultOfMethodCallIgnored
new File(resultImagePath).delete();
}
} else {
resultBitmap = bitmap1;
}
}
results.put(1, inputFragment.get(pageIndex.getInputPageIndex(0)).getResult());
if (inputFragment.size() > 1) {
results.put(2, inputFragment.get(pageIndex.getInputPageIndex(1)).getResult());
}
JSONObject resultJson = TestConfigHelper.getJsonResult(this, testInfo,
results, null, imageFileName);
resultIntent.putExtra(SensorConstants.RESPONSE, resultJson.toString());
if (!imageFileName.isEmpty() && resultBitmap != null) {
resultIntent.putExtra(SensorConstants.IMAGE, imageFileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resultBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
resultBitmap.recycle();
resultIntent.putExtra(SensorConstants.IMAGE_BITMAP, stream.toByteArray());
}
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
@Override
public void onSubmitResult(Integer id, String result) {
if (inputFragment.get(pageIndex.getInputPageIndex(id - 1)).isValid(false)) {
testInfo.getResults().get(id - 1).setResultValue(Float.parseFloat(result));
submitFragment.setResult(testInfo);
}
nextPage();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (viewPager.getCurrentItem() == 0) {
onBackPressed();
} else {
viewPager.setCurrentItem(0);
showHideFooter();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (resultLayout.getVisibility() == View.VISIBLE) {
viewPager.setCurrentItem(instructionList.size() + 1);
} else if (viewPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
pageBack();
}
}
private void pageBack() {
viewPager.setCurrentItem(Math.max(0, viewPager.getCurrentItem() - 1));
}
public void onSkipClick(MenuItem item) {
if (viewPager.getCurrentItem() > pageIndex.getSkipToIndex() + 1) {
viewPager.setCurrentItem(pageIndex.getSkipToIndex2());
} else {
viewPager.setCurrentItem(pageIndex.getSkipToIndex());
}
if (AppPreferences.analyticsEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("InstructionsSkipped", testInfo.getName() +
" (" + testInfo.getBrand() + ")");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Navigation");
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "si_" + testInfo.getUuid());
mFirebaseAnalytics.logEvent("instruction_skipped", bundle);
}
}
@Override
public void onPhotoTaken() {
nextPage();
}
public void onSubmitClick(View view) {
sendResults();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_SHOW_OK = "show_ok";
FragmentInstructionBinding fragmentInstructionBinding;
Instruction instruction;
private ButtonType showButton;
private LinearLayout resultLayout;
private ViewGroup viewRoot;
/**
* Returns a new instance of this fragment for the given section number.
*
* @param instruction The information to to display
* @return The instance
*/
static PlaceholderFragment newInstance(Instruction instruction, ButtonType showButton) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SECTION_NUMBER, instruction);
args.putSerializable(ARG_SHOW_OK, showButton);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentInstructionBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_instruction, container, false);
viewRoot = container;
if (getArguments() != null) {
instruction = getArguments().getParcelable(ARG_SECTION_NUMBER);
showButton = (ButtonType) getArguments().getSerializable(ARG_SHOW_OK);
fragmentInstructionBinding.setInstruction(instruction);
}
View view = fragmentInstructionBinding.getRoot();
if (showButton == ButtonType.SUBMIT) {
view.findViewById(R.id.buttonSubmit).setVisibility(View.VISIBLE);
}
resultLayout = view.findViewById(R.id.layout_results);
return view;
}
void setResult(TestInfo testInfo) {
if (testInfo != null && testInfo.getResults().size() > 1 && getActivity() != null) {
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resultLayout.removeAllViews();
SparseArray<String> results = new SparseArray<>();
for (Result result : testInfo.getResults()) {
results.put(result.getId(), String.valueOf(result.getResultValue()));
String valueString = createValueUnitString(result.getResultValue(), result.getUnit(),
getString(R.string.no_result));
LinearLayout itemResult;
itemResult = (LinearLayout) inflater.inflate(R.layout.item_result,
viewRoot, false);
TextView textTitle = itemResult.findViewById(R.id.text_title);
textTitle.setText(result.getName());
TextView textResult = itemResult.findViewById(R.id.text_result);
textResult.setText(valueString);
resultLayout.addView(itemResult);
}
resultLayout.setVisibility(View.VISIBLE);
}
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (pageIndex.getType(position) == PageType.PHOTO) {
if (resultPhotoFragment.get(position) == null) {
resultPhotoFragment.put(position, ResultPhotoFragment.newInstance(
testInfo.getResults().get(resultPhotoFragment.size()).getName(),
instructionList.get(position), position));
}
return resultPhotoFragment.get(position);
} else if (pageIndex.getType(position) == PageType.INPUT) {
if (inputFragment.get(position) == null) {
inputFragment.put(position, MeasurementInputFragment.newInstance(
testInfo, inputFragment.size(), instructionList.get(position), position));
}
return inputFragment.get(position);
} else if (position == totalPageCount - 1) {
if (submitFragment == null) {
submitFragment = PlaceholderFragment.newInstance(
instructionList.get(position), ButtonType.SUBMIT);
}
return submitFragment;
} else {
return PlaceholderFragment.newInstance(
instructionList.get(position), ButtonType.NONE);
}
}
@Override
public int getCount() {
return totalPageCount;
}
}
}
| 21,276 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SwatchSelectTestActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/SwatchSelectTestActivity.java | package org.akvo.caddisfly.sensor.manual;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.databinding.FragmentInstructionBinding;
import org.akvo.caddisfly.helper.InstructionHelper;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.PageIndex;
import org.akvo.caddisfly.model.PageType;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.widget.CustomViewPager;
import org.akvo.caddisfly.widget.PageIndicatorView;
import org.akvo.caddisfly.widget.SwipeDirection;
import org.json.JSONObject;
import java.util.ArrayList;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueUnitString;
public class SwatchSelectTestActivity extends BaseActivity
implements SwatchSelectFragment.OnSwatchSelectListener {
private ImageView imagePageRight;
private ImageView imagePageLeft;
private SparseArray<SwatchSelectFragment> inputFragment = new SparseArray<>();
private PlaceholderFragment submitFragment;
private PageIndex pageIndex = new PageIndex();
private float[] testResults;
private TestInfo testInfo;
private CustomViewPager viewPager;
private FrameLayout resultLayout;
private RelativeLayout footerLayout;
private PageIndicatorView pagerIndicator;
private boolean showSkipMenu = true;
private FirebaseAnalytics mFirebaseAnalytics;
private int totalPageCount;
private float scale;
private ArrayList<Instruction> instructionList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_steps);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
scale = getResources().getDisplayMetrics().density;
viewPager = findViewById(R.id.viewPager);
pagerIndicator = findViewById(R.id.pager_indicator);
resultLayout = findViewById(R.id.resultLayout);
footerLayout = findViewById(R.id.layout_footer);
if (testInfo == null) {
testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
return;
}
InstructionHelper.setupInstructions(testInfo.getInstructions(),
instructionList, pageIndex, false);
totalPageCount = instructionList.size();
SectionsPagerAdapter mSectionsPagerAdapter =
new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mSectionsPagerAdapter);
pagerIndicator.showDots(true);
pagerIndicator.setPageCount(totalPageCount);
imagePageRight = findViewById(R.id.image_pageRight);
imagePageRight.setOnClickListener(view -> nextPage());
imagePageLeft = findViewById(R.id.image_pageLeft);
imagePageLeft.setVisibility(View.INVISIBLE);
imagePageLeft.setOnClickListener(view -> pageBack());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
pagerIndicator.setActiveIndex(position);
showHideFooter();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void nextPage() {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
private void showHideFooter() {
if (imagePageLeft == null) {
return;
}
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageLeft.setVisibility(View.VISIBLE);
imagePageRight.setVisibility(View.VISIBLE);
pagerIndicator.setVisibility(View.VISIBLE);
footerLayout.setVisibility(View.VISIBLE);
setTitle(testInfo.getName());
showSkipMenu = viewPager.getCurrentItem() < pageIndex.getSkipToIndex() - 1;
switch (pageIndex.getType(viewPager.getCurrentItem())) {
case INPUT:
setTitle(R.string.select_color_intervals);
if (inputFragment.get(pageIndex.getInputPageIndex(0)).isValid()) {
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageRight.setVisibility(View.VISIBLE);
} else {
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
}
break;
case RESULT:
setTitle(R.string.result);
break;
case DEFAULT:
footerLayout.setVisibility(View.VISIBLE);
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
break;
}
// Last page
if (viewPager.getCurrentItem() == totalPageCount - 1) {
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
imagePageLeft.setVisibility(View.VISIBLE);
submitFragment.setResult(testInfo);
if (scale <= 1.5) {
// don't show footer page indicator for smaller screens
(new Handler()).postDelayed(() -> footerLayout.setVisibility(View.GONE), 400);
}
}
// First page
if (viewPager.getCurrentItem() == 0) {
imagePageLeft.setVisibility(View.INVISIBLE);
}
invalidateOptionsMenu();
}
@Override
public void onBackPressed() {
if (resultLayout.getVisibility() == View.VISIBLE) {
viewPager.setCurrentItem(instructionList.size() + 1);
} else if (viewPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
pageBack();
}
}
private void pageBack() {
viewPager.setCurrentItem(Math.max(0, viewPager.getCurrentItem() - 1));
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(testInfo.getName());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (showSkipMenu) {
getMenuInflater().inflate(R.menu.menu_instructions, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (viewPager.getCurrentItem() == 0) {
onBackPressed();
} else {
viewPager.setCurrentItem(0);
showHideFooter();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSkipClick(MenuItem item) {
viewPager.setCurrentItem(pageIndex.getSkipToIndex());
if (AppPreferences.analyticsEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("InstructionsSkipped", testInfo.getName() +
" (" + testInfo.getBrand() + ")");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Navigation");
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "si_" + testInfo.getUuid());
mFirebaseAnalytics.logEvent("instruction_skipped", bundle);
}
}
public void onSwatchSelect(float[] key) {
showHideFooter();
if (inputFragment.get(pageIndex.getInputPageIndex(0)).isValid()) {
testResults = key;
testInfo.getResults().get(0).setResultValue(key[0]);
testInfo.getResults().get(1).setResultValue(key[1]);
submitFragment.setResult(testInfo);
}
}
public void onSubmitClick(View view) {
sendResults();
}
private void sendResults() {
if (inputFragment.get(pageIndex.getInputPageIndex(0)).isValid()) {
SparseArray<String> results = new SparseArray<>();
results.put(1, String.valueOf(testInfo.getResults().get(0).getResultValue()));
results.put(2, String.valueOf(testInfo.getResults().get(1).getResultValue()));
JSONObject resultJsonObj = TestConfigHelper.getJsonResult(this, testInfo,
results, null, null);
Intent intent = new Intent();
intent.putExtra(SensorConstants.RESPONSE, resultJsonObj.toString());
setResult(RESULT_OK, intent);
}
finish();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_SHOW_OK = "show_ok";
FragmentInstructionBinding fragmentInstructionBinding;
Instruction instruction;
private boolean showOk;
private LinearLayout resultLayout;
private ViewGroup viewRoot;
/**
* Returns a new instance of this fragment for the given section number.
*
* @param instruction The information to to display
* @return The instance
*/
static PlaceholderFragment newInstance(Instruction instruction, boolean showOkButton) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SECTION_NUMBER, instruction);
args.putBoolean(ARG_SHOW_OK, showOkButton);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentInstructionBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_instruction, container, false);
viewRoot = container;
if (getArguments() != null) {
instruction = getArguments().getParcelable(ARG_SECTION_NUMBER);
showOk = getArguments().getBoolean(ARG_SHOW_OK);
fragmentInstructionBinding.setInstruction(instruction);
}
View view = fragmentInstructionBinding.getRoot();
if (showOk) {
view.findViewById(R.id.buttonSubmit).setVisibility(View.VISIBLE);
}
resultLayout = view.findViewById(R.id.layout_results);
return view;
}
void setResult(TestInfo testInfo) {
if (testInfo != null && getActivity() != null) {
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resultLayout.removeAllViews();
SparseArray<String> results = new SparseArray<>();
results.put(1, String.valueOf(testInfo.getResults().get(0).getResultValue()));
results.put(2, String.valueOf(testInfo.getResults().get(1).getResultValue()));
for (Result result : testInfo.getResults()) {
String valueString = createValueUnitString(result.getResultValue(), result.getUnit(),
getString(R.string.no_result));
LinearLayout itemResult;
itemResult = (LinearLayout) inflater.inflate(R.layout.item_result,
viewRoot, false);
TextView textTitle = itemResult.findViewById(R.id.text_title);
textTitle.setText(result.getName());
TextView textResult = itemResult.findViewById(R.id.text_result);
textResult.setText(valueString);
resultLayout.addView(itemResult);
}
resultLayout.setVisibility(View.VISIBLE);
}
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (pageIndex.getType(position) == PageType.INPUT) {
if (inputFragment.get(position) == null) {
inputFragment.put(position,
SwatchSelectFragment.newInstance(testResults, testInfo.getRanges()));
}
return inputFragment.get(position);
} else if (position == totalPageCount - 1) {
if (submitFragment == null) {
submitFragment = PlaceholderFragment.newInstance(
instructionList.get(position), true);
}
return submitFragment;
} else {
return PlaceholderFragment.newInstance(
instructionList.get(position), false);
}
}
@Override
public int getCount() {
return totalPageCount;
}
}
}
| 14,517 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
OnKeyboardVisibilityListener.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/manual/OnKeyboardVisibilityListener.java | package org.akvo.caddisfly.sensor.manual;
//https://stackoverflow.com/questions/4312319/how-to-capture-the-virtual-keyboard-show-hide-event-in-android
public interface OnKeyboardVisibilityListener {
void onKeyboardVisibilityChanged(boolean visible);
}
| 257 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SensorActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/usb/SensorActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.usb;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Spanned;
import android.util.SparseArray;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.databinding.ActivitySensorBinding;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.usb.UsbService;
import org.akvo.caddisfly.util.StringUtil;
import org.akvo.caddisfly.viewmodel.TestInfoViewModel;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import timber.log.Timber;
/**
* The activity that displays the results for the connected sensor.
*/
public class SensorActivity extends BaseActivity {
private static final int REQUEST_DELAY_MILLIS = 1500;
private static final int IDENTIFY_DELAY_MILLIS = 300;
private static final int ANIMATION_DURATION = 500;
private static final int ANIMATION_DURATION_LONG = 1500;
private static final String LINE_FEED = "\r\n";
private static final String EMPTY_STRING = "";
private final Handler handler = new Handler();
private final SparseArray<String> results = new SparseArray<>();
private ActivitySensorBinding b;
// Notifications from UsbService will be received here.
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (Objects.requireNonNull(arg1.getAction())) {
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED:
Toast.makeText(arg0, "USB Permission not granted", Toast.LENGTH_SHORT).show();
displayNotConnectedView();
break;
case UsbService.ACTION_NO_USB:
displayNotConnectedView();
break;
case UsbService.ACTION_USB_DISCONNECTED:
Toast.makeText(arg0, "USB disconnected", Toast.LENGTH_SHORT).show();
displayNotConnectedView();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED:
Toast.makeText(arg0, "USB device not supported", Toast.LENGTH_SHORT).show();
displayNotConnectedView();
break;
default:
break;
}
}
};
private AlertDialog alertDialog;
private TestInfo testInfo;
private Toast debugToast;
private boolean mIsInternal = false;
private String mReceivedData = EMPTY_STRING;
private UsbService usbService;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
if (usbService.isUsbConnected()) {
b.imageUsbConnection.animate().alpha(0f).setDuration(ANIMATION_DURATION);
b.progressWait.setVisibility(View.VISIBLE);
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
private int identityCheck = 0;
private int deviceStatus = 0;
private final Runnable validateDeviceRunnable = new Runnable() {
@Override
public void run() {
String data = "device" + LINE_FEED;
if (usbService != null && usbService.isUsbConnected()) {
// if UsbService was correctly bound, Send data
usbService.write(data.getBytes(StandardCharsets.UTF_8));
} else {
displayNotConnectedView();
}
switch (deviceStatus) {
case 0:
handler.postDelayed(this, IDENTIFY_DELAY_MILLIS);
break;
case 1:
handler.postDelayed(runnable, IDENTIFY_DELAY_MILLIS);
alertDialog.dismiss();
break;
default:
b.progressWait.setVisibility(View.GONE);
if (!alertDialog.isShowing()) {
alertDialog.show();
}
handler.postDelayed(runnable, IDENTIFY_DELAY_MILLIS);
break;
}
}
};
private final Runnable runnable = new Runnable() {
@Override
public void run() {
if (deviceStatus == 1) {
requestResult();
handler.postDelayed(this, REQUEST_DELAY_MILLIS);
} else {
handler.postDelayed(validateDeviceRunnable, IDENTIFY_DELAY_MILLIS * 2);
}
}
};
@Override
public void onResume() {
super.onResume();
deviceStatus = 0;
identityCheck = 0;
setFilters(); // Start listening notifications from UsbService
// Start UsbService(if it was not started before) and Bind it
startService(UsbService.class, usbConnection, null);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(R.string.sensor);
}
@Override
public void onPause() {
super.onPause();
deviceStatus = 0;
identityCheck = 0;
handler.removeCallbacks(runnable);
handler.removeCallbacks(validateDeviceRunnable);
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
@SuppressWarnings("SameParameterValue")
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
alertDialog.dismiss();
handler.postDelayed(validateDeviceRunnable, IDENTIFY_DELAY_MILLIS * 2);
}
private void requestResult() {
String data = "r" + LINE_FEED;
if (usbService != null && usbService.isUsbConnected()) {
// if UsbService was correctly bound, Send data
usbService.write(data.getBytes(StandardCharsets.UTF_8));
} else {
displayNotConnectedView();
}
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
b = DataBindingUtil.setContentView(this, R.layout.activity_sensor);
final TestInfoViewModel viewModel =
ViewModelProviders.of(this).get(TestInfoViewModel.class);
testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
// model.setTest(testInfo);
b.setTestInfoViewModel(viewModel);
final Intent intent = getIntent();
mIsInternal = intent.getBooleanExtra("internal", false);
mHandler = new MyHandler(this);
b.textSubtitle.setText(R.string.deviceConnectSensor);
b.buttonSubmitResult.setVisibility(View.INVISIBLE);
if (testInfo != null && testInfo.getUuid() != null) {
((TextView) findViewById(R.id.textTitle)).setText(
testInfo.getName());
String message = String.format("%s<br/><br/>%s", getString(R.string.expectedDeviceNotFound),
getString(R.string.connectCorrectSensor, testInfo.getName()));
Spanned spanned = StringUtil.fromHtml(message);
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.incorrectDevice)
.setMessage(spanned)
.setCancelable(false);
builder.setNegativeButton(R.string.ok, (dialogInterface, i) -> {
dialogInterface.dismiss();
finish();
});
alertDialog = builder.create();
}
b.progressWait.setVisibility(View.VISIBLE);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayNotConnectedView() {
if (!isFinishing()) {
b.progressWait.setVisibility(View.GONE);
b.layoutResult.animate().alpha(0f).setDuration(ANIMATION_DURATION);
b.imageUsbConnection.animate().alpha(1f).setDuration(ANIMATION_DURATION_LONG);
b.buttonSubmitResult.setVisibility(View.GONE);
b.textSubtitle.setText(R.string.deviceConnectSensor);
b.textSubtitle2.setText("");
}
}
@SuppressLint("ShowToast")
private void displayResult(String value) {
String tempValue = value.trim();
if (AppPreferences.getShowDebugInfo()) {
Toast.makeText(this, tempValue, Toast.LENGTH_SHORT).show();
}
// reject value if corrupt
if (tempValue.startsWith(".") || tempValue.startsWith(",")) {
return;
}
// clean up data
if (tempValue.contains(LINE_FEED)) {
String[] values = tempValue.split(LINE_FEED);
if (values.length > 0) {
tempValue = values[1];
}
}
tempValue = tempValue.trim();
if (!tempValue.isEmpty()) {
// if device not yet validated then check if device id is ok
if (deviceStatus == 0) {
if (tempValue.contains(" ")) {
if (tempValue.startsWith(testInfo.getDeviceId())) {
Pattern p = Pattern.compile(".*\\s(\\d+)");
deviceStatus = 1;
Matcher m = p.matcher(tempValue);
if (m.matches()) {
b.textSubtitle.setText(String.format("Sensor ID: %s", m.group(1)));
} else {
b.textSubtitle.setText(tempValue);
}
b.progressWait.setVisibility(View.VISIBLE);
hideNotConnectedView();
deviceStatus = 1;
} else {
if (identityCheck > 1) {
deviceStatus = 2;
}
identityCheck++;
}
}
return;
}
if (deviceStatus == 2) {
return;
} else {
alertDialog.dismiss();
}
showDebugInfo(tempValue);
if (tempValue.contains(" ")) {
return;
}
String[] resultArray = tempValue.split(",");
if (resultArray.length == testInfo.getResponseFormat().split(",").length) {
// use the response format to display the results in test id order
String responseFormat = testInfo.getResponseFormat().replace("$", EMPTY_STRING)
.replace(" ", EMPTY_STRING).replace(",", EMPTY_STRING).trim();
results.clear();
for (int i = 0; i < resultArray.length; i++) {
resultArray[i] = resultArray[i].trim();
try {
double result = Double.parseDouble(resultArray[i]);
results.put(Integer.parseInt(responseFormat.substring(i, i + 1)), String.valueOf(result));
} catch (Exception e) {
Timber.e("%s: %s | %s", e.getMessage(), value, tempValue);
return;
}
}
// display the results
showResults();
b.layoutResult.animate().alpha(1f).setDuration(ANIMATION_DURATION);
hideNotConnectedView();
}
}
}
private void showResults() {
if (testInfo.getResults().size() > 0 && results.size() > 0
&& !results.get(1).equals(EMPTY_STRING)) {
b.textResult.setText(results.get(1));
b.textUnit.setText(testInfo.getResults().get(0).getUnit());
b.textResult.setVisibility(View.VISIBLE);
b.textUnit.setVisibility(View.VISIBLE);
b.progressWait.setVisibility(View.GONE);
b.buttonSubmitResult.setVisibility(View.VISIBLE);
} else {
b.textResult.setText(EMPTY_STRING);
b.textUnit.setText(EMPTY_STRING);
b.textResult.setVisibility(View.INVISIBLE);
b.textUnit.setVisibility(View.INVISIBLE);
b.progressWait.setVisibility(View.VISIBLE);
b.buttonSubmitResult.setVisibility(View.GONE);
b.textSubtitle2.setText(R.string.dipSensorInSample);
}
if (testInfo.getResults().size() > 1 && results.size() > 1) {
b.textResult2.setText(results.get(2));
b.textUnit2.setText(testInfo.getResults().get(1).getUnit());
b.textResult2.setVisibility(View.VISIBLE);
b.textUnit2.setVisibility(View.VISIBLE);
} else {
b.textResult2.setVisibility(View.GONE);
b.textUnit2.setVisibility(View.GONE);
}
// if test is not via survey then do not show the accept button
if (mIsInternal) {
b.buttonSubmitResult.setVisibility(View.GONE);
}
}
@SuppressLint("ShowToast")
private void showDebugInfo(String tempValue) {
if (AppPreferences.getShowDebugInfo()) {
final String finalValue = tempValue;
runOnUiThread(() -> {
if (debugToast == null) {
debugToast = Toast.makeText(getBaseContext(), finalValue, Toast.LENGTH_LONG);
}
debugToast.setText(finalValue);
debugToast.show();
});
}
}
private void hideNotConnectedView() {
b.imageUsbConnection.animate().alpha(0f).setDuration(ANIMATION_DURATION);
}
@SuppressWarnings("unused")
public void onClickSubmitResult(View view) {
// Build the result json to be returned
Intent resultIntent = new Intent();
JSONObject resultJson = TestConfigHelper.getJsonResult(this, testInfo, results,
null, EMPTY_STRING);
resultIntent.putExtra(SensorConstants.RESPONSE, resultJson.toString());
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
/*
* This handler will be passed to UsbService.
* Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<SensorActivity> mActivity;
MyHandler(SensorActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
if (msg.what == UsbService.MESSAGE_FROM_SERIAL_PORT) {
String data = (String) msg.obj;
SensorActivity sensorActivity = mActivity.get();
if (sensorActivity != null) {
sensorActivity.mReceivedData += data;
if (sensorActivity.mReceivedData.contains(LINE_FEED)) {
sensorActivity.displayResult(sensorActivity.mReceivedData);
sensorActivity.mReceivedData = EMPTY_STRING;
}
}
}
}
}
}
| 18,232 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
WaitingFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/WaitingFragment.java | package org.akvo.caddisfly.sensor.bluetooth;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import org.akvo.caddisfly.BuildConfig;
import org.akvo.caddisfly.R;
import java.util.Locale;
public class WaitingFragment extends Fragment {
private static final String INSTRUCTION_INDEX = "instruction_index";
public static WaitingFragment getInstance(int index) {
WaitingFragment fragment = new WaitingFragment();
Bundle args = new Bundle();
args.putInt(INSTRUCTION_INDEX, index);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_waiting_result, container, false);
ProgressBar progressCircle = view.findViewById(R.id.progressCircle);
if (getArguments() != null) {
TextView textIndex = view.findViewById(R.id.text_index);
textIndex.setText(String.format(Locale.US, "%d.", getArguments().getInt(INSTRUCTION_INDEX)));
}
if (!BuildConfig.TEST_RUNNING) {
progressCircle.setVisibility(View.VISIBLE);
}
return view;
}
}
| 1,483 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BluetoothResultFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/BluetoothResultFragment.java | package org.akvo.caddisfly.sensor.bluetooth;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.util.StringUtil;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.content.Context.CLIPBOARD_SERVICE;
/**
* A simple {@link Fragment} subclass.
*/
public class BluetoothResultFragment extends Fragment {
private final SparseArray<String> results = new SparseArray<>();
private TextView textName1;
private TextView textResult1;
private TextView textUnit1;
private TextView textName2;
private TextView textResult2;
private TextView textUnit2;
private TextView textName3;
private TextView textResult3;
private TextView textUnit3;
private LinearLayout layoutResult;
private AlertDialog errorDialog;
private LinearLayout layoutResult1;
private LinearLayout layoutResult2;
private LinearLayout layoutResult3;
private Button buttonSubmitResult;
private TestInfo testInfo;
/**
* Creates test fragment for specific uuid.
*/
public static BluetoothResultFragment getInstance(TestInfo testInfo) {
BluetoothResultFragment fragment = new BluetoothResultFragment();
Bundle args = new Bundle();
args.putParcelable(ConstantKey.TEST_INFO, testInfo);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bluetooth_result, container, false);
if (getArguments() != null) {
testInfo = getArguments().getParcelable(ConstantKey.TEST_INFO);
}
layoutResult1 = view.findViewById(R.id.layoutResult1);
textResult1 = view.findViewById(R.id.textResult1);
textUnit1 = view.findViewById(R.id.textUnit1);
textName1 = view.findViewById(R.id.textName1);
layoutResult2 = view.findViewById(R.id.layoutResult2);
textResult2 = view.findViewById(R.id.textResult2);
textUnit2 = view.findViewById(R.id.textUnit2);
textName2 = view.findViewById(R.id.textName2);
layoutResult3 = view.findViewById(R.id.layoutResult3);
textResult3 = view.findViewById(R.id.textResult3);
textUnit3 = view.findViewById(R.id.textUnit3);
textName3 = view.findViewById(R.id.textName3);
layoutResult = view.findViewById(R.id.layoutResult);
buttonSubmitResult = view.findViewById(R.id.button_submit_result);
buttonSubmitResult.setOnClickListener(view12 -> {
// Build the result json to be returned
Intent resultIntent = new Intent();
Activity activity = getActivity();
if (activity != null) {
JSONObject resultJson = TestConfigHelper.getJsonResult(getActivity(), testInfo,
results, null, "");
resultIntent.putExtra(SensorConstants.RESPONSE, resultJson.toString());
activity.setResult(Activity.RESULT_OK, resultIntent);
activity.finish();
}
});
if (AppPreferences.isDiagnosticMode()) {
LinearLayout layoutTitle = view.findViewById(R.id.layoutTitleBar);
if (layoutTitle != null) {
layoutTitle.setBackgroundColor(ContextCompat.getColor(
Objects.requireNonNull(getActivity()), R.color.diagnostic));
}
}
SpannableStringBuilder endInstruction = StringUtil.toInstruction((AppCompatActivity) getActivity(), testInfo,
String.format(StringUtil.getStringByName(getActivity(), testInfo.getEndInstruction()),
StringUtil.convertToTags(testInfo.getMd610Id()), testInfo.getName()));
((TextView) view.findViewById(R.id.textEndInstruction)).setText(endInstruction);
return view;
}
private void showError(Activity activity) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
alertDialog.setTitle(R.string.incorrect_test_selected);
alertDialog.setMessage(TextUtils.concat(
StringUtil.toInstruction((AppCompatActivity) getActivity(),
null, getString(R.string.data_does_not_match) + "<br /><br />"),
StringUtil.toInstruction((AppCompatActivity) getActivity(),
null, getString(R.string.select_correct_test))
));
alertDialog.setPositiveButton(R.string.ok, (dialogInterface, i) -> dialogInterface.dismiss());
alertDialog.setCancelable(false);
errorDialog = alertDialog.create();
errorDialog.show();
}
/**
* Display the result data.
*/
boolean displayData(String data) {
if (errorDialog != null) {
errorDialog.dismiss();
}
// Display data received for diagnostic purposes
showDebugInfo(data);
String resultTitles = ",,Version,Version,Id,Test,Range,,,,Date,Time,,,,,,,Result,Unit";
String[] titles = resultTitles.split(",");
String testId = "";
String[] ranges = new String[2];
String unit = "";
boolean dataOk = false;
layoutResult1.setVisibility(View.INVISIBLE);
layoutResult2.setVisibility(View.INVISIBLE);
layoutResult3.setVisibility(View.INVISIBLE);
String[] dataArray = data.split(";");
for (int i = 0; i < dataArray.length; i++) {
if (titles.length > i && !titles[i].isEmpty()) {
if (titles[i].equals("Version")) {
String version = dataArray[i].trim();
if (version.startsWith("V")) {
dataOk = true;
} else {
return false;
}
}
if (titles[i].equals("Id")) {
testId = dataArray[i].trim();
}
if (titles[i].equals("Range")) {
Matcher m =
Pattern.compile("([-+]?[0-9]*\\.?[0-9]+)-([-+]?[0-9]*\\.?[0-9]+)\\s+(.+)\\s+(.+)")
.matcher(dataArray[i].trim());
if (m.find()) {
ranges[0] = m.group(1);
ranges[1] = m.group(2);
unit = m.group(3);
}
}
if (titles[i].equals("Result")) {
int resultCount = 0;
for (int j = 0; j + i < dataArray.length; j = j + 4) {
resultCount++;
String result = dataArray[j + i].trim();
String md610Id = dataArray[j + i + 1].trim().replace(unit, "").trim();
boolean isText = false;
try {
Double.parseDouble(result);
} catch (Exception e) {
isText = true;
}
if (isText) {
result = handleOutOfRangeResult(ranges, result);
}
showResults(result, md610Id);
}
if (results.size() < 1 || resultCount != testInfo.getResults().size()) {
dataOk = false;
}
break;
}
}
}
if (dataOk && testId.equals(testInfo.getMd610Id())) {
layoutResult.setVisibility(View.VISIBLE);
buttonSubmitResult.setVisibility(View.VISIBLE);
return true;
} else {
showError(getActivity());
layoutResult.setVisibility(View.GONE);
return false;
}
}
private String handleOutOfRangeResult(String[] ranges, String data) {
DecimalFormat df = new DecimalFormat("#.###");
if (data.equalsIgnoreCase("underrange")) {
try {
Double.parseDouble(ranges[0]);
} catch (Exception e) {
ranges[0] = df.format(testInfo.getMinRangeValue());
}
if (ranges[0].equals("0")) {
return "0";
} else {
return "<" + ranges[0];
}
} else if (data.equalsIgnoreCase("overrange")) {
try {
Double.parseDouble(ranges[1]);
} catch (Exception e) {
ranges[1] = df.format(testInfo.getMaxRangeValue());
}
return ">" + ranges[1];
}
return "";
}
private void showResults(String result, String md610Id) {
if (testInfo.getResults().size() > 1) {
for (Result subTest : testInfo.getResults()) {
if (subTest.getMd610Id().equalsIgnoreCase(md610Id)) {
switch (subTest.getId()) {
case 1:
layoutResult1.setVisibility(View.VISIBLE);
textName1.setText(subTest.getName());
if (!result.isEmpty()) {
textUnit1.setText(subTest.getUnit());
textResult1.setText(result);
} else {
textUnit1.setText("");
textResult1.setText("");
}
break;
case 2:
layoutResult2.setVisibility(View.VISIBLE);
textName2.setText(subTest.getName());
if (!result.isEmpty()) {
textUnit2.setText(subTest.getUnit());
textResult2.setText(result);
} else {
textUnit2.setText("");
textResult2.setText("");
}
break;
case 3:
layoutResult3.setVisibility(View.VISIBLE);
textName3.setText(subTest.getName());
if (!result.isEmpty()) {
textUnit3.setText(subTest.getUnit());
textResult3.setText(result);
} else {
textUnit3.setText("");
textResult3.setText("");
}
break;
default:
break;
}
results.put(subTest.getId(), result);
}
}
} else {
layoutResult1.setVisibility(View.VISIBLE);
textName1.setText(testInfo.getResults().get(0).getName());
textResult1.setText(result);
textUnit1.setText(testInfo.getResults().get(0).getUnit());
results.put(1, result);
}
}
private void showDebugInfo(String data) {
if (AppPreferences.getShowDebugInfo()) {
AlertDialog.Builder builder;
final TextView showText = new TextView(getActivity());
showText.setText(String.format("%s = %s", testInfo.getName(), data));
showText.setPadding(50, 20, 40, 30);
builder = new AlertDialog.Builder(getActivity());
builder.setView(showText);
builder.setPositiveButton("Copy", (dialog1, which) -> {
if (getActivity() != null) {
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("", showText.getText());
if (clipboard != null) {
clipboard.setPrimaryClip(clip);
}
Toast.makeText(getActivity(), "Data copied to clipboard",
Toast.LENGTH_SHORT)
.show();
}
});
builder.setNegativeButton(R.string.cancel, (dialog12, which) -> dialog12.dismiss());
AlertDialog dialog;
dialog = builder.create();
dialog.setTitle("Received Data");
dialog.setCancelable(false);
dialog.show();
}
}
}
| 13,645 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DeviceScanActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/DeviceScanActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.bluetooth;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
import android.provider.Settings;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.util.ApiUtil;
import java.util.ArrayList;
import java.util.List;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity extends BaseActivity implements DeviceConnectDialog.InterfaceCommunicator {
private static final int PERMISSION_ALL = 1;
private static final String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};
private static final float SNACK_BAR_LINE_SPACING = 1.4f;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after scan period
private static final long SCAN_PERIOD = 6000;
private static final int REQUEST_CODE = 100;
private static final long CONNECTING_DELAY = 2000;
private CoordinatorLayout coordinatorLayout;
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback;
private LeDeviceListAdapter mLeDeviceListAdapter;
private LinearLayout layoutInfo;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private boolean mScanning;
private Handler mHandler;
private ProgressBar progressBar;
private ListView deviceList;
private RelativeLayout layoutDevices;
private Runnable runnable;
private ScanCallback mScanCallback;
private DeviceConnectDialog deviceConnectDialog;
private Snackbar snackbar;
private TestInfo testInfo;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mScanCallback = new ScanCallback() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
processResult(result);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
for (ScanResult result : results) {
processResult(result);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void processResult(ScanResult result) {
mLeDeviceListAdapter.addDevice(result.getDevice());
}
};
} else {
mLeScanCallback =
(device, rssi, scanRecord) -> runOnUiThread(() -> mLeDeviceListAdapter.addDevice(device));
}
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager != null) {
mBluetoothAdapter = bluetoothManager.getAdapter();
}
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
layoutDevices = findViewById(R.id.layoutDevices);
deviceList = findViewById(R.id.device_list);
progressBar = findViewById(R.id.progressBar);
layoutInfo = findViewById(R.id.layout_bluetooth_info);
coordinatorLayout = findViewById(R.id.coordinatorLayout);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(R.string.nearby_devices);
}
private void showInstructionDialog() {
if (deviceConnectDialog == null || !deviceConnectDialog.isVisible()) {
deviceConnectDialog = DeviceConnectDialog.newInstance();
final FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment fragment = getFragmentManager().findFragmentByTag("connectionInfoDialog");
if (fragment != null) {
ft.remove(fragment);
}
deviceConnectDialog.setCancelable(false);
deviceConnectDialog.show(ft, "connectionInfoDialog");
}
}
private boolean connectToDevice(int position) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return false;
}
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) {
return false;
}
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(ConstantKey.TEST_INFO, testInfo);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
if (mScanning) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBluetoothLeScanner.stopScan(mScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
mScanning = false;
}
final ProgressDialog dlg = new ProgressDialog(this);
dlg.setMessage(getString(R.string.deviceConnecting));
dlg.setCancelable(false);
dlg.show();
new Handler().postDelayed(() -> {
startActivityForResult(intent, REQUEST_CODE);
dlg.dismiss();
}, CONNECTING_DELAY);
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
final Activity activity = this;
if (requestCode == PERMISSION_ALL) {
// If request is cancelled, the result arrays are empty.
boolean granted = false;
for (int grantResult : grantResults) {
if (grantResult != PERMISSION_GRANTED) {
granted = false;
break;
} else {
granted = true;
}
}
if (!granted) {
snackbar = Snackbar
.make(coordinatorLayout, getString(R.string.location_permission),
Snackbar.LENGTH_INDEFINITE)
.setAction("SETTINGS", view -> ApiUtil.startInstalledAppDetailsActivity(activity));
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
snackbar.setActionTextColor(typedValue.data);
View snackView = snackbar.getView();
TextView textView = snackView.findViewById(R.id.snackbar_text);
textView.setHeight(getResources().getDimensionPixelSize(R.dimen.snackBarHeight));
textView.setLineSpacing(0, SNACK_BAR_LINE_SPACING);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
}
}
@Override
protected void onResume() {
super.onResume();
layoutDevices.setVisibility(View.GONE);
layoutInfo.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED) {
if (snackbar == null || !snackbar.isShownOrQueued()) {
requestPermissions(PERMISSIONS, PERMISSION_ALL);
}
} else {
scanLeDevice(true);
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
deviceList.setAdapter(mLeDeviceListAdapter);
mHandler.postDelayed(() -> {
if (mLeDeviceListAdapter.getCount() < 1) {
layoutInfo.setVisibility(View.VISIBLE);
}
}, 1000);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
mHandler.removeCallbacks(runnable);
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Intent intent = new Intent(data);
this.setResult(Activity.RESULT_OK, intent);
finish();
} else if (resultCode == Activity.RESULT_CANCELED) {
scanLeDevice(true);
}
}
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
}
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(runnable);
if (deviceConnectDialog != null) {
deviceConnectDialog.dismiss();
}
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
private void scanLeDevice(final boolean enable) {
progressBar.setVisibility(View.VISIBLE);
if (enable) {
if (mScanning) {
return;
}
if (mBluetoothAdapter.isEnabled()) {
// Ensures Location is enabled on the device. This is required for bluetooth connections
checkLocationIsEnabled();
} else {
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mBluetoothLeScanner == null) {
return;
}
runnable = () -> {
mScanning = false;
if (mBluetoothAdapter.isEnabled()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBluetoothLeScanner.stopScan(mScanCallback);
} else {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
if (!isDestroyed() && !isFinishing() && mLeDeviceListAdapter.getCount() < 1) {
deviceList.setVisibility(View.GONE);
layoutInfo.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
showInstructionDialog();
}
};
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(runnable, SCAN_PERIOD);
mScanning = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(ParcelUuid.fromString(GattAttributes.LOVIBOND_SERVICE)).build();
List<ScanFilter> scanFilters = new ArrayList<>();
scanFilters.add(filter);
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothLeScanner.startScan(scanFilters, settings, mScanCallback);
}
progressBar.setVisibility(View.VISIBLE);
} else {
//noinspection deprecation
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
} else {
mScanning = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
mBluetoothLeScanner.stopScan(mScanCallback);
}
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
}
/**
* Ensure location is enabled on the device
* https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
*/
private void checkLocationIsEnabled() {
LocationRequest mLocationRequestBalancedPowerAccuracy = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationRequest mLocationRequestHighAccuracy = LocationRequest.create().setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequestHighAccuracy)
.addLocationRequest(mLocationRequestBalancedPowerAccuracy)
.setNeedBle(true)
.setAlwaysShow(true);
Task<LocationSettingsResponse> task =
LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(task1 -> {
try {
task1.getResult(ApiException.class);
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
try {
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
resolvable.startResolutionForResult(DeviceScanActivity.this, 1);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// The device is probably in airplane mode
(new Handler()).postDelayed(this::navigateToLocationSettings, 1000);
break;
}
}
});
}
/**
* If device is on airplane mode then only option is to open the settings screen and
* request user to enable location from there.
*/
public void navigateToLocationSettings() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.turn_location_on)
.setCancelable(false)
.setPositiveButton(R.string.ok, (dialog, id) -> {
dialog.dismiss();
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
})
.setNegativeButton(R.string.cancel, (dialog, id) -> {
dialog.cancel();
finish();
});
final AlertDialog alert = builder.create();
alert.show();
}
}
@Override
public void sendRequestCode(int code) {
if (code == RESULT_OK) {
scanLeDevice(true);
} else {
finish();
}
}
private static class ViewHolder {
private TextView deviceName;
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private final List<BluetoothDevice> mLeDevices;
private final LayoutInflater mInflater;
LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<>();
mInflater = DeviceScanActivity.this.getLayoutInflater();
}
private void addDevice(BluetoothDevice device) {
if (!mLeDevices.contains(device)
&& device.getType() != BluetoothDevice.DEVICE_TYPE_CLASSIC
&& device.getType() != BluetoothDevice.DEVICE_TYPE_UNKNOWN
) {
mLeDevices.add(device);
mLeDeviceListAdapter.notifyDataSetChanged();
layoutDevices.setVisibility(View.VISIBLE);
deviceList.setVisibility(View.VISIBLE);
layoutInfo.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
setTitle(R.string.nearby_devices);
}
}
private BluetoothDevice getDevice(int position) {
if (position < mLeDevices.size()) {
return mLeDevices.get(position);
}
return null;
}
void clear() {
mLeDevices.clear();
}
@Override
public int getCount() {
return mLeDevices.size();
}
@Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@SuppressLint("InflateParams")
@Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
ViewHolder viewHolder;
View view = convertView;
if (view == null) {
view = mInflater.inflate(R.layout.item_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceName = view.findViewById(R.id.device_name);
view.setTag(viewHolder);
Button buttonConnect = view.findViewById(R.id.button_connect);
buttonConnect.setOnClickListener(v -> {
if (!connectToDevice(position)) {
Toast.makeText(getBaseContext(), R.string.unableToConnect, Toast.LENGTH_LONG).show();
finish();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(position);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0) {
viewHolder.deviceName.setText(R.string.md610_photometer);
} else {
viewHolder.deviceName.setText(R.string.unknown_device);
}
return view;
}
}
}
| 23,711 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
GattAttributes.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/GattAttributes.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.bluetooth;
/**
* This GATT attributes for the device.
*/
final class GattAttributes {
public static final String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
public static final String LOVIBOND_DATA_CHARACTERISTIC = "e7add780-b042-4876-aae1-112855353cc1";
public static final String LOVIBOND_SERVICE = "0bd51666-e7cb-469b-8e4d-2742f1ba77cc";
private GattAttributes() {
}
}
| 1,833 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DeviceConnectDialog.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/DeviceConnectDialog.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.bluetooth;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import org.akvo.caddisfly.R;
public class DeviceConnectDialog extends DialogFragment {
private static final double WIDTH_PERCENTAGE = 0.98;
public static DeviceConnectDialog newInstance() {
return new DeviceConnectDialog();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("MD610 not found");
LayoutInflater inflater = LayoutInflater.from(getActivity());
@SuppressLint("InflateParams")
View newFileView = inflater.inflate(R.layout.dialog_device_instructions, null);
builder.setView(newFileView);
builder.setPositiveButton(R.string.retry, (dialog, which) -> {
InterfaceCommunicator listener = (InterfaceCommunicator) getActivity();
listener.sendRequestCode(Activity.RESULT_OK);
});
builder.setNegativeButton(R.string.cancel, (dialog, which) -> {
InterfaceCommunicator listener = (InterfaceCommunicator) getActivity();
listener.sendRequestCode(Activity.RESULT_CANCELED);
});
return builder.create();
}
@Override
public void onStart() {
super.onStart();
if (getDialog() == null) {
return;
}
int dialogWidth = (int) (WIDTH_PERCENTAGE * getResources().getDisplayMetrics().widthPixels);
if (getDialog().getWindow() != null) {
getDialog().getWindow().setLayout(dialogWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
}
}
public interface InterfaceCommunicator {
void sendRequestCode(int code);
}
}
| 2,771 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ReagentLabel.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/ReagentLabel.java | package org.akvo.caddisfly.sensor.bluetooth;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import org.akvo.caddisfly.R;
public class ReagentLabel extends View {
private final Paint strokePaint = new Paint();
private final Paint titleTextPaint = new Paint();
private final Paint superscriptTextPaint = new Paint();
private final Paint superscript2TextPaint = new Paint();
private final Paint subtitleTextPaint = new Paint();
private final Paint blueTextPaint = new Paint();
private final Paint redTextPaint = new Paint();
private float titleHeight;
private Rect rect1;
private float titleWidth;
private float titleCharWidth;
private float subtitleWidth;
private float subtitleCharWidth;
private float margin;
private int imageMargin;
private int imageWidth;
private int imageHeight;
private float subtitleY;
private float subtitleHeight;
private float line1Top;
private float line2Top;
private String reagentName;
private String reagentCode;
public ReagentLabel(Context context, AttributeSet attrs) {
super(context, attrs);
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
// stroke
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setColor(Color.rgb(40, 40, 40));
strokePaint.setStrokeWidth((float) Math.min(10, height * 0.005));
titleTextPaint.setStyle(Paint.Style.FILL);
titleTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
titleTextPaint.setColor(Color.rgb(30, 30, 30));
superscriptTextPaint.setStyle(Paint.Style.FILL);
superscriptTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
superscriptTextPaint.setColor(Color.rgb(0, 0, 0));
subtitleTextPaint.setStyle(Paint.Style.FILL);
subtitleTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
subtitleTextPaint.setColor(Color.rgb(0, 0, 0));
blueTextPaint.setStyle(Paint.Style.FILL);
blueTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
blueTextPaint.setColor(Color.rgb(12, 68, 150));
redTextPaint.setStyle(Paint.Style.FILL);
redTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
redTextPaint.setColor(Color.rgb(240, 0, 9));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (rect1 == null) {
rect1 = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());
margin = (float) (getMeasuredHeight() * 0.1);
imageMargin = (int) (getMeasuredHeight() * 0.08);
imageWidth = (int) (getMeasuredWidth() * 0.2);
imageHeight = (343 * imageWidth) / 440;
int baseHeight = 22;
for (int i = baseHeight; i >= 10; i--) {
baseHeight = i;
titleTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
i, getResources().getDisplayMetrics()));
float width = titleTextPaint.measureText("Lovibond® Water Testing");
if (width < getMeasuredWidth() - imageWidth - (margin * 2)) {
break;
}
}
superscriptTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
baseHeight - 2, getResources().getDisplayMetrics()));
subtitleTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
baseHeight - 3, getResources().getDisplayMetrics()));
superscript2TextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
baseHeight - 3, getResources().getDisplayMetrics()));
for (int i = baseHeight - 1; i >= 10; i--) {
baseHeight = i;
blueTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
i, getResources().getDisplayMetrics()));
float width = blueTextPaint.measureText(reagentName);
if (width < getMeasuredWidth() - (margin * 2)) {
break;
}
}
redTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
baseHeight - 1, getResources().getDisplayMetrics()));
titleWidth = titleTextPaint.measureText("Lovibond");
titleCharWidth = titleTextPaint.measureText("W");
titleHeight = titleTextPaint.measureText("W");
subtitleWidth = subtitleTextPaint.measureText("Tintometer");
subtitleCharWidth = titleTextPaint.measureText("W");
subtitleHeight = titleTextPaint.measureText("W");
subtitleY = imageHeight + imageMargin - (imageMargin * 0.3f);
line1Top = margin + subtitleY + margin + (margin / 2) - 3;
line2Top = margin + line1Top + margin - 3;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(rect1, strokePaint);
canvas.drawText("Lovibond", margin, margin + titleHeight, titleTextPaint);
canvas.drawText("®", margin + titleWidth, margin + (titleHeight / 2), superscriptTextPaint);
canvas.drawText("Water Testing", margin + titleWidth + titleCharWidth, margin + titleHeight, titleTextPaint);
canvas.drawText("Tintometer", margin, subtitleY, subtitleTextPaint);
canvas.drawText("®", margin + subtitleWidth, subtitleY - (subtitleHeight / 3), superscript2TextPaint);
canvas.drawText("Group", margin + subtitleWidth + subtitleCharWidth, subtitleY, subtitleTextPaint);
canvas.drawText(reagentName.toUpperCase(), margin, line1Top, blueTextPaint);
canvas.drawText(reagentCode, margin, line2Top, redTextPaint);
Drawable d = getResources().getDrawable(R.drawable.lovibond_logo);
d.setBounds(getMeasuredWidth() - imageMargin - imageWidth, imageMargin,
getMeasuredWidth() - imageMargin, imageHeight + imageMargin);
d.draw(canvas);
}
public void setReagentName(String reagentName) {
this.reagentName = reagentName;
}
public void setReagentCode(String reagentCode) {
this.reagentCode = reagentCode;
}
} | 6,821 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BluetoothLeService.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/BluetoothLeService.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.sensor.bluetooth;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import java.util.List;
import java.util.UUID;
import timber.log.Timber;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
public static final String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public static final String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public static final String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public static final String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public static final String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
private static final UUID UUID_LOVIBOND_DATA =
UUID.fromString(GattAttributes.LOVIBOND_DATA_CHARACTERISTIC);
private final IBinder mBinder = new LocalBinder();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
broadcastUpdate(intentAction);
Timber.i("Connected to GATT server.");
// Attempts to discover services after successful connection.
Timber.i("Attempting to start service discovery:%s", mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
Timber.i("Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Timber.w("onServicesDiscovered received: %s", status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(@SuppressWarnings("SameParameterValue") final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
intent.putExtra(EXTRA_DATA, new String(data));
}
sendBroadcast(intent);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Timber.e("Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Timber.e("Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address The device address of the destination device.
* @return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Timber.w("BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && mBluetoothDeviceAddress.equals(address)
&& mBluetoothGatt != null) {
Timber.d("Trying to use an existing mBluetoothGatt for connection.");
//mConnectionState = STATE_CONNECTING;
return mBluetoothGatt.connect();
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Timber.w("Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Timber.d("Trying to create a new connection.");
mBluetoothDeviceAddress = address;
return true;
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
private void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Enables or disables notification on a give characteristic.
*
* @param characteristic Characteristic to act on.
* @param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicIndication(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Timber.w("BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
if (UUID_LOVIBOND_DATA.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
*
* @return A {@code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) {
return null;
}
return mBluetoothGatt.getServices();
}
class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
}
| 10,621 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DeviceControlActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/DeviceControlActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.bluetooth;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.Constants;
import org.akvo.caddisfly.databinding.FragmentInstructionBinding;
import org.akvo.caddisfly.helper.InstructionHelper;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.PageIndex;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.widget.PageIndicatorView;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import timber.log.Timber;
/**
* For a given BLE device, this Activity provides the user interface to connect, display data,
* and display GATT services and characteristics supported by the device. The Activity
* communicates with {@code BluetoothLeService}, which in turn interacts with the
* Bluetooth LE API.
*/
public class DeviceControlActivity extends BaseActivity {
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private static final long RESULT_DISPLAY_DELAY = 2000;
private PageIndex pageIndex = new PageIndex();
private SelectTestFragment selectTestFragment;
private WaitingFragment waitingFragment;
private ViewPager viewPager;
private FrameLayout resultLayout;
private FrameLayout pagerLayout;
private RelativeLayout footerLayout;
private TestInfo testInfo;
private String mDeviceAddress;
private BluetoothLeService mBluetoothLeService;
// to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private FirebaseAnalytics mFirebaseAnalytics;
private Handler debugTestHandler;
private Handler debugResultHandler;
private boolean showSkipMenu = false;
private BluetoothResultFragment mBluetoothResultFragment;
private String mData;
private PageIndicatorView pagerIndicator;
private boolean registered;
private ArrayList<Instruction> instructionList = new ArrayList<>();
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (Objects.requireNonNull(action)) {
case BluetoothLeService.ACTION_GATT_CONNECTED:
if (AppPreferences.getShowDebugInfo()) {
Toast.makeText(DeviceControlActivity.this,
"Device connected", Toast.LENGTH_SHORT).show();
}
break;
case BluetoothLeService.ACTION_GATT_DISCONNECTED:
Toast.makeText(DeviceControlActivity.this,
"Device disconnected. Check bluetooth settings.", Toast.LENGTH_SHORT).show();
finish();
break;
case BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED:
setGattServices(mBluetoothLeService.getSupportedGattServices());
break;
case BluetoothLeService.ACTION_DATA_AVAILABLE:
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
break;
default:
break;
}
}
};
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
private void registerReceiver() {
if (!registered) {
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
registered = true;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_steps);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
final Intent intent = getIntent();
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
testInfo = intent.getParcelableExtra(ConstantKey.TEST_INFO);
int stepCount = InstructionHelper.setupInstructions(testInfo.getInstructions(),
instructionList, pageIndex, false);
hookBluetooth();
waitingFragment = WaitingFragment.getInstance(stepCount);
mBluetoothResultFragment = BluetoothResultFragment.getInstance(testInfo);
selectTestFragment = SelectTestFragment.getInstance(testInfo);
viewPager = findViewById(R.id.viewPager);
pagerIndicator = findViewById(R.id.pager_indicator);
resultLayout = findViewById(R.id.resultLayout);
pagerLayout = findViewById(R.id.pagerLayout);
footerLayout = findViewById(R.id.layout_footer);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.resultLayout, mBluetoothResultFragment);
ft.commit();
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mSectionsPagerAdapter);
pagerIndicator.showDots(true);
pagerIndicator.setPageCount(mSectionsPagerAdapter.getCount() - 1);
ImageView imagePageRight = findViewById(R.id.image_pageRight);
imagePageRight.setOnClickListener(view ->
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1));
ImageView imagePageLeft = findViewById(R.id.image_pageLeft);
imagePageLeft.setOnClickListener(view -> pageBack());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Nothing to do here
}
@Override
public void onPageSelected(int position) {
pagerIndicator.setActiveIndex(position - 1);
if (position == 0) {
showSelectTestView();
} else if (position == 1) {
showInstructionsView();
} else if (position == instructionList.size() + 1) {
showWaitingView();
} else {
showInstructionsView();
onInstructionFinish(instructionList.size() - position);
}
}
@Override
public void onPageScrollStateChanged(int state) {
// Nothing to do here
}
});
showSelectTestView();
}
private void pageBack() {
viewPager.setCurrentItem(Math.max(0, viewPager.getCurrentItem() - 1));
}
@Override
protected void onResume() {
super.onResume();
registerReceiver();
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
if (!result) {
finish();
}
}
}
private boolean waitingForResult() {
return viewPager.getCurrentItem() == instructionList.size() + 1;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (showSkipMenu) {
getMenuInflater().inflate(R.menu.menu_instructions, menu);
}
return true;
}
@Override
protected void onPause() {
super.onPause();
unHookBluetooth();
}
private void hookBluetooth() {
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
private void unHookBluetooth() {
unregisterReceiver();
if (debugTestHandler != null) {
debugTestHandler.removeCallbacksAndMessages(null);
}
if (debugResultHandler != null) {
debugResultHandler.removeCallbacksAndMessages(null);
}
}
private void unregisterReceiver() {
try {
unregisterReceiver(mGattUpdateReceiver);
registered = false;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unHookBluetooth();
unbindServices();
mBluetoothLeService = null;
}
private void unbindServices() {
try {
unbindService(mServiceConnection);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (viewPager.getCurrentItem() == 0) {
onBackPressed();
} else {
showSelectTestView();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (debugTestHandler != null) {
debugTestHandler.removeCallbacksAndMessages(null);
}
if (debugResultHandler != null) {
debugResultHandler.removeCallbacksAndMessages(null);
}
if (resultLayout.getVisibility() == View.VISIBLE) {
viewPager.setCurrentItem(instructionList.size() + 1);
showWaitingView();
} else if (viewPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
pageBack();
}
}
private void displayData(String data) {
if (!waitingForResult()) {
return;
}
mData += data;
Matcher m = Pattern.compile("DT01;((?!DT01;).)*?;;;;").matcher(mData);
if (m.find()) {
unregisterReceiver();
final String fullData = m.group();
mData = "";
final ProgressDialog dlg = new ProgressDialog(this);
dlg.setMessage("Receiving data");
dlg.setCancelable(false);
dlg.show();
if (debugResultHandler != null) {
debugResultHandler.removeCallbacksAndMessages(null);
}
debugResultHandler = new Handler();
debugResultHandler.postDelayed(() -> {
try {
if (mBluetoothResultFragment.displayData(fullData)) {
setTitle(R.string.result);
showResultView();
} else {
registerReceiver();
}
} catch (Exception e) {
Toast.makeText(this, getString(R.string.invalid_data_received), Toast.LENGTH_LONG).show();
Timber.e("Bluetooth data error: %s", fullData);
}
dlg.dismiss();
}, RESULT_DISPLAY_DELAY);
}
}
private void setGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) {
return;
}
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
// The characteristic 'Data' must be set to "indicate"
if (gattCharacteristic.getUuid().toString().equals(GattAttributes.LOVIBOND_DATA_CHARACTERISTIC)) {
mBluetoothLeService.setCharacteristicIndication(gattCharacteristic, true);
}
}
}
}
private void showInstructionsView() {
footerLayout.setVisibility(View.VISIBLE);
pagerLayout.setVisibility(View.VISIBLE);
resultLayout.setVisibility(View.GONE);
setTitle(testInfo.getMd610Id() + ". " + testInfo.getName());
showSkipMenu = true;
invalidateOptionsMenu();
}
private void showSelectTestView() {
pagerLayout.setVisibility(View.VISIBLE);
resultLayout.setVisibility(View.GONE);
footerLayout.setVisibility(View.GONE);
viewPager.setCurrentItem(0);
showSkipMenu = false;
setTitle(R.string.selectTest);
invalidateOptionsMenu();
}
private void showWaitingView() {
registerReceiver();
pagerLayout.setVisibility(View.VISIBLE);
resultLayout.setVisibility(View.GONE);
footerLayout.setVisibility(View.GONE);
showSkipMenu = false;
setTitle(R.string.awaitingResult);
invalidateOptionsMenu();
if (AppPreferences.isTestMode()) {
if (debugTestHandler != null) {
debugTestHandler.removeCallbacksAndMessages(null);
}
debugTestHandler = new Handler();
debugTestHandler.postDelayed(() -> {
if (testInfo.getUuid().equals(Constants.FLUORIDE_ID)) {
displayData(Constants.BLUETOOTH_TEST_DATA_F);
} else {
displayData(Constants.BLUETOOTH_TEST_DATA);
}
}, 6000);
}
}
private void showResultView() {
resultLayout.setVisibility(View.VISIBLE);
pagerLayout.setVisibility(View.GONE);
}
private void onInstructionFinish(int page) {
if (page > 1) {
showSkipMenu = true;
invalidateOptionsMenu();
} else if (page == 0) {
showSkipMenu = false;
invalidateOptionsMenu();
}
}
public void onSkipClick(MenuItem item) {
viewPager.setCurrentItem(instructionList.size() + 1);
showWaitingView();
if (AppPreferences.analyticsEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("InstructionsSkipped", testInfo.getName() +
" (" + testInfo.getBrand() + ")");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Navigation");
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "si_" + testInfo.getUuid());
mFirebaseAnalytics.logEvent("instruction_skipped", bundle);
}
}
public void onSelectTestClick(View view) {
viewPager.setCurrentItem(1);
showInstructionsView();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
FragmentInstructionBinding fragmentInstructionBinding;
Instruction instruction;
/**
* Returns a new instance of this fragment for the given section number.
*
* @param instruction The information to to display
* @return The instance
*/
static PlaceholderFragment newInstance(Instruction instruction) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SECTION_NUMBER, instruction);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentInstructionBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_instruction, container, false);
if (getArguments() != null) {
instruction = getArguments().getParcelable(ARG_SECTION_NUMBER);
fragmentInstructionBinding.setInstruction(instruction);
}
return fragmentInstructionBinding.getRoot();
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return selectTestFragment;
} else if (position == instructionList.size() + 1) {
return waitingFragment;
} else {
return PlaceholderFragment.newInstance(instructionList.get(position - 1));
}
}
@Override
public int getCount() {
return instructionList.size() + 2;
}
}
}
| 19,750 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SelectTestFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/bluetooth/SelectTestFragment.java | package org.akvo.caddisfly.sensor.bluetooth;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.util.StringUtil;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class SelectTestFragment extends Fragment {
private TestInfo testInfo;
public static SelectTestFragment getInstance(TestInfo testInfo) {
SelectTestFragment fragment = new SelectTestFragment();
Bundle args = new Bundle();
args.putParcelable(ConstantKey.TEST_INFO, testInfo);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_select_test, container, false);
if (getArguments() != null) {
testInfo = getArguments().getParcelable(ConstantKey.TEST_INFO);
}
SpannableStringBuilder selectionInstruction = StringUtil.toInstruction((AppCompatActivity) getActivity(), testInfo,
String.format(StringUtil.getStringByName(getContext(), testInfo.getSelectInstruction()),
StringUtil.convertToTags(testInfo.getMd610Id()), testInfo.getName()));
((TextView) view.findViewById(R.id.textSelectInstruction)).setText(selectionInstruction);
return view;
}
}
| 1,735 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CbtActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/cbt/CbtActivity.java | package org.akvo.caddisfly.sensor.cbt;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.concatTwoBitmapsHorizontal;
import static org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils.concatTwoBitmapsVertical;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueUnitString;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.databinding.FragmentInstructionBinding;
import org.akvo.caddisfly.helper.InstructionHelper;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.MpnValue;
import org.akvo.caddisfly.model.PageIndex;
import org.akvo.caddisfly.model.PageType;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.sensor.manual.ResultPhotoFragment;
import org.akvo.caddisfly.sensor.striptest.utils.BitmapUtils;
import org.akvo.caddisfly.ui.BaseActivity;
import org.akvo.caddisfly.ui.BaseFragment;
import org.akvo.caddisfly.util.StringUtil;
import org.akvo.caddisfly.widget.ButtonType;
import org.akvo.caddisfly.widget.CustomViewPager;
import org.akvo.caddisfly.widget.PageIndicatorView;
import org.akvo.caddisfly.widget.SwipeDirection;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Objects;
import java.util.UUID;
public class CbtActivity extends BaseActivity
implements CompartmentBagFragment.OnCompartmentBagSelectListener,
ResultPhotoFragment.OnPhotoTakenListener {
private CbtResultFragment resultFragment;
private final SparseArray<ResultPhotoFragment> resultPhotoFragment = new SparseArray<>();
private final SparseArray<CompartmentBagFragment> inputFragment = new SparseArray<>();
private final ArrayList<Integer> inputIndexes = new ArrayList<>();
private final SparseArray<String> cbtResultKeys = new SparseArray<>();
private ImageView imagePageRight;
private ImageView imagePageLeft;
private final PageIndex pageIndex = new PageIndex();
private String imageFileName = "";
private String currentPhotoPath;
private TestInfo testInfo;
private FirebaseAnalytics mFirebaseAnalytics;
private final ArrayList<Instruction> instructionList = new ArrayList<>();
private int totalPageCount;
private RelativeLayout footerLayout;
private PageIndicatorView pagerIndicator;
private boolean showSkipMenu = true;
private CustomViewPager viewPager;
private int testPhase;
private float scale;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_steps);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
scale = getResources().getDisplayMetrics().density;
viewPager = findViewById(R.id.viewPager);
pagerIndicator = findViewById(R.id.pager_indicator);
footerLayout = findViewById(R.id.layout_footer);
if (savedInstanceState != null) {
currentPhotoPath = savedInstanceState.getString(ConstantKey.CURRENT_PHOTO_PATH);
imageFileName = savedInstanceState.getString(ConstantKey.CURRENT_IMAGE_FILE_NAME);
testInfo = savedInstanceState.getParcelable(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
testInfo = getIntent().getParcelableExtra(ConstantKey.TEST_INFO);
}
if (testInfo == null) {
return;
}
testPhase = getIntent().getIntExtra(ConstantKey.TEST_PHASE, 0);
if (testPhase == 2) {
InstructionHelper.setupInstructions(testInfo.getInstructions2(), instructionList, pageIndex, false);
} else {
InstructionHelper.setupInstructions(testInfo.getInstructions(), instructionList, pageIndex, false);
}
totalPageCount = instructionList.size();
if (savedInstanceState == null) {
createFragments();
}
viewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
pagerIndicator.showDots(true);
pagerIndicator.setPageCount(totalPageCount);
imagePageRight = findViewById(R.id.image_pageRight);
imagePageRight.setOnClickListener(view -> nextPage());
imagePageLeft = findViewById(R.id.image_pageLeft);
imagePageLeft.setVisibility(View.INVISIBLE);
imagePageLeft.setOnClickListener(view -> pageBack());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (resultPhotoFragment.get(position - 1) != null &&
!resultPhotoFragment.get(position - 1).isValid()) {
pageBack();
return;
}
pagerIndicator.setActiveIndex(position);
showHideFooter();
if (pageIndex.getType(position) == PageType.PHOTO && position > 2) {
if (cbtResultKeys.size() > 0) {
if (cbtResultKeys.get(inputIndexes.get(0)).equals("11111")) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 3, true);
}
}
}
if (pageIndex.getType(position) == PageType.INPUT && position > 3) {
if (cbtResultKeys.size() > 0) {
if (cbtResultKeys.get(inputIndexes.get(0)).equals("11111")) {
viewPager.setCurrentItem(pageIndex.getInputPageIndex(0), true);
}
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
showHideFooter();
}
private void createFragments() {
if (resultFragment == null) {
resultFragment = CbtResultFragment.newInstance(testInfo.getResults().size());
resultFragment.setFragmentId(pageIndex.getResultIndex());
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(ConstantKey.CURRENT_PHOTO_PATH, currentPhotoPath);
outState.putString(ConstantKey.CURRENT_IMAGE_FILE_NAME, imageFileName);
outState.putParcelable(ConstantKey.TEST_INFO, testInfo);
super.onSaveInstanceState(outState);
}
@Override
public void onRestoreInstanceState(@NotNull Bundle inState) {
for (int i = 0; i < getSupportFragmentManager().getFragments().size(); i++) {
Fragment fragment = getSupportFragmentManager().getFragments().get(i);
if (fragment instanceof ResultPhotoFragment) {
resultPhotoFragment.put(((BaseFragment) fragment).getFragmentId(),
(ResultPhotoFragment) fragment);
}
if (fragment instanceof CompartmentBagFragment) {
inputFragment.put(((BaseFragment) fragment).getFragmentId(),
(CompartmentBagFragment) fragment);
}
}
createFragments();
super.onRestoreInstanceState(inState);
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
showHideFooter();
}
private void pageBack() {
viewPager.setCurrentItem(Math.max(0, viewPager.getCurrentItem() - 1));
}
private void nextPage() {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
private void showHideFooter() {
if (imagePageLeft == null) {
return;
}
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageLeft.setVisibility(View.VISIBLE);
imagePageRight.setVisibility(View.VISIBLE);
pagerIndicator.setVisibility(View.VISIBLE);
footerLayout.setVisibility(View.VISIBLE);
setTitle(testInfo.getName());
showSkipMenu = viewPager.getCurrentItem() < pageIndex.getSkipToIndex() - 2;
if (viewPager.getCurrentItem() > pageIndex.getSkipToIndex()) {
showSkipMenu = viewPager.getCurrentItem() < pageIndex.getSkipToIndex2() - 2;
}
switch (pageIndex.getType(viewPager.getCurrentItem())) {
case PHOTO:
if (resultPhotoFragment.get(viewPager.getCurrentItem()) != null) {
if (resultPhotoFragment.get(viewPager.getCurrentItem()).isValid()) {
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
imagePageRight.setVisibility(View.VISIBLE);
} else {
viewPager.setAllowedSwipeDirection(SwipeDirection.left);
imagePageRight.setVisibility(View.INVISIBLE);
}
}
break;
case INPUT:
setTitle(R.string.setCompartmentColors);
break;
case RESULT:
setTitle(R.string.result);
break;
case DEFAULT:
footerLayout.setVisibility(View.VISIBLE);
viewPager.setAllowedSwipeDirection(SwipeDirection.all);
break;
}
// Last page
if (viewPager.getCurrentItem() == totalPageCount - 1) {
imagePageRight.setVisibility(View.INVISIBLE);
if (testPhase == 2) {
if (scale <= 1.5) {
// don't show footer page indicator for smaller screens
(new Handler()).postDelayed(() -> footerLayout.setVisibility(View.GONE), 400);
}
}
}
// First page
if (viewPager.getCurrentItem() == 0) {
imagePageLeft.setVisibility(View.INVISIBLE);
}
invalidateOptionsMenu();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(testInfo.getName());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (showSkipMenu) {
getMenuInflater().inflate(R.menu.menu_instructions, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (viewPager.getCurrentItem() == 0) {
onBackPressed();
} else {
viewPager.setCurrentItem(0);
showHideFooter();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (viewPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
pageBack();
}
}
/**
* Show CBT incubation times instructions in a dialog.
*
* @param view the view
*/
public void onClickIncubationTimes(@SuppressWarnings("unused") View view) {
DialogFragment newFragment = new CbtActivity.IncubationTimesDialogFragment();
newFragment.show(getSupportFragmentManager(), "incubationTimes");
}
public void onSkipClick(MenuItem item) {
viewPager.setCurrentItem(pageIndex.getSkipToIndex());
if (AppPreferences.analyticsEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("InstructionsSkipped", testInfo.getName() +
" (" + testInfo.getBrand() + ")");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Navigation");
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "si_" + testInfo.getUuid());
mFirebaseAnalytics.logEvent("instruction_skipped", bundle);
}
}
public void onCompartmentBagSelect(String key, int fragmentId) {
int secondFragmentId = 0;
// Get the id of the TC input fragment
if (inputIndexes.size() > 1) {
secondFragmentId = inputIndexes.get(1);
}
cbtResultKeys.put(fragmentId, key);
for (int i = 0; i < inputIndexes.size(); i++) {
inputFragment.get(inputIndexes.get(0));
}
String secondResult;
String newSecondResult = key.replace("1", "2");
CompartmentBagFragment secondFragment = null;
if (fragmentId == inputIndexes.get(0)) {
resultFragment.setResult(cbtResultKeys.get(fragmentId), testInfo.getSampleQuantity());
if (inputIndexes.size() > 1) {
secondFragment = inputFragment.get(secondFragmentId);
secondResult = secondFragment.getKey();
} else {
secondResult = newSecondResult;
}
for (int i = 0; i < secondResult.length(); i++) {
if (secondResult.charAt(i) == '1' && newSecondResult.charAt(i) != '2') {
char[] chars = newSecondResult.toCharArray();
chars[i] = '1';
newSecondResult = String.valueOf(chars);
}
}
if (secondFragment != null) {
secondFragment.setKey(newSecondResult);
}
}
resultFragment.setResult2(newSecondResult, testInfo.getSampleQuantity());
// If E.coli input fragment then add or remove TC part based on input
if (fragmentId != secondFragmentId) {
InstructionHelper.setupInstructions(testInfo.getInstructions2(), instructionList, pageIndex, key.equals("11111"));
totalPageCount = instructionList.size();
pagerIndicator.setPageCount(totalPageCount);
Objects.requireNonNull(viewPager.getAdapter()).notifyDataSetChanged();
pagerIndicator.setVisibility(View.GONE);
pagerIndicator.invalidate();
pagerIndicator.setVisibility(View.VISIBLE);
}
}
public void onNextClick(View view) {
nextPage();
}
public void onCloseClick(View view) {
setResult(Activity.RESULT_FIRST_USER, new Intent());
finish();
}
public void onSubmitClick(View view) {
sendResults();
}
private void sendResults() {
SparseArray<String> results = new SparseArray<>();
Intent resultIntent = new Intent();
Bitmap resultBitmap = null;
if (resultPhotoFragment.get(pageIndex.getPhotoPageIndex(0)) != null) {
imageFileName = UUID.randomUUID().toString() + ".jpg";
String resultImagePath = resultPhotoFragment.get(pageIndex.getPhotoPageIndex(0)).getImageFileName();
Bitmap bitmap1 = BitmapFactory.decodeFile(resultImagePath);
if (resultPhotoFragment.get(pageIndex.getPhotoPageIndex(1)) != null) {
String result1ImagePath = resultPhotoFragment.get(pageIndex.getPhotoPageIndex(1)).getImageFileName();
Bitmap bitmap2 = BitmapFactory.decodeFile(result1ImagePath);
if (bitmap1 != null && bitmap2 != null) {
if (Math.abs(bitmap1.getWidth() - bitmap2.getWidth()) > 50) {
bitmap2 = BitmapUtils.RotateBitmap(bitmap2, 90);
}
if (bitmap1.getWidth() > bitmap1.getHeight()) {
resultBitmap = concatTwoBitmapsHorizontal(bitmap1, bitmap2);
} else {
resultBitmap = concatTwoBitmapsVertical(bitmap1, bitmap2);
}
bitmap1.recycle();
bitmap2.recycle();
//noinspection ResultOfMethodCallIgnored
new File(result1ImagePath).delete();
//noinspection ResultOfMethodCallIgnored
new File(resultImagePath).delete();
}
} else {
resultBitmap = bitmap1;
}
}
MpnValue mpnValue = TestConfigHelper.getMpnValueForKey(
resultFragment.getResult(), testInfo.getSampleQuantity());
MpnValue mpnTcValue = TestConfigHelper.getMpnValueForKey(
resultFragment.getResult2(), testInfo.getSampleQuantity());
results.put(1, StringUtil.getStringResourceByName(this,
mpnValue.getRiskCategory(), "en").toString());
results.put(2, mpnValue.getMpn());
results.put(3, String.valueOf(mpnValue.getConfidence()));
results.put(4, mpnTcValue.getMpn());
results.put(5, String.valueOf(mpnTcValue.getConfidence()));
JSONObject resultJson = TestConfigHelper.getJsonResult(this, testInfo,
results, null, imageFileName);
resultIntent.putExtra(SensorConstants.RESPONSE, resultJson.toString());
if (!imageFileName.isEmpty() && resultBitmap != null) {
resultIntent.putExtra(SensorConstants.IMAGE, imageFileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resultBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
resultBitmap.recycle();
resultIntent.putExtra(SensorConstants.IMAGE_BITMAP, stream.toByteArray());
}
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
@Override
public void onPhotoTaken() {
nextPage();
}
public static class IncubationTimesDialogFragment extends DialogFragment {
@NonNull
@SuppressLint("InflateParams")
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_incubation_times, null))
// Add action buttons
.setPositiveButton(R.string.ok, (dialog, id) -> dialog.dismiss());
return builder.create();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_SHOW_OK = "show_ok";
FragmentInstructionBinding fragmentInstructionBinding;
Instruction instruction;
private ButtonType showButton;
private LinearLayout resultLayout;
private ViewGroup viewRoot;
/**
* Returns a new instance of this fragment for the given section number.
*
* @param instruction The information to to display
* @param showButton The button to be shown
* @return The instance
*/
@SuppressWarnings("SameParameterValue")
static PlaceholderFragment newInstance(Instruction instruction, ButtonType showButton) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SECTION_NUMBER, instruction);
args.putSerializable(ARG_SHOW_OK, showButton);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentInstructionBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_instruction, container, false);
viewRoot = container;
if (getArguments() != null) {
instruction = getArguments().getParcelable(ARG_SECTION_NUMBER);
showButton = (ButtonType) getArguments().getSerializable(ARG_SHOW_OK);
fragmentInstructionBinding.setInstruction(instruction);
}
View view = fragmentInstructionBinding.getRoot();
switch (showButton) {
case START:
view.findViewById(R.id.buttonStart).setVisibility(View.VISIBLE);
break;
case CLOSE:
view.findViewById(R.id.buttonClose).setVisibility(View.VISIBLE);
break;
case SUBMIT:
view.findViewById(R.id.buttonSubmit).setVisibility(View.VISIBLE);
break;
}
resultLayout = view.findViewById(R.id.layout_results);
return view;
}
public void setResult(TestInfo testInfo) {
if (testInfo != null) {
LayoutInflater inflater = (LayoutInflater) Objects.requireNonNull(getActivity())
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resultLayout.removeAllViews();
SparseArray<String> results = new SparseArray<>();
results.put(1, String.valueOf(testInfo.getResults().get(0).getResultValue()));
results.put(2, String.valueOf(testInfo.getResults().get(1).getResultValue()));
for (Result result : testInfo.getResults()) {
String valueString = createValueUnitString(result.getResultValue(), result.getUnit(),
getString(R.string.no_result));
LinearLayout itemResult;
itemResult = (LinearLayout) inflater.inflate(R.layout.item_result,
viewRoot, false);
TextView textTitle = itemResult.findViewById(R.id.text_title);
textTitle.setText(result.getName());
TextView textResult = itemResult.findViewById(R.id.text_result);
textResult.setText(valueString);
resultLayout.addView(itemResult);
}
resultLayout.setVisibility(View.VISIBLE);
}
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (pageIndex.getResultIndex() == position) {
return resultFragment;
} else if (pageIndex.getType(position) == PageType.INPUT) {
if (inputFragment.get(position) == null) {
String key = "00000";
boolean useBlue = false;
if (inputIndexes.size() > 0) {
int firstFragmentId = inputIndexes.get(0);
if (cbtResultKeys.get(firstFragmentId) == null) {
cbtResultKeys.put(firstFragmentId, key);
}
key = cbtResultKeys.get(firstFragmentId).replace("1", "2");
resultFragment.setResult2(key, testInfo.getSampleQuantity());
}
if (inputFragment.size() > 0) {
useBlue = true;
}
inputFragment.put(position, CompartmentBagFragment.newInstance(key, position,
instructionList.get(position), useBlue));
inputIndexes.add(position);
}
return inputFragment.get(position);
} else if (pageIndex.getType(position) == PageType.PHOTO) {
if (resultPhotoFragment.get(position) == null) {
resultPhotoFragment.put(position, ResultPhotoFragment.newInstance(
"", instructionList.get(position), position));
}
return resultPhotoFragment.get(position);
} else if (position == totalPageCount - 1) {
if (testPhase == 2) {
return PlaceholderFragment.newInstance(
instructionList.get(position), ButtonType.SUBMIT);
}
return PlaceholderFragment.newInstance(
instructionList.get(position), ButtonType.CLOSE);
} else {
return PlaceholderFragment.newInstance(
instructionList.get(position), ButtonType.NONE);
}
}
@Override
public int getCount() {
return totalPageCount;
}
@Override
public int getItemPosition(@NonNull Object object) {
return PagerAdapter.POSITION_NONE;
}
}
}
| 26,251 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CbtResultFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/cbt/CbtResultFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.cbt;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.databinding.FragmentCbtResultBinding;
import org.akvo.caddisfly.helper.TestConfigHelper;
import org.akvo.caddisfly.model.MpnValue;
import org.akvo.caddisfly.ui.BaseFragment;
import org.akvo.caddisfly.util.StringUtil;
import java.util.Objects;
public class CbtResultFragment extends BaseFragment {
private static final String ARG_RESULT_COUNT = "result_count";
private MpnValue mpnValue = null;
private MpnValue mpnValue2 = null;
private String result = "00000";
private String result2 = "00000";
private FragmentCbtResultBinding b;
private int resultCount = 1;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment CbtResultFragment.
*/
public static CbtResultFragment newInstance(int resultCount) {
CbtResultFragment fragment = new CbtResultFragment();
Bundle args = new Bundle();
args.putInt(ARG_RESULT_COUNT, resultCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
resultCount = getArguments().getInt(ARG_RESULT_COUNT);
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
b = DataBindingUtil.inflate(inflater,
R.layout.fragment_cbt_result, container, false);
if (mpnValue == null) {
mpnValue = TestConfigHelper.getMpnValueForKey("00000", "0");
}
if (mpnValue2 == null) {
mpnValue2 = TestConfigHelper.getMpnValueForKey("00000", "0");
}
showResult();
return b.getRoot();
}
void setResult(String result, String sampleQuantity) {
this.result = result;
mpnValue = TestConfigHelper.getMpnValueForKey(result, sampleQuantity);
showResult();
}
void setResult2(String result, String sampleQuantity) {
this.result2 = result;
mpnValue2 = TestConfigHelper.getMpnValueForKey(result, sampleQuantity);
showResult();
}
private void showResult() {
if (getActivity() != null) {
String[] results = StringUtil.getStringResourceByName(Objects.requireNonNull(getActivity()),
mpnValue.getRiskCategory()).toString().split("/");
b.textSubRisk.setText("");
if (resultCount > 3) {
b.layoutResult2.setVisibility(View.VISIBLE);
b.layoutRisk.setVisibility(View.GONE);
b.layoutRisk2.setVisibility(View.VISIBLE);
b.textName1.setVisibility(View.VISIBLE);
b.textRisk1.setText(results[0].trim());
if (results.length > 1) {
b.textSubRisk2.setText(results[1].trim());
b.textSubRisk2.setVisibility(View.VISIBLE);
} else {
b.textSubRisk2.setVisibility(View.GONE);
}
} else {
b.layoutResult2.setVisibility(View.GONE);
b.layoutRisk.setVisibility(View.VISIBLE);
b.layoutRisk2.setVisibility(View.GONE);
b.textName1.setVisibility(View.GONE);
b.textRisk.setText(results[0].trim());
if (results.length > 1) {
b.textSubRisk.setText(results[1].trim());
b.textSubRisk.setVisibility(View.VISIBLE);
} else {
b.textSubRisk.setVisibility(View.GONE);
}
}
b.layoutRisk.setBackgroundColor(mpnValue.getBackgroundColor1());
b.layoutRisk2.setBackgroundColor(mpnValue.getBackgroundColor1());
b.textResult1.setText(mpnValue.getMpn());
b.textResult2.setText(mpnValue2.getMpn());
}
}
String getResult() {
return result;
}
String getResult2() {
return result2;
}
}
| 5,178 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CustomShapeButton.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/cbt/CustomShapeButton.java | package org.akvo.caddisfly.sensor.cbt;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import org.akvo.caddisfly.R;
public class CustomShapeButton extends View {
private final Path mPath = new Path();
private final Path markerPath = new Path();
private final Paint yellowPaint = new Paint();
private final Paint yellowSelectPaint = new Paint();
private final Paint selectPaint = new Paint();
private final Paint activePaint = new Paint();
private final Paint disabledPaint = new Paint();
private final Paint strokePaint = new Paint();
private final Paint markerPaint = new Paint();
private final Paint textPaint = new Paint();
private final Paint disabledTextPaint = new Paint();
private int colWidth;
private int bottom;
private int bottom3;
private int bottom2;
private int bottom1;
private int area1 = 0;
private int area2 = 0;
private int area3 = 0;
private int area4 = 0;
private int area5 = 0;
private boolean active1 = false;
private boolean active2 = false;
private boolean active3 = false;
private boolean active4 = false;
private boolean active5 = false;
private Rect rect1;
private String mKey;
public CustomShapeButton(Context context, AttributeSet attrs) {
super(context, attrs);
// fill
yellowPaint.setStyle(Paint.Style.FILL);
yellowPaint.setColor(Color.rgb(255, 238, 170));
yellowSelectPaint.setColor(Color.rgb(255, 248, 180));
disabledPaint.setColor(Color.rgb(69, 159, 159));
// stroke
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setColor(Color.rgb(100, 100, 100));
strokePaint.setStrokeWidth(5);
markerPaint.setStyle(Paint.Style.STROKE);
markerPaint.setColor(Color.rgb(219, 210, 39));
markerPaint.setStrokeWidth(20);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
textPaint.setColor(Color.rgb(30, 30, 30));
int sizeInPx = context.getResources().getDimensionPixelSize(R.dimen.cbt_shapes_text_size);
textPaint.setTextSize(sizeInPx);
disabledTextPaint.setStyle(Paint.Style.FILL);
disabledTextPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
disabledTextPaint.setColor(Color.rgb(120, 120, 120));
disabledTextPaint.setTextSize(sizeInPx);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
float x = event.getX();
float y = event.getY();
if (action == MotionEvent.ACTION_UP) {
if (x < colWidth && y < bottom3) {
area1 = toggle(area1);
} else if (x < colWidth * 2 && y < bottom) {
area2 = toggle(area2);
} else if (x > colWidth * 4 && y < bottom1) {
area5 = toggle(area5);
} else if (x > colWidth * 3 && x < colWidth * 4 && y < bottom2) {
area4 = toggle(area4);
} else if ((x > colWidth * 2 && x < colWidth * 3)
|| (x > colWidth * 3 && y > bottom2 && x < (colWidth * 4) + (colWidth / (double) 3))) {
area3 = toggle(area3);
}
active1 = false;
active2 = false;
active3 = false;
active4 = false;
active5 = false;
invalidate();
performClick();
return true;
} else if (action == MotionEvent.ACTION_DOWN) {
if (x < colWidth && y < bottom3) {
active1 = true;
} else if (x < colWidth * 2 && y < bottom) {
active2 = true;
} else if (x > colWidth * 4 && y < bottom1) {
active5 = true;
} else if (x > colWidth * 3 && x < colWidth * 4 && y < bottom2) {
active4 = true;
} else if ((x > colWidth * 2 && x < colWidth * 3)
|| (x > colWidth * 3 && y > bottom2 && x < (colWidth * 4) + (colWidth / (double) 3))) {
active3 = true;
}
invalidate();
return true;
} else if (action == MotionEvent.ACTION_CANCEL) {
active1 = false;
active2 = false;
active3 = false;
active4 = false;
active5 = false;
invalidate();
return true;
}
getKey();
return false;
}
private int toggle(int area1) {
if (area1 != 2) {
if (area1 == 0) {
return 1;
} else {
return 0;
}
}
return area1;
}
@Override
public boolean performClick() {
// Calls the super implementation, which generates an AccessibilityEvent
// and calls the onClick() listener on the view, if any
super.performClick();
// Handle the action for the custom click here
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int lineTop = 60;
int fillLine = 80;
int left = 0;
colWidth = (getWidth() / 5);
bottom = (int) (getHeight() - strokePaint.getStrokeWidth());
int fillHeight = bottom - fillLine;
bottom1 = (int) (fillHeight * 0.2) + lineTop;
bottom2 = (int) (fillHeight * 0.36) + lineTop;
bottom3 = (int) (fillHeight * 0.64) + lineTop;
if (rect1 == null) {
rect1 = new Rect(left, fillLine, colWidth, bottom3);
}
canvas.drawRect(rect1, getPaint(area1, active1));
canvas.drawRect(left, bottom3, colWidth, bottom, getPaint(area2, active2));
canvas.drawRect(colWidth, fillLine, colWidth * 2, bottom, getPaint(area2, active2));
canvas.drawRect(colWidth * 2, fillLine, colWidth * 3, bottom, getPaint(area3, active3));
canvas.drawRect(colWidth * 3, bottom2, colWidth * 4 + (colWidth / 3), bottom, getPaint(area3, active3));
canvas.drawRect(colWidth * 3, fillLine, colWidth * 4, bottom2, getPaint(area4, active4));
canvas.drawRect(colWidth * 4, fillLine, colWidth * 5, bottom1, getPaint(area5, active5));
mPath.moveTo(left, lineTop);
mPath.lineTo(left, bottom);
mPath.lineTo(colWidth * 2, bottom);
mPath.lineTo(colWidth * 2, lineTop);
mPath.moveTo(colWidth, lineTop);
mPath.lineTo(colWidth, bottom3);
mPath.lineTo(left, bottom3);
mPath.moveTo(colWidth * 3, lineTop);
mPath.lineTo(colWidth * 3, bottom2);
mPath.lineTo((colWidth * 4) + (colWidth / 3), bottom2);
mPath.lineTo((colWidth * 4) + (colWidth / 3), bottom);
mPath.lineTo((colWidth * 2), bottom);
mPath.moveTo(colWidth * 4, lineTop);
mPath.lineTo(colWidth * 4, bottom2);
mPath.moveTo(colWidth * 4, bottom1);
mPath.lineTo(colWidth * 5, bottom1);
mPath.lineTo(colWidth * 5, lineTop);
canvas.drawPath(mPath, strokePaint);
// Yellow marker on the top of the bag
markerPath.moveTo(left, 30f);
markerPath.lineTo(getWidth(), 30f);
canvas.drawPath(markerPath, markerPaint);
int halfWidth = colWidth / 2;
canvas.drawText("1", halfWidth - 10, fillLine + (bottom3 / 2) - 10, getTextPaint(area1));
canvas.drawText("2", colWidth - 10, bottom3 + ((bottom - bottom3) / 2), getTextPaint(area2));
canvas.drawText("3", (colWidth * 3) + 20, fillLine + (bottom - bottom2), getTextPaint(area3));
canvas.drawText("4", halfWidth - 10 + colWidth * 3, fillLine + (bottom2 / 2) - 20, getTextPaint(area4));
canvas.drawText("5", halfWidth - 10 + colWidth * 4, fillLine + (bottom1 / 2) - 26, getTextPaint(area5));
}
public String getKey() {
mKey = String.valueOf(area1)
+ area2
+ area3
+ area4
+ area5;
return mKey;
}
public void setKey(String key) {
try {
mKey = key;
String[] values = mKey.split("");
area1 = Integer.parseInt(values[1]);
area2 = Integer.parseInt(values[2]);
area3 = Integer.parseInt(values[3]);
area4 = Integer.parseInt(values[4]);
area5 = Integer.parseInt(values[5]);
} catch (Exception e) {
mKey = "00000";
}
}
private Paint getPaint(int value, boolean active) {
switch (value) {
case 0:
return active ? yellowSelectPaint : yellowPaint;
case 1:
return active ? activePaint : selectPaint;
}
return disabledPaint;
}
private Paint getTextPaint(int value) {
if (value == 2) {
return disabledTextPaint;
}
return textPaint;
}
public void useBlueSelection(boolean value) {
if (value) {
selectPaint.setColor(Color.rgb(34, 206, 255));
activePaint.setColor(Color.rgb(20, 170, 235));
} else {
selectPaint.setColor(Color.rgb(69, 159, 159));
activePaint.setColor(Color.rgb(79, 165, 165));
}
}
} | 9,555 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CompartmentBagFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/sensor/cbt/CompartmentBagFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.sensor.cbt;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.databinding.FragmentCompartmentBagBinding;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.ui.BaseFragment;
public class CompartmentBagFragment extends BaseFragment {
private static final String ARG_INSTRUCTION = "resultInstruction";
private static final String ARG_RESULT_VALUES = "result_key";
private static final String ARG_USE_BLUE = "use_blue_selection";
private OnCompartmentBagSelectListener mListener;
private String resultValues = "";
private Boolean useBlue;
private FragmentCompartmentBagBinding b;
public static CompartmentBagFragment newInstance(String key, int id,
Instruction instruction, boolean useBlue) {
CompartmentBagFragment fragment = new CompartmentBagFragment();
fragment.setFragmentId(id);
Bundle args = new Bundle();
args.putParcelable(ARG_INSTRUCTION, instruction);
args.putString(ARG_RESULT_VALUES, key);
args.putBoolean(ARG_USE_BLUE, useBlue);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null && resultValues.isEmpty()) {
resultValues = getArguments().getString(ARG_RESULT_VALUES);
useBlue = getArguments().getBoolean(ARG_USE_BLUE);
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
b = DataBindingUtil.inflate(inflater,
R.layout.fragment_compartment_bag, container, false);
Instruction instruction = getArguments().getParcelable(ARG_INSTRUCTION);
b.setInstruction(instruction);
b.compartments.setKey(resultValues);
b.compartments.useBlueSelection(useBlue);
b.compartments.setOnClickListener(v -> {
resultValues = b.compartments.getKey();
if (mListener != null) {
mListener.onCompartmentBagSelect(resultValues, getFragmentId());
}
});
return b.getRoot();
}
public String getKey() {
return resultValues;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnCompartmentBagSelectListener) {
mListener = (OnCompartmentBagSelectListener) context;
} else {
throw new IllegalArgumentException(context.toString()
+ " must implement OnCompartmentBagSelectListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void setKey(String key) {
resultValues = key;
}
public interface OnCompartmentBagSelectListener {
void onCompartmentBagSelect(String key, int fragmentId);
}
}
| 4,045 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestInfoAdapter.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/TestInfoAdapter.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.ui;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.databinding.TestItemBinding;
import org.akvo.caddisfly.model.TestInfo;
import java.util.List;
public class TestInfoAdapter extends RecyclerView.Adapter<TestInfoAdapter.TestInfoViewHolder> {
@Nullable
private final TestInfoClickCallback mTestInfoClickCallback;
private List<? extends TestInfo> mTestList;
TestInfoAdapter(@Nullable TestInfoClickCallback clickCallback) {
mTestInfoClickCallback = clickCallback;
}
void setTestList(final List<? extends TestInfo> testList) {
if (mTestList != null) {
mTestList.clear();
}
mTestList = testList;
notifyItemRangeInserted(0, testList.size());
}
@NonNull
@Override
public TestInfoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
TestItemBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()), R.layout.test_item,
parent, false);
binding.setCallback(mTestInfoClickCallback);
return new TestInfoViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull TestInfoViewHolder holder, int position) {
holder.binding.setTestInfo(mTestList.get(position));
holder.binding.executePendingBindings();
}
@Override
public int getItemCount() {
return mTestList == null ? 0 : mTestList.size();
}
public TestInfo getItemAt(int i) {
return mTestList.get(i);
}
static class TestInfoViewHolder extends RecyclerView.ViewHolder {
final TestItemBinding binding;
TestInfoViewHolder(TestItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
| 3,434 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestInfoClickCallback.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/TestInfoClickCallback.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.ui;
import org.akvo.caddisfly.model.TestInfo;
public interface TestInfoClickCallback {
void onClick(TestInfo testInfo);
}
| 1,527 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
NoticesDialogFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/NoticesDialogFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.ui;
import android.app.DialogFragment;
import android.app.Fragment;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import org.akvo.caddisfly.R;
/**
* A simple {@link Fragment} subclass.
*/
public class NoticesDialogFragment extends DialogFragment {
public static NoticesDialogFragment newInstance() {
return new NoticesDialogFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_notices_dialog, container, false);
makeEverythingClickable(view.findViewById(R.id.about_container));
return view;
}
private void makeEverythingClickable(ViewGroup vg) {
for (int i = 0; i < vg.getChildCount(); i++) {
if (vg.getChildAt(i) instanceof ViewGroup) {
makeEverythingClickable((ViewGroup) vg.getChildAt(i));
} else if (vg.getChildAt(i) instanceof TextView) {
TextView tv = (TextView) vg.getChildAt(i);
if (tv.getTag() != null && tv.getTag().equals("link")) {
tv.setLinkTextColor(getResources().getColor(R.color.links));
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
}
@Override
public void onResume() {
if (getDialog().getWindow() != null) {
WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
getDialog().getWindow().setAttributes(params);
}
super.onResume();
}
}
| 2,893 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Intro2Fragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/Intro2Fragment.java | /*
* Copyright (C) 2018 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Flow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.akvo.caddisfly.ui;
import android.graphics.drawable.ClipDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import org.akvo.caddisfly.R;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
public class Intro2Fragment extends Fragment {
public Intro2Fragment() {
}
public static Intro2Fragment newInstance() {
return new Intro2Fragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro_fragment_page2, container, false);
ImageView imageview = view.findViewById(R.id.main_icon);
ClipDrawable drawable = (ClipDrawable) imageview.getBackground();
drawable.setLevel(9000);
return view;
}
}
| 1,704 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AboutActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/AboutActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.ui;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.app.CaddisflyApp;
import org.akvo.caddisfly.databinding.ActivityAboutBinding;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.preference.SettingsActivity;
import org.akvo.caddisfly.util.PreferencesUtil;
import org.akvo.caddisfly.viewmodel.TestListViewModel;
import static org.akvo.caddisfly.common.AppConstants.TERMS_OF_USE_URL;
/**
* Activity to display info about the app.
*/
public class AboutActivity extends BaseActivity {
private static final int CHANGE_MODE_MIN_CLICKS = 10;
private int clickCount = 0;
private ActivityAboutBinding b;
private NoticesDialogFragment dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
b = DataBindingUtil.setContentView(this, R.layout.activity_about);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setTitle(R.string.about);
}
/**
* Displays legal information.
*/
public void onSoftwareNoticesClick(@SuppressWarnings("unused") View view) {
dialog = NoticesDialogFragment.newInstance();
dialog.show(getFragmentManager(), "NoticesDialog");
}
/**
* Disables diagnostic mode.
*/
public void disableDiagnosticsMode(@SuppressWarnings("unused") View view) {
Toast.makeText(getBaseContext(), getString(R.string.diagnosticModeDisabled),
Toast.LENGTH_SHORT).show();
AppPreferences.disableDiagnosticMode();
switchLayoutForDiagnosticOrUserMode();
changeActionBarStyleBasedOnCurrentMode();
clearTests();
}
private void clearTests() {
final TestListViewModel viewModel =
ViewModelProviders.of(this).get(TestListViewModel.class);
viewModel.clearTests();
}
/**
* Turn on diagnostic mode if user clicks on version section CHANGE_MODE_MIN_CLICKS times.
*/
public void switchToDiagnosticMode(@SuppressWarnings("unused") View view) {
if (!AppPreferences.isDiagnosticMode()) {
clickCount++;
if (clickCount >= CHANGE_MODE_MIN_CLICKS) {
clickCount = 0;
Toast.makeText(getBaseContext(), getString(
R.string.diagnosticModeEnabled), Toast.LENGTH_SHORT).show();
AppPreferences.enableDiagnosticMode();
changeActionBarStyleBasedOnCurrentMode();
switchLayoutForDiagnosticOrUserMode();
// clear and reload all the tests as diagnostic mode includes experimental tests
clearTests();
}
}
}
@Override
protected void onResume() {
super.onResume();
if (PreferencesUtil.getBoolean(this, R.string.refreshAboutKey, false)) {
PreferencesUtil.removeKey(this, R.string.refreshAboutKey);
this.recreate();
return;
}
switchLayoutForDiagnosticOrUserMode();
b.textVersion.setText(CaddisflyApp.getAppVersion(AppPreferences.isDiagnosticMode()));
}
/**
* Show the diagnostic mode layout.
*/
private void switchLayoutForDiagnosticOrUserMode() {
invalidateOptionsMenu();
if (AppPreferences.isDiagnosticMode()) {
findViewById(R.id.layoutDiagnostics).setVisibility(View.VISIBLE);
} else {
if (findViewById(R.id.layoutDiagnostics).getVisibility() == View.VISIBLE) {
findViewById(R.id.layoutDiagnostics).setVisibility(View.GONE);
}
}
b.textVersion.setText(CaddisflyApp.getAppVersion(AppPreferences.isDiagnosticMode()));
}
public void onSettingsClick(@SuppressWarnings("unused") MenuItem item) {
final Intent intent = new Intent(this, SettingsActivity.class);
startActivityForResult(intent, 100);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (AppPreferences.isDiagnosticMode()) {
getMenuInflater().inflate(R.menu.menu_main, menu);
}
return true;
}
public void onHomeClick(View view) {
if (dialog != null) {
dialog.dismiss();
}
}
public void onTermsOfServicesClick(View view) {
openUrl(this, TERMS_OF_USE_URL);
}
@SuppressWarnings("SameParameterValue")
private void openUrl(@NonNull Context context, String url) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(browserIntent);
}
}
| 5,789 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestListActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/TestListActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.ui;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import com.google.android.material.snackbar.Snackbar;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.databinding.ActivityTestListBinding;
import org.akvo.caddisfly.helper.ApkHelper;
import org.akvo.caddisfly.helper.ErrorMessages;
import org.akvo.caddisfly.helper.PermissionsDelegate;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.model.TestType;
import org.akvo.caddisfly.repository.TestConfigRepository;
import org.akvo.caddisfly.util.ApiUtil;
import org.akvo.caddisfly.viewmodel.TestListViewModel;
public class TestListActivity extends BaseActivity
implements TestListFragment.OnListFragmentInteractionListener {
private static final float SNACK_BAR_LINE_SPACING = 1.4f;
private final PermissionsDelegate permissionsDelegate = new PermissionsDelegate(this);
private TestInfo testInfo;
private ActivityTestListBinding b;
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissionsDelegate.resultGranted(grantResults)) {
startTest();
} else {
String message = getString(R.string.cameraAndStoragePermissions);
Snackbar snackbar = Snackbar
.make(b.mainLayout, message,
Snackbar.LENGTH_LONG)
.setAction("SETTINGS", view -> ApiUtil.startInstalledAppDetailsActivity(this));
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
snackbar.setActionTextColor(typedValue.data);
View snackView = snackbar.getView();
TextView textView = snackView.findViewById(R.id.snackbar_text);
textView.setHeight(getResources().getDimensionPixelSize(R.dimen.snackBarHeight));
textView.setLineSpacing(0, SNACK_BAR_LINE_SPACING);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
b = DataBindingUtil.setContentView(this, R.layout.activity_test_list);
setTitle(R.string.selectTest);
if (getIntent().getData() != null && ApkHelper.isNonStoreVersion(this)) {
String uuid = getIntent().getData().getQueryParameter("id");
if (uuid != null && !uuid.isEmpty()) {
final Intent intent = new Intent(getBaseContext(), TestActivity.class);
final TestListViewModel viewModel =
ViewModelProviders.of(this).get(TestListViewModel.class);
testInfo = viewModel.getTestInfo(uuid);
intent.putExtra(ConstantKey.TEST_INFO, testInfo);
startActivity(intent);
}
finish();
}
// Add list fragment if this is first creation
if (savedInstanceState == null) {
TestType testType = (TestType) getIntent().getSerializableExtra(ConstantKey.TYPE);
TestListFragment fragment = TestListFragment.newInstance(testType);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment, "TestListViewModel").commit();
}
}
/**
* Shows the detail fragment.
*/
private void navigateToTestDetails() {
startTest();
}
private void startTest() {
testInfo = (new TestConfigRepository()).getTestInfo(testInfo.getUuid());
if (testInfo == null || testInfo.getIsGroup()) {
return;
}
if (testInfo.getResults().size() == 0) {
ErrorMessages.alertCouldNotLoadConfig(this);
return;
}
Intent intent = new Intent(this, TestActivity.class);
intent.putExtra(ConstantKey.TEST_INFO, testInfo);
intent.putExtra("internal", true);
startActivity(intent);
}
@Override
public void onListFragmentInteraction(TestInfo testInfo) {
this.testInfo = testInfo;
navigateToTestDetails();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 5,723 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BaseFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/BaseFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.ui;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.jetbrains.annotations.NotNull;
public class BaseFragment extends Fragment {
private int id;
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
if (savedInstanceState != null) {
id = savedInstanceState.getInt(ConstantKey.FRAGMENT_ID);
}
super.onViewStateRestored(savedInstanceState);
}
@Override
public void onSaveInstanceState(@NotNull Bundle outState) {
outState.putInt(ConstantKey.FRAGMENT_ID, id);
super.onSaveInstanceState(outState);
}
protected void setTitle(View view, String title) {
if (getActivity() != null) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
if (toolbar != null) {
try {
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
} catch (Exception ignored) {
// do nothing
}
}
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
TextView textTitle = view.findViewById(R.id.textToolbarTitle);
if (textTitle != null) {
textTitle.setText(title);
}
}
}
}
public int getFragmentId() {
return id;
}
public void setFragmentId(int value) {
id = value;
}
}
| 2,730 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestListFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/TestListFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.ui;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.databinding.FragmentListBinding;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.model.TestType;
import org.akvo.caddisfly.viewmodel.TestListViewModel;
import java.util.List;
public class TestListFragment extends Fragment {
private FragmentListBinding b;
private OnListFragmentInteractionListener mListener;
private final TestInfoClickCallback mTestInfoClickCallback = test -> {
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
Runnable runnable = () -> mListener.onListFragmentInteraction(test);
(new Handler()).postDelayed(runnable, 100);
}
};
private TestType mTestType;
private TestInfoAdapter mTestInfoAdapter;
public static TestListFragment newInstance(TestType testType) {
TestListFragment fragment = new TestListFragment();
Bundle args = new Bundle();
args.putSerializable(ConstantKey.TYPE, testType);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
b = DataBindingUtil.inflate(inflater,
R.layout.fragment_list, container, false);
if (getArguments() != null) {
mTestType = (TestType) getArguments().get(ConstantKey.TYPE);
}
mTestInfoAdapter = new TestInfoAdapter(mTestInfoClickCallback);
if (getContext() != null) {
b.listTypes.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
}
b.listTypes.setHasFixedSize(true);
b.listTypes.setAdapter(mTestInfoAdapter);
return b.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadTests();
b.listTypes.setAdapter(mTestInfoAdapter);
}
private void loadTests() {
final TestListViewModel viewModel =
ViewModelProviders.of(this).get(TestListViewModel.class);
List<TestInfo> tests = viewModel.getTests(mTestType);
if (tests.size() == 1) {
mListener.onListFragmentInteraction(tests.get(0));
} else {
mTestInfoAdapter.setTestList(tests);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new IllegalArgumentException(context.toString()
+ " must implement OnCalibrationSelectedListener");
}
}
void refresh() {
loadTests();
mTestInfoAdapter.notifyDataSetChanged();
b.listTypes.getAdapter().notifyDataSetChanged();
b.listTypes.invalidate();
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction(TestInfo testInfo);
}
}
| 4,553 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestInfoFragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/TestInfoFragment.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.akvo.caddisfly.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.ConstantKey;
import org.akvo.caddisfly.databinding.FragmentTestDetailBinding;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.model.TestType;
import org.akvo.caddisfly.preference.AppPreferences;
import org.akvo.caddisfly.viewmodel.TestInfoViewModel;
public class TestInfoFragment extends Fragment {
/**
* Creates test fragment for specific test.
*/
public static TestInfoFragment getInstance(TestInfo testInfo) {
TestInfoFragment fragment = new TestInfoFragment();
Bundle args = new Bundle();
args.putParcelable(ConstantKey.TEST_INFO, testInfo);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
// Inflate this data b layout
FragmentTestDetailBinding b = DataBindingUtil.inflate(inflater,
R.layout.fragment_test_detail, container, false);
final TestInfoViewModel model =
ViewModelProviders.of(this).get(TestInfoViewModel.class);
if (getArguments() != null) {
TestInfo testInfo = getArguments().getParcelable(ConstantKey.TEST_INFO);
if (testInfo != null) {
if (AppPreferences.isDiagnosticMode()) {
b.swatchView.setVisibility(View.VISIBLE);
b.swatchView.setTestInfo(testInfo);
}
model.setTest(testInfo);
b.setTestInfoViewModel(model);
b.setTestInfo(testInfo);
b.layoutPrepareSubmit.setVisibility(View.GONE);
b.layoutNext.setVisibility(View.VISIBLE);
if (testInfo.getSubtype() == TestType.STRIP_TEST) {
b.buttonNext.setText(R.string.prepare_test);
} else if (testInfo.getSubtype() == TestType.CBT) {
b.layoutPrepareSubmit.setVisibility(View.VISIBLE);
b.layoutNext.setVisibility(View.GONE);
}
}
}
return b.getRoot();
}
}
| 3,971 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
BaseActivity.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/BaseActivity.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.ui;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.preference.AppPreferences;
/**
* The base activity with common functions.
*/
public abstract class BaseActivity extends AppCompatActivity {
private String mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateTheme();
changeActionBarStyleBasedOnCurrentMode();
}
private void updateTheme() {
setTheme(R.style.AppTheme_Main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
try {
setSupportActionBar(toolbar);
} catch (Exception ignored) {
// do nothing
}
}
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
}
}
@Override
protected void onResume() {
super.onResume();
changeActionBarStyleBasedOnCurrentMode();
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("");
}
setTitle(mTitle);
}
@Override
public void setTitle(CharSequence title) {
TextView textTitle = findViewById(R.id.textToolbarTitle);
if (textTitle != null && title != null) {
mTitle = title.toString();
textTitle.setText(title);
}
}
@Override
public void setTitle(int titleId) {
TextView textTitle = findViewById(R.id.textToolbarTitle);
if (textTitle != null && titleId != 0) {
mTitle = getString(titleId);
textTitle.setText(titleId);
}
}
/**
* Changes the action bar style depending on if the app is in user mode or diagnostic mode
* This serves as a visual indication as to what mode the app is running in.
*/
protected void changeActionBarStyleBasedOnCurrentMode() {
invalidateOptionsMenu();
if (AppPreferences.isDiagnosticMode()) {
if (getSupportActionBar() != null) {
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(
ContextCompat.getColor(this, R.color.diagnostic)));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.diagnostic_status));
}
LinearLayout layoutTitle = findViewById(R.id.layoutTitleBar);
if (layoutTitle != null) {
layoutTitle.setBackgroundColor(ContextCompat.getColor(this, R.color.diagnostic));
}
} else {
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int color = typedValue.data;
if (getSupportActionBar() != null) {
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
}
LinearLayout layoutTitle = findViewById(R.id.layoutTitleBar);
if (layoutTitle != null) {
layoutTitle.setBackgroundColor(color);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
color = typedValue.data;
getWindow().setStatusBarColor(color);
}
}
}
}
| 4,971 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Intro1Fragment.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/ui/Intro1Fragment.java | /*
* Copyright (C) 2018 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Flow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.akvo.caddisfly.ui;
import android.graphics.drawable.ClipDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import org.akvo.caddisfly.R;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
public class Intro1Fragment extends Fragment {
public Intro1Fragment() {
}
public static Intro1Fragment newInstance() {
return new Intro1Fragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro_fragment_page1, container, false);
ImageView imageview = view.findViewById(R.id.main_icon);
ClipDrawable drawable = (ClipDrawable) imageview.getBackground();
drawable.setLevel(9000);
return view;
}
}
| 1,704 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TimerView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/TimerView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.sensor.striptest.utils.Constants;
/**
* Countdown timer view.
* based on: https://github.com/maxwellforest/blog_android_timer
*/
public class TimerView extends View {
private static final int BACKGROUND_COLOR = Color.argb(120, 180, 180, 200);
private static final int ERASES_COLOR = Color.argb(180, 40, 40, 40);
private static final int FINISH_ARC_COLOR = Color.argb(255, 0, 245, 120);
private static final int ARC_START_ANGLE = 270; // 12 o'clock
private static final float THICKNESS_SCALE = 0.1f;
@NonNull
private final Paint mCirclePaint;
@NonNull
private final Paint mArcPaint;
private final Rect rectangle = new Rect();
@NonNull
private final Paint mEraserPaint;
@NonNull
private final Paint mTextPaint;
private final Paint mCircleBackgroundPaint;
private final Paint mSubTextPaint;
private Bitmap mBitmap;
private Canvas mCanvas;
private RectF mCircleOuterBounds;
private RectF mCircleInnerBounds;
private float mCircleSweepAngle = -1;
private float mCircleFinishAngle = -1;
private float mProgress;
public TimerView(@NonNull Context context) {
this(context, null);
}
public TimerView(@NonNull Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
int circleColor = Color.RED;
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TimerView);
if (ta != null) {
circleColor = ta.getColor(R.styleable.TimerView_circleColor, circleColor);
ta.recycle();
}
}
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(Color.WHITE);
Typeface typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
mTextPaint.setTypeface(typeface);
mTextPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.progressTextSize));
mSubTextPaint = new Paint();
mSubTextPaint.setAntiAlias(true);
mSubTextPaint.setColor(Color.LTGRAY);
Typeface subTypeface = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
mSubTextPaint.setTypeface(subTypeface);
mSubTextPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.progressSubTextSize));
mCircleBackgroundPaint = new Paint();
mCircleBackgroundPaint.setAntiAlias(true);
mCircleBackgroundPaint.setColor(BACKGROUND_COLOR);
mCirclePaint = new Paint();
mCirclePaint.setAntiAlias(true);
mCirclePaint.setColor(circleColor);
mArcPaint = new Paint();
mArcPaint.setAntiAlias(true);
mArcPaint.setColor(FINISH_ARC_COLOR);
mEraserPaint = new Paint();
mEraserPaint.setAntiAlias(true);
mEraserPaint.setColor(ERASES_COLOR);
}
@SuppressWarnings("SuspiciousNameCombination")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec); // Trick to make the view square
}
@Override
protected void onSizeChanged(int w, int h, int oldWidth, int oldHeight) {
if (w != oldWidth || h != oldHeight) {
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mBitmap.eraseColor(Color.TRANSPARENT);
mCanvas = new Canvas(mBitmap);
}
super.onSizeChanged(w, h, oldWidth, oldHeight);
updateBounds();
}
@Override
protected void onDraw(@NonNull Canvas canvas) {
mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
if (mCircleSweepAngle > -1) {
String text = String.valueOf((int) mProgress);
mTextPaint.getTextBounds(text, 0, text.length(), rectangle);
mCanvas.drawArc(mCircleOuterBounds, ARC_START_ANGLE, 360, true, mCircleBackgroundPaint);
if (mCircleSweepAngle > mCircleFinishAngle) {
mCanvas.drawArc(mCircleOuterBounds, ARC_START_ANGLE, mCircleSweepAngle, true, mCirclePaint);
mCanvas.drawArc(mCircleOuterBounds, ARC_START_ANGLE, mCircleFinishAngle, true, mArcPaint);
} else {
mCanvas.drawArc(mCircleOuterBounds, ARC_START_ANGLE, mCircleSweepAngle, true, mArcPaint);
}
mCanvas.drawOval(mCircleInnerBounds, mEraserPaint);
float width = mTextPaint.measureText(text);
mCanvas.drawText(text, (getWidth() - width) / 2f,
((getHeight() + Math.abs(rectangle.height())) / 2f) - 10, mTextPaint);
int mainTextHeight = rectangle.height();
String subText = getContext().getString(R.string.seconds);
width = mSubTextPaint.measureText(subText);
mSubTextPaint.getTextBounds(subText, 0, subText.length(), rectangle);
mCanvas.drawText(subText, (getWidth() - width) / 2f,
((getHeight() + Math.abs(rectangle.height())) / 2f) + mainTextHeight - 10, mSubTextPaint);
}
canvas.drawBitmap(mBitmap, 0, 0, null);
}
public void setProgress(int progress, int max) {
mProgress = progress;
drawProgress(progress, max);
}
private void drawProgress(float progress, float max) {
mCircleSweepAngle = (progress * 360) / max;
mCircleFinishAngle = (Constants.GET_READY_SECONDS * 360) / max;
invalidate();
}
private void updateBounds() {
final float thickness = getWidth() * THICKNESS_SCALE;
mCircleOuterBounds = new RectF(0, 0, getWidth(), getHeight());
mCircleInnerBounds = new RectF(
mCircleOuterBounds.left + thickness,
mCircleOuterBounds.top + thickness,
mCircleOuterBounds.right - thickness,
mCircleOuterBounds.bottom - thickness);
invalidate();
}
}
| 7,338 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SwipeDirection.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/SwipeDirection.java | package org.akvo.caddisfly.widget;
public enum SwipeDirection {
all, left, right, none
} | 93 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CircleView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/CircleView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
public class CircleView extends View {
private static final int RADIUS = 40;
@NonNull
private final Paint circlePaint;
public CircleView(Context context) {
this(context, null);
}
public CircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setColor(Color.YELLOW);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeWidth(5);
}
@Override
protected void onDraw(@NonNull Canvas canvas) {
int w = getWidth();
int h = getHeight();
canvas.drawCircle(w / 2f, h / 2f, RADIUS, circlePaint);
super.onDraw(canvas);
}
}
| 1,873 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ButtonType.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/ButtonType.java | package org.akvo.caddisfly.widget;
public enum ButtonType {
NONE,
START,
SUBMIT,
CLOSE
}
| 106 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
WrapContentViewPager.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/WrapContentViewPager.java | package org.akvo.caddisfly.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
public class WrapContentViewPager extends ViewPager {
public WrapContentViewPager(Context context) {
super(context);
}
public WrapContentViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) height = h;
}
heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (Exception ignored) {
}
}
} | 1,099 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
RowView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/RowView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.widget;
import android.content.Context;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.akvo.caddisfly.R;
/**
* A single numbered row for a list.
*/
public class RowView extends TableRow {
private final TextView textNumber;
private final TextView textPara;
/**
* A single numbered row for a list.
*
* @param context the context
* @param attrs the attributeSet
*/
public RowView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(LinearLayout.HORIZONTAL);
setGravity(Gravity.CENTER_VERTICAL);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (inflater != null) {
inflater.inflate(R.layout.row_view, this, true);
}
TableRow tableRow = (TableRow) getChildAt(0);
textNumber = (TextView) tableRow.getChildAt(0);
textPara = (TextView) tableRow.getChildAt(1);
}
public RowView(Context context) {
this(context, null);
}
public void setNumber(String s) {
textNumber.setText(s);
}
public void append(Spanned s) {
textPara.append(s);
}
public String getString() {
return textPara.getText().toString();
}
public void enableLinks(boolean b) {
textPara.setMovementMethod(LinkMovementMethod.getInstance());
}
}
| 2,439 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
HtmlTextView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/HtmlTextView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.widget;
import android.content.Context;
import android.util.AttributeSet;
import org.akvo.caddisfly.util.StringUtil;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
public class HtmlTextView extends AppCompatTextView {
public HtmlTextView(Context context) {
super(context);
init(context);
}
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
setText(StringUtil.toInstruction((AppCompatActivity) context, null, getText().toString()));
}
}
| 1,586 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SwatchView.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/SwatchView.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import org.akvo.caddisfly.model.ColorItem;
import org.akvo.caddisfly.model.GroupType;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.sensor.striptest.utils.ColorUtils;
import java.util.List;
import static org.akvo.caddisfly.sensor.striptest.utils.ResultUtils.createValueString;
/**
* Displays the swatches for the calibrated colors of the test.
*/
public class SwatchView extends View {
private static final int VAL_BAR_HEIGHT = 15;
private static final int TEXT_SIZE = 20;
private static final float MARGIN = 10;
private static float gutterSize = 5;
private float blockWidth = 0;
private float lineHeight = 0;
private final Paint paintColor;
private final float[] lab = new float[3];
private int lineCount = 0;
private int extraHeight = 0;
private float totalWidth = 0;
private TestInfo testInfo;
private final Paint blackText;
/**
* Displays the swatches for the calibrated colors of the test.
*
* @param context the context
* @param attrs the attribute set
*/
public SwatchView(Context context, AttributeSet attrs) {
super(context, attrs);
blackText = new Paint();
blackText.setColor(Color.BLACK);
blackText.setTextSize(TEXT_SIZE);
blackText.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
blackText.setTextAlign(Paint.Align.CENTER);
paintColor = new Paint();
paintColor.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (testInfo != null) {
int index = -1;
for (int resultIndex = 0; resultIndex < testInfo.getResults().size(); resultIndex++) {
List<ColorItem> colors = testInfo.getResults().get(resultIndex).getColors();
if (colors.size() > 0) {
index += 1;
int colorCount = colors.size();
for (int i = 0; i < colorCount; i++) {
ColorItem colorItem = colors.get(i);
if (colorItem != null) {
paintColor.setColor(colorItem.getRgb());
canvas.drawRect(MARGIN + (i * totalWidth), MARGIN + (index * lineHeight),
i * totalWidth + blockWidth, (index * lineHeight) + blockWidth, paintColor);
if (testInfo.getGroupingType() == GroupType.INDIVIDUAL
|| index == testInfo.getResults().size() - 1) {
canvas.drawText(createValueString(colorItem.getValue().floatValue()),
MARGIN + (i * totalWidth + blockWidth / 2),
MARGIN + (index * lineHeight) + blockWidth + VAL_BAR_HEIGHT, blackText);
}
}
}
}
}
}
}
/**
* Set the test for which the swatches should be displayed.
*
* @param testInfo the test
*/
public void setTestInfo(TestInfo testInfo) {
this.testInfo = testInfo;
if (testInfo.getGroupingType() == GroupType.GROUP) {
gutterSize = 1;
extraHeight = 40;
}
lineCount = 0;
for (int resultIndex = 0; resultIndex < testInfo.getResults().size(); resultIndex++) {
List<ColorItem> colors = testInfo.getResults().get(resultIndex).getColors();
if (colors != null && colors.size() > 0) {
lineCount += 1;
int colorCount = colors.size();
int[][] rgbCols = new int[colorCount][3];
// get lab colours and turn them to RGB
for (int i = 0; i < colorCount; i++) {
List<Double> patchColorValues = colors.get(i).getLab();
if (patchColorValues != null) {
lab[0] = patchColorValues.get(0).floatValue();
lab[1] = patchColorValues.get(1).floatValue();
lab[2] = patchColorValues.get(2).floatValue();
rgbCols[i] = ColorUtils.xyzToRgbInt(ColorUtils.Lab2XYZ(lab));
int color = Color.rgb(rgbCols[i][0], rgbCols[i][1], rgbCols[i][2]);
colors.get(i).setRgb(color);
}
}
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
if (getMeasuredWidth() != 0 && getMeasuredHeight() != 0) {
float width = getMeasuredWidth() - (MARGIN * 2);
if (testInfo != null) {
for (int resultIndex = 0; resultIndex < testInfo.getResults().size(); resultIndex++) {
List<ColorItem> colors = testInfo.getResults().get(resultIndex).getColors();
if (colors != null && colors.size() > 0) {
float colorCount = colors.size();
if (blockWidth == 0) {
blockWidth = (width - (colorCount - 4) * gutterSize) / colorCount;
if (testInfo.getGroupingType() == GroupType.GROUP) {
lineHeight = blockWidth + (VAL_BAR_HEIGHT / 3f);
} else {
lineHeight = blockWidth + VAL_BAR_HEIGHT + VAL_BAR_HEIGHT;
}
}
}
}
}
totalWidth = gutterSize + blockWidth;
}
super.onMeasure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec((int) ((lineCount * lineHeight) + extraHeight), MeasureSpec.EXACTLY));
}
} | 6,984 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CenteredImageSpan.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/widget/CenteredImageSpan.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.WeakReference;
//ref: https://stackoverflow.com/questions/25628258/align-text-around-imagespan-center-vertical
public class CenteredImageSpan extends ImageSpan {
private WeakReference<Drawable> mDrawableRef;
public CenteredImageSpan(Context context, final int drawableRes) {
super(context, drawableRes);
}
@Override
public int getSize(@NotNull Paint paint, CharSequence text,
int start, int end,
Paint.FontMetricsInt fontMetricsInt) {
Drawable d = getCachedDrawable();
Rect rect = d.getBounds();
if (fontMetricsInt != null) {
Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
int fontHeight = fmPaint.descent - fmPaint.ascent;
int drHeight = rect.bottom - rect.top;
int centerY = fmPaint.ascent + fontHeight / 2;
fontMetricsInt.ascent = centerY - drHeight / 2;
fontMetricsInt.top = fontMetricsInt.ascent;
fontMetricsInt.bottom = centerY + drHeight / 2;
fontMetricsInt.descent = fontMetricsInt.bottom;
}
return rect.right;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start,
int end, float x, int top, int y, int bottom,
Paint paint) {
Drawable drawable = getCachedDrawable();
canvas.save();
Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
int fontHeight = fmPaint.descent - fmPaint.ascent;
int centerY = y + fmPaint.descent - fontHeight / 2;
int transY = centerY - (drawable.getBounds().bottom - drawable.getBounds().top) / 2;
canvas.translate(x, transY);
drawable.draw(canvas);
canvas.restore();
}
// Redefined locally because it is a private member from DynamicDrawableSpan
private Drawable getCachedDrawable() {
WeakReference<Drawable> wr = mDrawableRef;
Drawable d = null;
if (wr != null) {
d = wr.get();
}
if (d == null) {
d = getDrawable();
mDrawableRef = new WeakReference<>(d);
}
return d;
}
}
| 3,255 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
SoundPoolPlayer.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/SoundPoolPlayer.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.SparseIntArray;
import androidx.annotation.RawRes;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.common.AppConfig;
import org.akvo.caddisfly.preference.AppPreferences;
/**
* Manages various sounds used in the app.
*/
public class SoundPoolPlayer {
private final SparseIntArray mSounds = new SparseIntArray();
private final Context mContext;
private SoundPool mPlayer = null;
public SoundPoolPlayer(Context context) {
mContext = context;
setupPlayer(mContext);
}
private void setupPlayer(Context context) {
//noinspection
mPlayer = new SoundPool(4, AudioManager.STREAM_ALARM, 0);
//low beep sound
mSounds.put(R.raw.futurebeep2, this.mPlayer.load(context, R.raw.futurebeep2, 1));
}
/**
* Play a short sound effect.
*
* @param resourceId the
*/
public void playShortResource(@RawRes int resourceId) {
if (mPlayer == null) {
setupPlayer(mContext);
}
//play sound if the sound is not turned off in the preference
if (AppPreferences.isSoundOn()) {
mPlayer.play(mSounds.get(resourceId), AppConfig.SOUND_EFFECTS_VOLUME,
AppConfig.SOUND_EFFECTS_VOLUME, 0, 0, 1);
}
}
public void release() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
| 2,317 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ErrorMessages.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/ErrorMessages.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import android.app.Activity;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.AlertUtil;
public class ErrorMessages {
private static final String MESSAGE_TWO_LINE_FORMAT = "%s%n%n%s";
private static final String TWO_SENTENCE_FORMAT = "%s%n%n%s";
/**
* Error message for feature not supported by the device.
*/
public static void alertFeatureNotSupported(Activity activity, boolean finishOnDismiss) {
String message = String.format(MESSAGE_TWO_LINE_FORMAT, activity.getString(R.string.phoneDoesNotSupport),
activity.getString(R.string.pleaseContactSupport));
AlertUtil.showAlert(activity, R.string.notSupported, message,
R.string.ok,
(dialogInterface, i) -> {
dialogInterface.dismiss();
if (finishOnDismiss) {
activity.finish();
}
}, null,
dialogInterface -> {
dialogInterface.dismiss();
if (finishOnDismiss) {
activity.finish();
}
}
);
}
/**
* Error message for configuration not loading correctly.
*/
public static void alertCouldNotLoadConfig(Activity activity) {
String message = String.format(TWO_SENTENCE_FORMAT,
activity.getString(R.string.errorLoadingConfiguration),
activity.getString(R.string.pleaseContactSupport));
AlertUtil.showError(activity, R.string.error, message, null, R.string.ok,
(dialogInterface, i) -> dialogInterface.dismiss(), null, null);
}
}
| 2,480 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CameraHelper.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/CameraHelper.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import android.content.Context;
import android.hardware.Camera;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.util.ApiUtil;
import org.akvo.caddisfly.util.PreferencesUtil;
import timber.log.Timber;
public final class CameraHelper {
private static final float ONE_MILLION = 1000000f;
private CameraHelper() {
}
public static int getMaxSupportedMegaPixelsByCamera(Context context) {
int cameraMegaPixels = 0;
if (PreferencesUtil.containsKey(context, R.string.cameraMegaPixelsKey)) {
cameraMegaPixels = PreferencesUtil.getInt(context, R.string.cameraMegaPixelsKey, 0);
} else {
Camera camera = ApiUtil.getCameraInstance();
try {
// make sure the camera is not in use
if (camera != null) {
Camera.Parameters allParams = camera.getParameters();
for (Camera.Size pictureSize : allParams.getSupportedPictureSizes()) {
int sizeInMegaPixel = (int) Math.ceil((pictureSize.width * pictureSize.height) / ONE_MILLION);
if (sizeInMegaPixel > cameraMegaPixels) {
cameraMegaPixels = sizeInMegaPixel;
}
}
}
PreferencesUtil.setInt(context, R.string.cameraMegaPixelsKey, cameraMegaPixels);
} catch (Exception e) {
Timber.e(e);
} finally {
if (camera != null) {
camera.release();
}
}
}
return cameraMegaPixels;
}
}
| 2,431 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ApkHelper.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/ApkHelper.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import org.akvo.caddisfly.BuildConfig;
import org.akvo.caddisfly.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Installation related utility methods.
*/
public final class ApkHelper {
private ApkHelper() {
}
/**
* Checks if app version has expired and if so displays an expiry message and closes activity.
*
* @param activity The activity
* @return True if the app has expired
*/
public static boolean isAppVersionExpired(@NonNull final Activity activity) {
//noinspection ConstantConditions
if (BuildConfig.BUILD_TYPE.equalsIgnoreCase("release") &&
isNonStoreVersion(activity)) {
final Uri marketUrl = Uri.parse("https://play.google.com/store/apps/details?id=" +
activity.getPackageName());
final Calendar appExpiryDate = GregorianCalendar.getInstance();
appExpiryDate.setTime(BuildConfig.BUILD_TIME);
appExpiryDate.add(Calendar.DAY_OF_YEAR, 15);
if ((new GregorianCalendar()).after(appExpiryDate)) {
String message = String.format("%s%n%n%s", activity.getString(R.string.thisVersionHasExpired),
activity.getString(R.string.uninstallAndInstallFromStore));
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.versionExpired)
.setMessage(message)
.setCancelable(false);
builder.setPositiveButton(R.string.ok, (dialogInterface, i) -> {
dialogInterface.dismiss();
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(marketUrl);
intent.setPackage("com.android.vending");
activity.startActivity(intent);
} catch (Exception ignore) {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.finishAndRemoveTask();
} else {
activity.finish();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
}
}
return false;
}
/**
* Checks if the app was installed from the app store or from an install file.
* source: http://stackoverflow.com/questions/37539949/detect-if-an-app-is-installed-from-play-store
*
* @param context The context
* @return True if app was not installed from the store
*/
public static boolean isNonStoreVersion(@NonNull Context context) {
// Valid installer package names
List<String> validInstallers = new ArrayList<>(
Arrays.asList("com.android.vending", "com.google.android.feedback"));
try {
// The package name of the app that has installed the app
final String installer = context.getPackageManager().getInstallerPackageName(context.getPackageName());
// true if the app has been downloaded from Play Store
return installer == null || !validInstallers.contains(installer);
} catch (Exception ignored) {
// do nothing
}
return true;
}
}
| 4,540 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestConfigHelper.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/TestConfigHelper.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import android.content.Context;
import android.graphics.Color;
import android.util.SparseArray;
import org.akvo.caddisfly.app.CaddisflyApp;
import org.akvo.caddisfly.common.ConstantJsonKey;
import org.akvo.caddisfly.common.Constants;
import org.akvo.caddisfly.common.SensorConstants;
import org.akvo.caddisfly.model.GroupType;
import org.akvo.caddisfly.model.MpnValue;
import org.akvo.caddisfly.model.Result;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.util.AssetsManager;
import org.akvo.caddisfly.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import timber.log.Timber;
import static org.akvo.caddisfly.common.Constants.MPN_TABLE_FILENAME;
import static org.akvo.caddisfly.common.Constants.MPN_TABLE_FILENAME_AGRICULTURE;
/**
* Utility functions to parse a text config json text.
*/
public final class TestConfigHelper {
private TestConfigHelper() {
}
/**
* Get the most probable number for the key.
*/
public static MpnValue getMpnValueForKey(String key, String sampleQuantity) {
String fileName = MPN_TABLE_FILENAME;
if (sampleQuantity.equals("10")) {
fileName = MPN_TABLE_FILENAME_AGRICULTURE;
}
HashMap<String, MpnValue> mpnTable = loadMpnTable(fileName);
MpnValue mpnValue = mpnTable.get(key.replace("2", "1"));
populateDisplayColors(mpnValue, fileName);
return mpnValue;
}
private static void populateDisplayColors(MpnValue mpnValue, String fileName) {
String jsonText = AssetsManager.getInstance().loadJsonFromAsset(fileName);
try {
JSONArray array = new JSONObject(jsonText).getJSONArray("displayColors");
for (int j = array.length() - 1; j >= 0; j--) {
JSONObject item = array.getJSONObject(j);
int threshold = item.getInt("threshold");
if (mpnValue.getConfidence() > threshold) {
mpnValue.setBackgroundColor1(Color.parseColor(item.getString("background1")));
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private static HashMap<String, MpnValue> loadMpnTable(String mpnTableFilename) {
HashMap<String, MpnValue> mapper = new HashMap<>();
String jsonText = AssetsManager.getInstance().loadJsonFromAsset(mpnTableFilename);
try {
JSONArray array = new JSONObject(jsonText).getJSONArray("rows");
for (int j = 0; j < array.length(); j++) {
JSONObject item = array.getJSONObject(j);
String key = item.getString("key");
mapper.put(key, new MpnValue(item.getString("mpn"), item.getDouble("confidence"),
item.getString("riskCategory")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return mapper;
}
/**
* Creates the json result containing the results for test.
*
* @param testInfo information about the test
* @param results the results for the test
* @param resultImageUrl the url of the image
* @return the result in json format
*/
public static JSONObject getJsonResult(Context context, TestInfo testInfo, SparseArray<String> results,
SparseArray<String> brackets, String resultImageUrl) {
JSONObject resultJson = new JSONObject();
try {
resultJson.put(ConstantJsonKey.TYPE, SensorConstants.TYPE_NAME);
resultJson.put(ConstantJsonKey.NAME, testInfo.getName());
resultJson.put(ConstantJsonKey.UUID, testInfo.getUuid());
JSONArray resultsJsonArray = new JSONArray();
for (Result subTest : testInfo.getResults()) {
JSONObject subTestJson = new JSONObject();
String subTestName = subTest.getName();
if (subTestName.contains("string:")) {
subTestName = subTestName.replace("string:", "");
subTestName = StringUtil.getStringResourceByName(context, subTestName).toString();
}
subTestJson.put(ConstantJsonKey.NAME, subTestName);
subTestJson.put(ConstantJsonKey.UNIT, subTest.getUnit());
subTestJson.put(ConstantJsonKey.ID, subTest.getId());
// If a result exists for the sub test id then add it
int id = subTest.getId();
if (results.size() >= id) {
subTestJson.put(ConstantJsonKey.VALUE, results.get(id));
// if there is a bracket result, include it.
if (brackets != null && brackets.get(id) != null) {
subTestJson.put(ConstantJsonKey.BRACKET, brackets.get(id));
}
}
resultsJsonArray.put(subTestJson);
if (testInfo.getGroupingType() == GroupType.GROUP) {
break;
}
}
resultJson.put(ConstantJsonKey.RESULT, resultsJsonArray);
if (resultImageUrl != null && !resultImageUrl.isEmpty()) {
resultJson.put(ConstantJsonKey.IMAGE, resultImageUrl);
}
// Add current date to result
resultJson.put(ConstantJsonKey.TEST_DATE, new SimpleDateFormat(Constants.DATE_TIME_FORMAT, Locale.US)
.format(Calendar.getInstance().getTime()));
// Add app details to the result
resultJson.put(ConstantJsonKey.APP, TestConfigHelper.getAppDetails());
} catch (JSONException e) {
Timber.e(e);
}
return resultJson;
}
private static JSONObject getAppDetails() throws JSONException {
JSONObject details = new JSONObject();
details.put("appVersion", CaddisflyApp.getAppVersion(true));
return details;
}
}
| 6,955 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
InstructionHelper.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/InstructionHelper.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import org.akvo.caddisfly.model.Instruction;
import org.akvo.caddisfly.model.PageIndex;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Installation related utility methods.
*/
public final class InstructionHelper {
private InstructionHelper() {
}
public static int setupInstructions(List<Instruction> testInstructions,
ArrayList<Instruction> instructions,
PageIndex pageIndex, boolean skip) {
int instructionIndex = 1;
int subSequenceIndex;
instructions.clear();
pageIndex.clear();
int index = 0;
String[] subSequenceNumbers = {"i", "ii", "iii"};
boolean alphaSequence = false;
for (int i = 0; i < testInstructions.size(); i++) {
Instruction instruction;
try {
instruction = testInstructions.get(i).clone();
if (instruction != null) {
List<String> section = instruction.section;
boolean indent = false;
subSequenceIndex = 0;
boolean leaveOut = false;
if (skip) {
for (int i1 = 0; i1 < section.size(); i1++) {
String item = section.get(i1);
if (item.contains("~skippable~")) {
leaveOut = true;
}
}
}
if (leaveOut) {
continue;
}
instruction.setIndex(instructionIndex);
for (int i1 = 0; i1 < section.size(); i1++) {
String item = section.get(i1);
if (item.contains("~photo~")) {
pageIndex.setPhotoIndex(index);
if (pageIndex.getSkipToIndex() < 0) {
pageIndex.setSkipToIndex(index);
} else if (pageIndex.getSkipToIndex2() < 0) {
pageIndex.setSkipToIndex2(index);
}
} else if (item.contains("~input~")) {
pageIndex.setInputIndex(index);
if (pageIndex.getSkipToIndex() < 0) {
pageIndex.setSkipToIndex(index);
}
} else if (item.contains("~result~")) {
pageIndex.setResultIndex(index);
}
Matcher m = Pattern.compile("^(\\d+?\\.\\s*)(.*)").matcher(item);
Matcher m1 = Pattern.compile("^([a-zA-Z]\\.\\s*)(.*)").matcher(item);
if (subSequenceIndex > 0 || item.startsWith("i.")) {
section.set(i1, subSequenceNumbers[subSequenceIndex] + ". " +
item.replace("i.", ""));
subSequenceIndex++;
indent = true;
} else if (m1.find()) {
section.set(i1, instructionIndex + item);
alphaSequence = true;
indent = true;
} else {
if (alphaSequence) {
instructionIndex++;
alphaSequence = false;
} else if (m.find()) {
section.set(i1, item);
} else if (item.startsWith("stage")) {
section.set(i1, item);
indent = true;
} else if (item.startsWith("~")) {
section.set(i1, item);
} else if (item.startsWith("/")) {
if (item.startsWith("/-")) {
section.set(i1, item.substring(2));
} else if (indent) {
section.set(i1, "." + item.substring(1));
} else {
section.set(i1, item.substring(1));
}
} else if (!item.startsWith(".") && !item.startsWith("image:")) {
section.set(i1, instructionIndex + ". " + item);
instructionIndex++;
indent = true;
}
}
}
}
index++;
instructions.add(instruction);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
if (pageIndex.getSkipToIndex() < 0) {
pageIndex.setSkipToIndex(testInstructions.size());
}
return instructionIndex;
}
}
| 5,986 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PermissionsDelegate.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/helper/PermissionsDelegate.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.helper;
import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class PermissionsDelegate {
private static final int REQUEST_CODE = 100;
private final Activity activity;
public PermissionsDelegate(Activity activity) {
this.activity = activity;
}
public boolean hasPermissions(String[] permissions) {
for (String permission :
permissions) {
int permissionCheckResult = ContextCompat.checkSelfPermission(
activity, permission
);
if (permissionCheckResult != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
public void requestPermissions(String[] permissions) {
ActivityCompat.requestPermissions(
activity,
permissions,
REQUEST_CODE
);
}
public void requestPermissions(String[] permissions, int requestCode) {
ActivityCompat.requestPermissions(
activity,
permissions,
requestCode
);
}
public boolean resultGranted(int[] grantResults) {
if (grantResults.length < 1) {
return false;
}
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
public boolean resultGranted(int requestCode, int[] grantResults) {
if (requestCode != REQUEST_CODE) {
return false;
}
if (grantResults.length < 1) {
return false;
}
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
}
| 2,740 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
CaddisflyApp.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/app/CaddisflyApp.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.app;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import org.akvo.caddisfly.BuildConfig;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.di.DaggerAppComponent;
import org.akvo.caddisfly.logging.SentryTree;
import org.akvo.caddisfly.util.PreferencesUtil;
import java.util.Arrays;
import java.util.Locale;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import io.sentry.Sentry;
import io.sentry.android.AndroidSentryClientFactory;
import timber.log.Timber;
public class CaddisflyApp extends DaggerApplication {
private static CaddisflyApp app; // Singleton
/**
* Gets the singleton app object.
*
* @return the singleton app
*/
public static CaddisflyApp getApp() {
return app;
}
private static void setApp(CaddisflyApp value) {
app = value;
}
/**
* Gets the app version.
*
* @return The version name and number
*/
public static String getAppVersion(boolean isDiagnostic) {
String version = "";
try {
Context context = getApp();
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
if (isDiagnostic) {
version = String.format("%s (Build %s)", packageInfo.versionName, packageInfo.versionCode);
} else {
version = String.format("%s %s", context.getString(R.string.version),
packageInfo.versionName);
}
} catch (PackageManager.NameNotFoundException ignored) {
// do nothing
}
return version;
}
// https://stackoverflow.com/a/52164101
@SuppressWarnings("SameParameterValue")
private static String decrypt(String str) {
str = str.replace("-", "");
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i += 3) {
String hex = str.substring(i + 1, i + 3);
result.append((char) (Integer.parseInt(hex, 16) ^ (Integer.parseInt(String.valueOf(str.charAt(i))))));
}
return result.toString();
}
@Override
public void onCreate() {
super.onCreate();
setApp(this);
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
} else {
String sentryDsn = decrypt(BuildConfig.SENTRY_DSN);
if (!sentryDsn.isEmpty()) {
Sentry.init(sentryDsn, new AndroidSentryClientFactory(getApplicationContext()));
}
Timber.plant(new SentryTree());
}
app = this;
}
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent.factory().create(this);
}
/**
* Sets the language of the app on start. The language can be one of system language, language
* set in the app preferences or language requested via the languageCode parameter
*
* @param languageCode If null uses language from app preferences else uses this value
*/
public void setAppLanguage(Context context, String languageCode, boolean isExternal, Handler handler) {
try {
Locale locale;
String code = languageCode;
//the languages supported by the app
String[] supportedLanguages = getResources().getStringArray(R.array.language_codes);
//the current system language set in the device settings
String currentSystemLanguage = Locale.getDefault().getLanguage().substring(0, 2);
//the language the system was set to the last time the app was run
String previousSystemLanguage = PreferencesUtil.getString(this, R.string.systemLanguageKey, "");
//if the system language was changed in the device settings then set that as the app language
if (!previousSystemLanguage.equals(currentSystemLanguage)
&& Arrays.asList(supportedLanguages).contains(currentSystemLanguage)) {
PreferencesUtil.setString(this, R.string.systemLanguageKey, currentSystemLanguage);
PreferencesUtil.setString(this, R.string.languageKey, currentSystemLanguage);
}
if (code == null || !Arrays.asList(supportedLanguages).contains(code)) {
//if requested language code is not supported then use language from preferences
code = PreferencesUtil.getString(this, R.string.languageKey, "");
if (!Arrays.asList(supportedLanguages).contains(code)) {
//no language was selected in the app settings so use the system language
String currentLanguage = getResources().getConfiguration().locale.getLanguage();
if (currentLanguage.equals(currentSystemLanguage)) {
//app is already set to correct language
return;
} else if (Arrays.asList(supportedLanguages).contains(currentSystemLanguage)) {
//set to system language
code = currentSystemLanguage;
} else {
//no supported languages found just default to English
code = "en";
}
}
}
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration config = res.getConfiguration();
locale = new Locale(code, Locale.getDefault().getCountry());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Resources activityRes = context.getResources();
Configuration activityConf = activityRes.getConfiguration();
activityConf.setLocale(locale);
activityRes.updateConfiguration(activityConf, activityRes.getDisplayMetrics());
PreferencesUtil.setString(this, R.string.languageKey, locale.getLanguage());
}
//if the app language is not already set to languageCode then set it now
if (!config.locale.getLanguage().substring(0, 2).equalsIgnoreCase(code)
|| !config.locale.getCountry().equalsIgnoreCase(Locale.getDefault().getCountry())) {
config.locale = locale;
config.setLayoutDirection(locale);
res.updateConfiguration(config, dm);
//if this session was launched from an external app then do not restart this app
if (!isExternal && handler != null) {
Message msg = handler.obtainMessage();
handler.sendMessage(msg);
}
}
} catch (Exception ignored) {
// do nothing
}
}
}
| 7,896 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AssetsManager.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/AssetsManager.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.content.res.AssetManager;
import org.akvo.caddisfly.app.CaddisflyApp;
import org.akvo.caddisfly.common.Constants;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import timber.log.Timber;
public final class AssetsManager {
private static AssetsManager assetsManager;
private final AssetManager manager;
private final String json;
public AssetsManager() {
this.manager = CaddisflyApp.getApp().getApplicationContext().getAssets();
json = loadJsonFromAsset(Constants.TESTS_META_FILENAME);
}
public static AssetsManager getInstance() {
if (assetsManager == null) {
assetsManager = new AssetsManager();
}
return assetsManager;
}
public String loadJsonFromAsset(String fileName) {
String json;
InputStream is = null;
try {
if (manager == null) {
return null;
}
is = manager.open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
//noinspection ResultOfMethodCallIgnored
is.read(buffer);
json = new String(buffer, StandardCharsets.UTF_8);
} catch (IOException ex) {
Timber.e(ex);
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Timber.e(e);
}
}
}
return json;
}
public String getJson() {
return json;
}
}
| 2,433 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AnimatedColor.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/AnimatedColor.java | package org.akvo.caddisfly.util;
import android.graphics.Color;
// http://myhexaville.com/2017/06/14/android-animated-status-bar-color/
public class AnimatedColor {
private final int mStartColor, mEndColor;
private final float[] mStartHSV, mEndHSV;
private float[] mMove = new float[3];
public AnimatedColor(int start, int end) {
mStartColor = start;
mEndColor = end;
mStartHSV = toHSV(start);
mEndHSV = toHSV(end);
}
public int with(float delta) {
if (delta <= 0) return mStartColor;
if (delta >= 1) return mEndColor;
return Color.HSVToColor(move(delta));
}
private float[] move(float delta) {
mMove[0] = (mEndHSV[0] - mStartHSV[0]) * delta + mStartHSV[0];
mMove[1] = (mEndHSV[1] - mStartHSV[1]) * delta + mStartHSV[1];
mMove[2] = (mEndHSV[2] - mStartHSV[2]) * delta + mStartHSV[2];
return mMove;
}
private float[] toHSV(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
return hsv;
}
} | 1,071 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
MathUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/MathUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
public final class MathUtil {
private MathUtil() {
}
/**
* Evaluates a math expression in a string.
* http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form#answer-26227947
*
* @param str the string to evaluate
* @return evaluated result
*/
public static double eval(final String str) {
return new Object() {
private int pos = -1;
private int ch;
void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}
boolean eat(int charToEat) {
while (ch == ' ') {
nextChar();
}
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < str.length()) {
throw new IllegalArgumentException("Unexpected: " + (char) ch);
}
return x;
}
// Grammar:
// expression = term | expression `+` term | expression `-` term
// term = factor | term `*` factor | term `/` factor
// factor = `+` factor | `-` factor | `(` expression `)`
// | number | functionName factor | factor `^` factor
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) {
x += parseTerm(); // addition
} else {
if (eat('-')) {
x -= parseTerm(); // subtraction
} else {
return x;
}
}
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) {
x *= parseFactor(); // multiplication
} else {
if (eat('/')) {
x /= parseFactor(); // division
} else {
return x;
}
}
}
}
double parseFactor() {
if (eat('+')) {
return parseFactor(); // unary plus
}
if (eat('-')) {
return -parseFactor(); // unary minus
}
double x;
int startPos = this.pos;
if (eat('(')) { // parentheses
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') {
nextChar();
}
x = Double.parseDouble(str.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') { // functions
while (ch >= 'a' && ch <= 'z') {
nextChar();
}
String func = str.substring(startPos, this.pos);
x = parseFactor();
switch (func) {
case "sqrt":
x = Math.sqrt(x);
break;
case "sin":
x = Math.sin(Math.toRadians(x));
break;
case "cos":
x = Math.cos(Math.toRadians(x));
break;
case "tan":
x = Math.tan(Math.toRadians(x));
break;
default:
throw new IllegalArgumentException("Unknown function: " + func);
}
} else {
throw new IllegalArgumentException("Unexpected: " + (char) ch);
}
if (eat('^')) {
x = Math.pow(x, parseFactor()); // exponentiation
}
return x;
}
}.parse();
}
}
| 5,237 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PreferencesUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/PreferencesUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import androidx.annotation.StringRes;
/**
* Various utility functions to get/set values from/to SharedPreferences.
*/
@SuppressWarnings("SameParameterValue")
public final class PreferencesUtil {
private static final String KEY_FORMAT = "%s_%s";
private PreferencesUtil() {
}
/**
* Gets a preference key from strings
*
* @param context the context
* @param keyId the key id
* @return the string key
*/
private static String getKey(Context context, @StringRes int keyId) {
return context.getString(keyId);
}
/**
* Gets a boolean value from preferences.
*
* @param context the context
* @param keyId the key id
* @param defaultValue the default value
* @return the stored boolean value
*/
public static boolean getBoolean(Context context, @StringRes int keyId, boolean defaultValue) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getBoolean(getKey(context, keyId), defaultValue);
}
/**
* Sets a boolean value to preferences.
*
* @param context the context
* @param keyId the key id
* @param value the value
*/
public static void setBoolean(Context context, @StringRes int keyId, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putBoolean(getKey(context, keyId), value);
editor.apply();
}
/**
* Gets an integer value from preferences.
*
* @param context the context
* @param key the key id
* @param defaultValue the default value
* @return stored int value
*/
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getInt(key, defaultValue);
}
/**
* Gets a long value from preferences.
*
* @param context the context
* @param keyId the key id
* @return the stored long value
*/
public static int getInt(Context context, @StringRes int keyId, int defaultValue) {
return PreferencesUtil.getInt(context, getKey(context, keyId), defaultValue);
}
public static void setInt(Context context, @StringRes int keyId, int value) {
PreferencesUtil.setInt(context, getKey(context, keyId), value);
}
/**
* Sets an integer value to preferences.
*
* @param context the context
* @param key the key id
* @param value the value to set
*/
public static void setInt(Context context, String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
/**
* Gets a long value from preferences.
*
* @param context the context
* @param keyId the key id
* @return the stored long value
*/
public static long getLong(Context context, String code, @StringRes int keyId) {
String key = String.format(KEY_FORMAT, code, getKey(context, keyId));
return getLong(context, key);
}
/**
* Gets a long value from preferences.
*
* @param context the context
* @param key the key id
* @return the stored long value
*/
@SuppressWarnings("WeakerAccess")
public static long getLong(Context context, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getLong(key, -1L);
}
public static void setLong(Context context, String code, @StringRes int keyId, long value) {
String key = String.format(KEY_FORMAT, code, getKey(context, keyId));
setLong(context, key, value);
}
/**
* Sets a long value to preferences.
*
* @param context the context
* @param keyId the key id
* @param value the value
*/
@SuppressWarnings({"unused"})
public static void setLong(Context context, @StringRes int keyId, long value) {
setLong(context, getKey(context, keyId), value);
}
/**
* Sets a long value to preferences.
*
* @param context the context
* @param key the int key id
*/
@SuppressWarnings("WeakerAccess")
public static void setLong(Context context, String key, long value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.apply();
}
/**
* Gets a string value from preferences.
*
* @param context the context
* @param keyId the key id
* @param defaultValue default value
* @return the stored string value
*/
public static String getString(Context context, @StringRes int keyId, String defaultValue) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(getKey(context, keyId), defaultValue);
}
/**
* Gets a string value from preferences.
*
* @param context the context
* @param keyId the key id
* @param defaultValue default value
* @return the stored string value
*/
private static String getString(Context context, String keyId, String defaultValue) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(keyId, defaultValue);
}
public static String getString(Context context, String code, @StringRes int keyId, String defaultValue) {
String key = String.format(KEY_FORMAT, code, getKey(context, keyId));
return getString(context, key, defaultValue);
}
/**
* Sets a string value to preferences.
*
* @param context the context
* @param keyId the key id
*/
public static void setString(Context context, @StringRes int keyId, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putString(getKey(context, keyId), value);
editor.apply();
}
public static void setString(Context context, String code, @StringRes int keyId, String value) {
String key = String.format(KEY_FORMAT, code, getKey(context, keyId));
setString(context, key, value);
}
/**
* Sets a string value to preferences.
*
* @param context the context
* @param keyId the key id
*/
@SuppressWarnings("WeakerAccess")
public static void setString(Context context, String keyId, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putString(keyId, value);
editor.apply();
}
@SuppressWarnings({"unused"})
public static void removeKey(Context context, @StringRes int keyId) {
removeKey(context, getKey(context, keyId));
}
/**
* Removes the key from the preferences.
*
* @param context the context
* @param key the key id
*/
private static void removeKey(Context context, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.remove(key);
editor.apply();
}
/**
* Checks if the key is already saved in the preferences.
*
* @param context the context
* @param keyId the key id
* @return true if found
*/
public static boolean containsKey(Context context, @StringRes int keyId) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.contains(getKey(context, keyId));
}
}
| 9,473 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
AlertUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/AlertUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import org.akvo.caddisfly.R;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
/**
* Utility functions to show alert messages.
*/
@SuppressWarnings({"SameParameterValue", "UnusedReturnValue"})
public final class AlertUtil {
private AlertUtil() {
}
/**
* Displays an alert dialog.
*
* @param context the context
* @param title the title
* @param message the message
*/
public static void showMessage(@NonNull Context context, @StringRes int title, @StringRes int message) {
showAlert(context, title, message, null, null, null);
}
/**
* Displays an alert dialog.
*
* @param context the context
* @param title the title
* @param message the message
*/
public static void showMessage(@NonNull Context context, @StringRes int title, String message) {
showAlert(context, title, message, null, null, null);
}
public static void askQuestion(@NonNull Context context, @StringRes int title, @StringRes int message,
@StringRes int okButtonText, @StringRes int cancelButtonText,
boolean isDestructive,
DialogInterface.OnClickListener positiveListener,
@Nullable DialogInterface.OnClickListener cancelListener) {
showAlert(context, context.getString(title), context.getString(message), okButtonText,
cancelButtonText, true, isDestructive, positiveListener,
cancelListener == null ? (dialogInterface, i) -> dialogInterface.dismiss() : cancelListener,
null);
}
public static AlertDialog showAlert(@NonNull Context context, @StringRes int title, String message,
@StringRes int okButtonText,
DialogInterface.OnClickListener positiveListener,
DialogInterface.OnClickListener negativeListener,
DialogInterface.OnCancelListener cancelListener) {
return showAlert(context, context.getString(title), message, okButtonText, R.string.cancel,
true, false, positiveListener, negativeListener, cancelListener);
}
public static AlertDialog showAlert(@NonNull Context context, @StringRes int title, @StringRes int message,
@StringRes int okButtonText,
DialogInterface.OnClickListener positiveListener,
DialogInterface.OnClickListener negativeListener,
DialogInterface.OnCancelListener cancelListener) {
return showAlert(context, context.getString(title), context.getString(message), okButtonText,
R.string.cancel, true, false, positiveListener, negativeListener, cancelListener);
}
private static void showAlert(@NonNull Context context, @StringRes int title, @StringRes int message,
DialogInterface.OnClickListener positiveListener,
DialogInterface.OnClickListener negativeListener,
DialogInterface.OnCancelListener cancelListener) {
showAlert(context, context.getString(title), context.getString(message), R.string.ok, R.string.cancel,
true, false, positiveListener, negativeListener, cancelListener);
}
private static void showAlert(@NonNull Context context, @StringRes int title, String message,
DialogInterface.OnClickListener positiveListener,
DialogInterface.OnClickListener negativeListener,
DialogInterface.OnCancelListener cancelListener) {
showAlert(context, context.getString(title), message, R.string.ok, R.string.cancel,
true, false, positiveListener, negativeListener, cancelListener);
}
/**
* Displays an alert dialog.
*
* @param context the context
* @param title the title
* @param message the message
* @param okButtonText ok button text
* @param positiveListener ok button listener
* @param negativeListener cancel button listener
* @return the alert dialog
*/
private static AlertDialog showAlert(@NonNull final Context context, String title, String message,
@StringRes int okButtonText, @StringRes int cancelButtonText,
boolean cancelable, boolean isDestructive,
@Nullable DialogInterface.OnClickListener positiveListener,
@Nullable DialogInterface.OnClickListener negativeListener,
DialogInterface.OnCancelListener cancelListener) {
AlertDialog.Builder builder;
if (isDestructive) {
TypedArray a = context.obtainStyledAttributes(R.styleable.BaseActivity);
int style = a.getResourceId(R.styleable.BaseActivity_dialogDestructiveButton, 0);
a.recycle();
builder = new AlertDialog.Builder(context, style);
} else {
builder = new AlertDialog.Builder(context);
}
builder.setTitle(title)
.setMessage(message)
.setCancelable(cancelable);
if (positiveListener != null) {
builder.setPositiveButton(okButtonText, positiveListener);
} else if (negativeListener == null) {
builder.setNegativeButton(okButtonText, (dialogInterface, i) -> dialogInterface.dismiss());
}
if (negativeListener != null) {
builder.setNegativeButton(cancelButtonText, negativeListener);
}
builder.setOnCancelListener(cancelListener);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
return alertDialog;
}
/**
* Displays an alert with error layout.
*
* @param context the context
* @param title the title
* @param message the message
* @param bitmap a bitmap to show along with message
* @param okButtonText ok button text
* @param positiveListener ok button listener
* @param negativeListener cancel button listener
* @return the alert dialog
*/
@SuppressLint("InflateParams")
public static AlertDialog showError(@NonNull Context context, @StringRes int title,
String message, @Nullable Bitmap bitmap,
@StringRes int okButtonText,
@Nullable DialogInterface.OnClickListener positiveListener,
@Nullable DialogInterface.OnClickListener negativeListener,
DialogInterface.OnCancelListener cancelListener) {
if (bitmap == null) {
return showAlert(context, context.getString(title), message, okButtonText,
R.string.cancel, false, false, positiveListener, negativeListener, cancelListener);
}
final AlertDialog alertDialog;
View alertView;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
alertView = inflater.inflate(R.layout.dialog_error, null, false);
builder.setView(alertView);
builder.setTitle(R.string.error);
builder.setMessage(message);
ImageView image = alertView.findViewById(R.id.imageSample);
image.setImageBitmap(bitmap);
if (positiveListener != null) {
builder.setPositiveButton(okButtonText, positiveListener);
}
if (negativeListener == null) {
builder.setNegativeButton(R.string.cancel, null);
} else {
int buttonText = R.string.cancel;
if (positiveListener == null) {
buttonText = okButtonText;
}
builder.setNegativeButton(buttonText, negativeListener);
}
builder.setCancelable(false);
alertDialog = builder.create();
if (context instanceof Activity) {
alertDialog.setOwnerActivity((Activity) context);
}
alertDialog.show();
return alertDialog;
}
}
| 9,772 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ApiUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/ApiUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import androidx.annotation.Nullable;
import org.akvo.caddisfly.sensor.manual.OnKeyboardVisibilityListener;
import timber.log.Timber;
/**
* Utility functions for api related actions.
*/
public final class ApiUtil {
private ApiUtil() {
}
@Nullable
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
Timber.e(e);
}
return c;
}
public static void startInstalledAppDetailsActivity(@Nullable final Activity context) {
if (context == null) {
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}
//https://stackoverflow.com/questions/4312319/how-to-capture-the-virtual-keyboard-show-hide-event-in-android
public static void setKeyboardVisibilityListener(
final OnKeyboardVisibilityListener onKeyboardVisibilityListener) {
Activity activity = (Activity) onKeyboardVisibilityListener;
final View parentView = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
parentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
private final int defaultKeyboardHeightDP = 100;
private final int EstimatedKeyboardDP = defaultKeyboardHeightDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);
private final Rect rect = new Rect();
private boolean alreadyOpen;
@Override
public void onGlobalLayout() {
int estimatedKeyboardHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, parentView.getResources().getDisplayMetrics());
parentView.getWindowVisibleDisplayFrame(rect);
int heightDiff = parentView.getRootView().getHeight() - (rect.bottom - rect.top);
boolean isShown = heightDiff >= estimatedKeyboardHeight;
if (isShown == alreadyOpen) {
return;
}
alreadyOpen = isShown;
onKeyboardVisibilityListener.onKeyboardVisibilityChanged(isShown);
}
});
}
}
| 3,736 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ImageUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/ImageUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import static org.akvo.caddisfly.helper.FileHelper.getUnitTestImagesFolder;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.exifinterface.media.ExifInterface;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import timber.log.Timber;
/**
* Set of utility functions to manipulate images.
*/
public final class ImageUtil {
private ImageUtil() {
}
public static boolean saveImage(Bitmap bitmap, String filename) {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(filename))) {
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out)) {
return true;
}
} catch (FileNotFoundException e) {
Timber.e(e);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private static void checkOrientation(String originalImage, String resizedImage) {
try {
ExifInterface exif1 = new ExifInterface(originalImage);
ExifInterface exif2 = new ExifInterface(resizedImage);
final String orientation1 = exif1.getAttribute(ExifInterface.TAG_ORIENTATION);
final String orientation2 = exif2.getAttribute(ExifInterface.TAG_ORIENTATION);
if (orientation1 != null && !TextUtils.isEmpty(orientation1)
&& !orientation1.equals(orientation2)) {
Timber.d("Orientation property in EXIF does not match. Overriding it with original value...");
exif2.setAttribute(ExifInterface.TAG_ORIENTATION, orientation1);
exif2.saveAttributes();
}
} catch (IOException e) {
Timber.e(e);
}
}
/**
* resizeImage handles resizing a too-large image file from the camera.
*/
public static void resizeImage(String origFilename, String outFilename, int width) {
int reqWidth;
int reqHeight;
reqWidth = width;
reqHeight = 960;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(origFilename, options);
// If image is in portrait mode, we swap the maximum width and height
if (options.outHeight > options.outWidth) {
int tmp = reqHeight;
//noinspection SuspiciousNameCombination
reqHeight = reqWidth;
reqWidth = tmp;
}
Timber.d("Orig Image size: %d x %d", options.outWidth, options.outHeight);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(origFilename, options);
if (bitmap != null && ImageUtil.saveImage(bitmap, outFilename)) {
ImageUtil.checkOrientation(origFilename, outFilename);// Ensure the EXIF data is not lost
// Timber.d("Resized Image size: %d x %d", bitmap.getWidth(), bitmap.getHeight());
}
}
/**
* Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
* the closest inSampleSize that will result in the final decoded bitmap having a width and
* height equal to or larger than the requested width and height. This implementation does not
* ensure a power of 2 is returned for inSampleSize which can be faster when decoding but
* results in a larger bitmap which isn't as useful for caching purposes.
*
* @param options An options object with out* params already populated (run through a decode*
* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
/**
* load the bytes from a file.
*
* @param name the file name
* @return the loaded bytes
*/
public static byte[] loadImageBytes(String name) {
File file = new File(getUnitTestImagesFolder(), name + ".yuv");
if (file.exists()) {
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytes);
} catch (IOException e) {
Timber.e(e);
}
return bytes;
}
return new byte[0];
}
/**
* Save an image in yuv format
*
* @param data the image data
* @param fileName the name of the file
*/
public static void saveYuvImage(@NonNull byte[] data, String fileName) {
File file = new File(getUnitTestImagesFolder(), fileName + ".yuv");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file.getPath());
fos.write(data);
} catch (Exception ignored) {
// do nothing
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
Timber.e(e);
}
}
}
}
}
| 8,275 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ListViewUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/ListViewUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* Utility functions for ListView manipulation.
*/
public final class ListViewUtil {
private ListViewUtil() {
}
/**
* Set the ListView height based on the number of rows and their height
* <p/>
* Height for ListView needs to be set if used as a child of another ListView.
* The child ListView will not display any scrollbars so the height needs to be
* set so that all the rows are visible
*
* @param listView the list view
* @param extraHeight extra bottom padding
*/
@SuppressWarnings("SameParameterValue")
public static void setListViewHeightBasedOnChildren(ListView listView, int extraHeight) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = extraHeight + totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
| 2,231 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
DateUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/DateUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import java.util.Calendar;
/**
* Utility functions for date and time.
*/
public final class DateUtil {
private DateUtil() {
}
/**
* Gets the number of days in between two given dates.
*
* @param calendar1 the first date
* @param calendar2 the second date
* @return the number days
*/
public static int getDaysDifference(Calendar calendar1, Calendar calendar2) {
if (calendar1 == null || calendar2 == null) {
return 0;
}
return (int) ((calendar2.getTimeInMillis()
- calendar1.getTimeInMillis()) / (1000 * 60 * 60 * 24));
}
/**
* Gets the number of hours in between two given dates.
*
* @param calendar1 the first date
* @param calendar2 the second date
* @return the number hours
*/
public static int getHoursDifference(Calendar calendar1, Calendar calendar2) {
if (calendar1 == null || calendar2 == null) {
return 0;
}
return (int) ((calendar2.getTimeInMillis()
- calendar1.getTimeInMillis()) / (1000 * 60 * 60));
}
}
| 1,910 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
StringUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/util/StringUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import org.akvo.caddisfly.R;
import org.akvo.caddisfly.model.TestInfo;
import org.akvo.caddisfly.widget.CenteredImageSpan;
import org.jetbrains.annotations.NotNull;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class StringUtil {
private StringUtil() {
}
public static Spanned getStringResourceByName(Context context, String theKey) {
return getStringResourceByName(context, theKey,
context.getResources().getConfiguration().locale.getLanguage());
}
public static Spanned getStringResourceByName(Context context, String theKey, String language) {
String key = theKey.trim();
String packageName = context.getPackageName();
int resId = context.getResources().getIdentifier(key, "string", packageName);
if (resId == 0) {
return Spannable.Factory.getInstance().newSpannable(fromHtml(key));
} else {
if (!language.isEmpty()) {
return Spannable.Factory.getInstance().newSpannable(
getLocalizedResources(context, new Locale(language)).getText(resId));
} else {
return Spannable.Factory.getInstance().newSpannable(context.getText(resId));
}
}
}
@NonNull
private static Resources getLocalizedResources(Context context, Locale desiredLocale) {
Configuration conf = context.getResources().getConfiguration();
conf = new Configuration(conf);
conf.setLocale(desiredLocale);
Context localizedContext = context.createConfigurationContext(conf);
return localizedContext.getResources();
}
public static Spanned fromHtml(String html) {
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
public static SpannableStringBuilder toInstruction(AppCompatActivity context, TestInfo testInfo, String text) {
SpannableStringBuilder builder = new SpannableStringBuilder();
boolean isBold = false;
if (text.startsWith("<b>") && text.endsWith("</b>")) {
isBold = true;
text = text.replace("<b>", "").replace("</b>", "");
}
Spanned spanned = StringUtil.getStringResourceByName(context, text);
builder.append(spanned);
if (isBold) {
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
builder.setSpan(
boldSpan,
0,
builder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
Matcher m = Pattern.compile("\\(\\*(\\w+)\\*\\)").matcher(builder);
while (m.find()) {
int resId = context.getResources().getIdentifier("button_" + m.group(1),
"drawable", context.getPackageName());
if (resId > 0) {
builder.setSpan(new CenteredImageSpan(context, resId),
m.start(0), m.end(0), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
}
// Set reagent in the string
replaceReagentTags(testInfo, builder);
// Set sample quantity in the string
Matcher m1 = Pattern.compile("%sampleQuantity").matcher(builder);
while (m1.find()) {
builder.replace(m1.start(), m1.end(), testInfo.getSampleQuantity());
}
if (testInfo != null) {
// Set reaction time in the string
for (int i = 1; i < 5; i++) {
Matcher m2 = Pattern.compile("%reactionTime" + i).matcher(builder);
while (m2.find()) {
if (testInfo.getReagent(i - 1).reactionTime != null) {
builder.replace(m2.start(), m2.end(),
context.getResources().getQuantityString(R.plurals.minutes,
testInfo.getReagent(i - 1).reactionTime,
testInfo.getReagent(i - 1).reactionTime));
}
}
}
}
insertDialogLinks(context, builder);
return builder;
}
private static void insertDialogLinks(AppCompatActivity context, SpannableStringBuilder builder) {
if (builder.toString().contains("[a topic=")) {
int startIndex = builder.toString().indexOf("[a topic=");
String topic;
Pattern p = Pattern.compile("\\[a topic=(.*?)]");
Matcher m3 = p.matcher(builder);
if (m3.find()) {
topic = m3.group(1);
builder.replace(m3.start(), m3.end(), "");
int endIndex = builder.toString().indexOf("[/a]");
builder.replace(endIndex, endIndex + 4, "");
String finalTopic = topic;
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(@NotNull View textView) {
if (finalTopic.equalsIgnoreCase("sulfide")) {
DialogFragment newFragment = new SulfideDialogFragment();
newFragment.show(context.getSupportFragmentManager(), "sulfideDialog");
}
}
@Override
public void updateDrawState(@NotNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
builder.setSpan(clickableSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(new UnderlineSpan(), startIndex, endIndex, 0);
}
}
}
private static void replaceReagentTags(TestInfo testInfo, SpannableStringBuilder builder) {
for (int i = 1; i < 5; i++) {
Matcher m1 = Pattern.compile("%reagent" + i).matcher(builder);
while (m1.find()) {
String name = testInfo.getReagent(i - 1).name;
String code = testInfo.getReagent(i - 1).code;
if (!code.isEmpty()) {
name = String.format("%s (%s)", name, code);
}
builder.replace(m1.start(), m1.end(), name);
}
}
}
public static String convertToTags(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
result.append("(*").append(text.charAt(i)).append("*)");
}
return result.toString();
}
public static String getStringByName(Context context, String name) {
if (name == null) {
return "";
}
return context.getResources().getString(context.getResources()
.getIdentifier(name, "string", context.getPackageName()));
}
public static class SulfideDialogFragment extends DialogFragment {
@NonNull
@SuppressLint("InflateParams")
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_sulfide_instruction, null))
// Add action buttons
.setPositiveButton(R.string.ok, (dialog, id) -> dialog.dismiss());
return builder.create();
}
}
}
| 9,323 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
MpnValue.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/MpnValue.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
public class MpnValue {
private final String mpn;
private final double confidence;
private final String riskCategory;
private int backgroundColor1;
private int backgroundColor2;
public MpnValue(String mpn, double confidence, String riskCategory) {
this.mpn = mpn;
this.confidence = confidence;
this.riskCategory = riskCategory;
}
public String getMpn() {
return mpn;
}
public double getConfidence() {
return confidence;
}
public String getRiskCategory() {
return riskCategory;
}
public int getBackgroundColor1() {
return backgroundColor1;
}
public void setBackgroundColor1(int backgroundColor1) {
this.backgroundColor1 = backgroundColor1;
}
public int getBackgroundColor2() {
return backgroundColor2;
}
public void setBackgroundColor2(int backgroundColor2) {
this.backgroundColor2 = backgroundColor2;
}
}
| 1,767 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestInfo.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/TestInfo.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TestInfo implements Parcelable {
public static final Creator<TestInfo> CREATOR = new Creator<TestInfo>() {
@Override
public TestInfo createFromParcel(Parcel in) {
return new TestInfo(in);
}
@Override
public TestInfo[] newArray(int size) {
return new TestInfo[size];
}
};
private final transient DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
private final transient DecimalFormat decimalFormat = new DecimalFormat("#.###", symbols);
@SerializedName("reagentType")
@Expose
private String reagentType = "";
@SerializedName("reagents")
@Expose
private List<Reagent> reagents = null;
@SerializedName("isCategory")
@Expose
private boolean isCategory;
@SerializedName("category")
@Expose
private String category;
@SerializedName("name")
@Expose
private String name;
@SerializedName("description")
@Expose
private String description;
@SerializedName("subtype")
@Expose
private TestType subtype;
@SerializedName("tags")
@Expose
private List<String> tags = null;
@SerializedName("uuid")
@Expose
private String uuid;
@SerializedName("brand")
@Expose
private String brand;
@SerializedName("brandUrl")
@Expose
private String brandUrl = "";
@SerializedName("groupingType")
@Expose
private GroupType groupingType;
@SerializedName("illuminant")
@Expose
private String illuminant;
@SerializedName("length")
@Expose
private Double length;
@SerializedName("height")
@Expose
private Double height;
@SerializedName("unit")
@Expose
private String unit;
@SerializedName("hasImage")
@Expose
private Boolean hasImage = false;
@SerializedName("results")
@Expose
private List<Result> results = new ArrayList<>();
@SerializedName("ranges")
@Expose
private String ranges;
@SerializedName("monthsValid")
@Expose
private Integer monthsValid;
@SerializedName("md610_id")
@Expose
private String md610Id;
@SerializedName("sampleQuantity")
@Expose
private String sampleQuantity;
@SerializedName("selectInstruction")
@Expose
private String selectInstruction;
@SerializedName("endInstruction")
@Expose
private String endInstruction;
@SerializedName("hasEndInstruction")
@Expose
private Boolean hasEndInstruction;
@SerializedName("instructions")
@Expose
private List<Instruction> instructions = null;
@SerializedName("instructions2")
@Expose
private List<Instruction> instructions2 = null;
@SerializedName("image")
@Expose
private String image;
@SerializedName("numPatch")
@Expose
private Integer numPatch;
@SerializedName("deviceId")
@Expose
private String deviceId;
@SerializedName("responseFormat")
@Expose
private String responseFormat;
@SerializedName("imageScale")
@Expose
private String imageScale;
public TestInfo() {
}
public TestInfo(String categoryName) {
category = categoryName;
isCategory = true;
}
private TestInfo(Parcel in) {
isCategory = in.readByte() != 0;
category = in.readString();
name = in.readString();
subtype = TestType.valueOf(in.readString());
description = in.readString();
tags = in.createStringArrayList();
reagentType = in.readString();
reagents = new ArrayList<>();
in.readTypedList(reagents, Reagent.CREATOR);
uuid = in.readString();
brand = in.readString();
brandUrl = in.readString();
String tmpGroupingType = in.readString();
if (tmpGroupingType != null && !tmpGroupingType.equalsIgnoreCase("null")) {
groupingType = GroupType.valueOf(tmpGroupingType);
}
illuminant = in.readString();
if (in.readByte() == 0) {
length = 0.0;
} else {
length = in.readDouble();
}
if (in.readByte() == 0) {
height = 0.0;
} else {
height = in.readDouble();
}
unit = in.readString();
byte tmpHasImage = in.readByte();
hasImage = tmpHasImage == 1;
ranges = in.readString();
if (in.readByte() == 0) {
monthsValid = null;
} else {
monthsValid = in.readInt();
}
md610Id = in.readString();
sampleQuantity = in.readString();
results = new ArrayList<>();
in.readTypedList(results, Result.CREATOR);
instructions = new ArrayList<>();
in.readTypedList(instructions, Instruction.CREATOR);
instructions2 = new ArrayList<>();
in.readTypedList(instructions2, Instruction.CREATOR);
selectInstruction = in.readString();
endInstruction = in.readString();
byte tmpHasEndInstruction = in.readByte();
hasEndInstruction = tmpHasEndInstruction == 1;
image = in.readString();
imageScale = in.readString();
if (in.readByte() == 0) {
numPatch = null;
} else {
numPatch = in.readInt();
}
deviceId = in.readString();
responseFormat = in.readString();
}
public boolean getIsGroup() {
return isCategory;
}
public String getCategory() {
return category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TestType getSubtype() {
return subtype;
}
public String getUuid() {
return uuid;
}
public String getBrand() {
return brand;
}
public String getRanges() {
return ranges;
}
public double getMinRangeValue() {
String[] array = ranges.split(",");
try {
return Double.valueOf(array[0]);
} catch (NumberFormatException e) {
return -1;
}
}
public double getMaxRangeValue() {
String[] array = ranges.split(",");
try {
return Double.valueOf(array[array.length - 1]);
} catch (NumberFormatException e) {
return -1;
}
}
public String getMinMaxRange() {
if (results != null && results.size() > 0) {
StringBuilder minMaxRange = new StringBuilder();
for (Result result : results) {
if (result.getColors() != null && result.getColors().size() > 0) {
int valueCount = result.getColors().size();
if (minMaxRange.length() > 0) {
minMaxRange.append(", ");
}
if (result.getColors().size() > 0) {
minMaxRange.append(String.format(Locale.US, "%s - %s",
decimalFormat.format(result.getColors().get(0).getValue()),
decimalFormat.format(result.getColors().get(valueCount - 1).getValue())));
}
if (groupingType == GroupType.GROUP) {
break;
}
} else {
if (ranges != null) {
String[] rangeArray = ranges.split(",");
if (rangeArray.length > 1) {
return rangeArray[0].trim() + " - " + rangeArray[rangeArray.length - 1].trim();
} else {
return "";
}
} else {
return "";
}
}
}
return minMaxRange.toString();
}
return "";
}
public String getMd610Id() {
return md610Id;
}
public String getBrandUrl() {
return brandUrl;
}
public GroupType getGroupingType() {
return groupingType;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public String getSampleQuantity() {
return sampleQuantity;
}
public List<Instruction> getInstructions() {
return instructions;
}
public List<Instruction> getInstructions2() {
return instructions2;
}
public String getImage() {
return image;
}
public String getImageScale() {
return imageScale;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeByte((byte) (isCategory ? 1 : 0));
parcel.writeString(category);
parcel.writeString(name);
parcel.writeString(subtype.name());
parcel.writeString(description);
parcel.writeStringList(tags);
parcel.writeString(reagentType);
parcel.writeTypedList(reagents);
parcel.writeString(uuid);
parcel.writeString(brand);
parcel.writeString(brandUrl);
parcel.writeString(String.valueOf(groupingType));
parcel.writeString(illuminant);
if (length == null) {
parcel.writeByte((byte) 0);
} else {
parcel.writeByte((byte) 1);
parcel.writeDouble(length);
}
if (height == null) {
parcel.writeByte((byte) 0);
} else {
parcel.writeByte((byte) 1);
parcel.writeDouble(height);
}
parcel.writeString(unit);
parcel.writeByte((byte) (hasImage == null ? 0 : hasImage ? 1 : 2));
parcel.writeString(ranges);
if (monthsValid == null) {
parcel.writeByte((byte) 0);
} else {
parcel.writeByte((byte) 1);
parcel.writeInt(monthsValid);
}
parcel.writeString(md610Id);
parcel.writeString(sampleQuantity);
parcel.writeTypedList(results);
parcel.writeTypedList(instructions);
parcel.writeTypedList(instructions2);
parcel.writeString(selectInstruction);
parcel.writeString(endInstruction);
parcel.writeByte((byte) (hasEndInstruction == null ? 0 : hasEndInstruction ? 1 : 2));
parcel.writeString(image);
parcel.writeString(imageScale);
if (numPatch == null) {
parcel.writeByte((byte) 0);
} else {
parcel.writeByte((byte) 1);
parcel.writeInt(numPatch);
}
parcel.writeString(deviceId);
parcel.writeString(responseFormat);
}
public Reagent getReagent(int i) {
if (reagents != null && reagents.size() > i) {
return reagents.get(i);
} else {
return new Reagent();
}
}
public List<Result> getResults() {
return results;
}
public String getSelectInstruction() {
return selectInstruction;
}
public String getEndInstruction() {
return endInstruction;
}
public double getStripLength() {
return length;
}
public String getDeviceId() {
return deviceId;
}
public String getResponseFormat() {
return responseFormat;
}
public Boolean getHasImage() {
return hasImage;
}
public String getReagentType() {
return reagentType;
}
} | 12,561 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Reagent.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/Reagent.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Reagent implements Parcelable {
public static final Creator<Reagent> CREATOR = new Creator<Reagent>() {
public Reagent createFromParcel(Parcel in) {
return new Reagent(in);
}
public Reagent[] newArray(int size) {
return (new Reagent[size]);
}
};
@SerializedName("name")
@Expose
public String name = "";
@SerializedName("code")
@Expose
public String code = "";
@SerializedName("reactionTime")
@Expose
public Integer reactionTime;
@SerializedName("type")
@Expose
public ReagentType type;
private Reagent(Parcel in) {
name = ((String) in.readValue((String.class.getClassLoader())));
code = ((String) in.readValue((String.class.getClassLoader())));
reactionTime = ((Integer) in.readValue((Integer.class.getClassLoader())));
type = ReagentType.valueOf(in.readString());
}
public Reagent() {
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(name);
dest.writeValue(code);
dest.writeValue(reactionTime);
if (type == null) {
dest.writeString(ReagentType.NONE.name());
} else {
dest.writeString(type.name());
}
}
public int describeContents() {
return 0;
}
} | 2,288 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestConfig.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/TestConfig.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class TestConfig {
@SerializedName("tests")
@Expose
private final List<TestInfo> tests = null;
public List<TestInfo> getTests() {
return tests;
}
}
| 1,094 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PageIndex.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/PageIndex.java | package org.akvo.caddisfly.model;
import android.util.SparseArray;
import java.util.ArrayList;
public class PageIndex {
private SparseArray<PageType> pages = new SparseArray<>();
private ArrayList<Integer> inputIndexes = new ArrayList<>();
private ArrayList<Integer> photoIndexes = new ArrayList<>();
private int resultIndex = -1;
private int skipToIndex = -1;
private int skipToIndex2 = -1;
public void setPhotoIndex(int index) {
pages.put(index, PageType.PHOTO);
photoIndexes.add(index);
}
public void setInputIndex(int index) {
pages.put(index, PageType.INPUT);
inputIndexes.add(index);
}
public int getPhotoPageIndex(int index) {
if (photoIndexes.size() > index) {
return photoIndexes.get(index);
} else {
return -1;
}
}
public int getInputPageIndex(int index) {
if (inputIndexes.size() > index) {
return inputIndexes.get(index);
} else {
return -1;
}
}
public int getResultIndex() {
return resultIndex;
}
public void setResultIndex(int index) {
pages.put(index, PageType.RESULT);
resultIndex = index;
}
public int getSkipToIndex() {
return skipToIndex;
}
public void setSkipToIndex(int value) {
skipToIndex = value;
}
public int getSkipToIndex2() {
return skipToIndex2;
}
public void setSkipToIndex2(int value) {
skipToIndex2 = value;
}
public PageType getType(int position) {
if (pages.indexOfKey(position) < 0) {
return PageType.DEFAULT;
} else {
return pages.get(position);
}
}
public void clear() {
pages.clear();
photoIndexes.clear();
inputIndexes.clear();
}
}
| 1,862 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Result.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/Result.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.akvo.caddisfly.preference.AppPreferences;
import java.util.ArrayList;
import java.util.List;
public class Result implements Parcelable {
@SuppressWarnings("unused")
public static final Creator<Result> CREATOR = new Creator<Result>() {
@Override
public Result createFromParcel(Parcel in) {
return new Result(in);
}
@Override
public Result[] newArray(int size) {
return new Result[size];
}
};
@SerializedName("id")
@Expose
private final Integer id;
@SerializedName("md610_id")
@Expose
private final String md610Id;
@SerializedName("name")
@Expose
private final String name;
@SerializedName("unit")
@Expose
private final String unit;
@SerializedName("range")
@Expose
private final String range;
@SerializedName("formula")
@Expose
private final String formula;
@SerializedName("unitChoice")
@Expose
private final String unitChoice;
@SerializedName("patchPos")
@Expose
private final Double patchPos;
@SerializedName("patchWidth")
@Expose
private final Double patchWidth;
@SerializedName("timeDelay")
@Expose
private final Integer timeDelay;
@SerializedName("testStage")
@Expose
private final Integer testStage;
@SerializedName("colors")
@Expose
private final List<ColorItem> colorItems;
@SerializedName("grayScale")
@Expose
private final Boolean grayScale;
private Float resultValue;
private Result(Parcel in) {
id = in.readByte() == 0x00 ? null : in.readInt();
md610Id = in.readString();
name = in.readString();
unit = in.readString();
range = in.readString();
formula = in.readString();
unitChoice = in.readString();
patchPos = in.readByte() == 0x00 ? null : in.readDouble();
patchWidth = in.readByte() == 0x00 ? null : in.readDouble();
timeDelay = in.readByte() == 0x00 ? null : in.readInt();
testStage = in.readByte() == 0x00 ? null : in.readInt();
if (in.readByte() == 0x01) {
colorItems = new ArrayList<>();
in.readList(colorItems, ColorItem.class.getClassLoader());
} else {
colorItems = null;
}
byte tmpGrayScale = in.readByte();
grayScale = tmpGrayScale == 1;
resultValue = in.readByte() == 0x00 ? null : in.readFloat();
}
public Integer getId() {
return id;
}
public String getMd610Id() {
return md610Id;
}
public String getName() {
return name;
}
public String getUnit() {
return unit == null ? "" : unit;
}
public String getRange() {
return range == null ? "" : range;
}
public String getFormula() {
return formula == null ? "" : formula;
}
public String getUnitChoice() {
return unitChoice;
}
public Double getPatchPos() {
return patchPos;
}
public Double getPatchWidth() {
return patchWidth;
}
/**
* Time to wait before analyzing.
*
* @return the time delay milli seconds
*/
public Integer getTimeDelay() {
if (AppPreferences.ignoreTimeDelays()) {
// use the id as seconds when ignoring actual timeDelay
return id;
} else {
return timeDelay == null ? 0 : timeDelay;
}
}
public Integer getTestStage() {
return testStage == null ? 1 : testStage;
}
public List<ColorItem> getColors() {
return colorItems == null ? new ArrayList<>() : colorItems;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(id);
}
dest.writeString(md610Id);
dest.writeString(name);
dest.writeString(unit);
dest.writeString(range);
dest.writeString(formula);
dest.writeString(unitChoice);
if (patchPos == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeDouble(patchPos);
}
if (patchWidth == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeDouble(patchWidth);
}
if (timeDelay == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(timeDelay);
}
if (testStage == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(testStage);
}
if (colorItems == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(colorItems);
}
dest.writeByte((byte) (grayScale == null ? 0 : grayScale ? 1 : 2));
if (resultValue == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeDouble(resultValue);
}
}
public float getResultValue() {
return resultValue;
}
public void setResultValue(float resultValue) {
this.resultValue = resultValue;
}
} | 6,510 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
TestType.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/TestType.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import com.google.gson.annotations.SerializedName;
/**
* The different types of testing methods.
*/
public enum TestType {
/**
* Strip paper is dipped into the sample and color is analysed from the resulting
* color change on the strip paper.
*/
@SerializedName("striptest")
STRIP_TEST,
/**
* External sensors connected to the phone/device.
*/
@SerializedName("sensor")
SENSOR,
/**
* External sensors/meters not connected to the phone/device.
*/
@SerializedName("manual")
MANUAL,
/**
* Lovibond tester - manual swatch select
*/
@SerializedName("manual_color_select")
MANUAL_COLOR_SELECT,
/**
* External bluetooth testing device.
*/
@SerializedName("bluetooth")
BLUETOOTH,
/**
* Aquagenx CBT.
*/
@SerializedName("cbt")
CBT,
}
| 1,662 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
Instruction.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/Instruction.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Instruction implements Parcelable, Cloneable {
public static final Creator<Instruction> CREATOR = new Creator<Instruction>() {
@Override
public Instruction createFromParcel(Parcel in) {
return new Instruction(in);
}
@Override
public Instruction[] newArray(int size) {
return new Instruction[size];
}
};
@SerializedName("section")
@Expose
public final List<String> section;
@SerializedName("testStage")
@Expose
public final int testStage;
@SerializedName("image")
@Expose
private final String image;
@SerializedName("layout")
@Expose
private final String layout;
private int index;
private Instruction(Instruction instruction) {
index = instruction.index;
section = new ArrayList<>(instruction.section);
image = instruction.image;
layout = instruction.layout;
testStage = instruction.testStage;
}
private Instruction(Parcel in) {
index = in.readInt();
section = in.createStringArrayList();
image = in.readString();
layout = in.readString();
testStage = in.readInt();
}
public Instruction clone() throws CloneNotSupportedException {
Instruction clone = (Instruction) super.clone();
return new Instruction(clone);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(index);
parcel.writeStringList(section);
parcel.writeString(image);
parcel.writeString(layout);
parcel.writeInt(testStage);
}
public int getIndex() {
return index;
}
public void setIndex(int value) {
index = value;
}
}
| 2,834 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
GroupType.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/GroupType.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import com.google.gson.annotations.SerializedName;
/**
* The different types of testing methods.
*/
public enum GroupType {
/**
* Liquid reagent is mixed with sample and color is analysed from the resulting
* color change in the solution.
*/
@SerializedName("INDIVIDUAL")
INDIVIDUAL,
/**
* Strip paper is dipped into the sample and color is analysed from the resulting
* color change on the strip paper.
*/
@SerializedName("GROUP")
GROUP
}
| 1,289 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ColorItem.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/ColorItem.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class ColorItem implements Parcelable {
@SuppressWarnings("unused")
public static final Creator<ColorItem> CREATOR = new Creator<ColorItem>() {
@Override
public ColorItem createFromParcel(Parcel in) {
return new ColorItem(in);
}
@Override
public ColorItem[] newArray(int size) {
return new ColorItem[size];
}
};
@SerializedName("lab")
@Expose
private final List<Double> lab;
@SerializedName("value")
@Expose
private Double value;
private Integer rgb;
private ColorItem(Parcel in) {
value = in.readByte() == 0x00 ? null : in.readDouble();
if (in.readByte() == 0x01) {
lab = new ArrayList<>();
in.readList(lab, Double.class.getClassLoader());
} else {
lab = null;
}
if (in.readByte() == 0) {
rgb = 0;
} else {
rgb = in.readInt();
}
}
public ColorItem(double value, int r, int g, int b) {
this.value = value;
this.rgb = Color.rgb(r, g, b);
this.lab = null;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public List<Double> getLab() {
return lab;
}
public int getRgb() {
return rgb;
}
public void setRgb(int rgb) {
this.rgb = rgb;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
if (value == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeDouble(value);
}
if (lab == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(lab);
}
if (rgb == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeInt(rgb);
}
}
} | 3,142 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
PageType.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/PageType.java | package org.akvo.caddisfly.model;
public enum PageType {
DEFAULT,
PHOTO,
INPUT,
RESULT
}
| 106 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
ReagentType.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/main/java/org/akvo/caddisfly/model/ReagentType.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.model;
import com.google.gson.annotations.SerializedName;
/**
* The different types of reagents.
*/
public enum ReagentType {
@SerializedName("liquid")
LIQUID,
@SerializedName("powder")
POWDER,
@SerializedName("tablet")
TABLET,
@SerializedName("tube")
TUBE,
@SerializedName("none")
NONE
}
| 1,120 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
NetUtil.java | /FileExtraction/Java_unseen/akvo_akvo-caddisfly/caddisfly-app/app/src/tryout/java/org/akvo/caddisfly/util/NetUtil.java | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Caddisfly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.caddisfly.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public final class NetUtil {
private NetUtil() {
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo != null && networkInfo.isConnected();
}
} | 1,330 | Java | .java | akvo/akvo-caddisfly | 12 | 9 | 0 | 2014-10-07T06:55:01Z | 2023-09-20T21:02:30Z |
RootTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/RootTest.java | /*package com.github.cypher;
import com.airhacks.afterburner.injection.Injector;
import RootView;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.junit.Test;
import org.testfx.framework.junit.ApplicationTest;
import java.util.HashMap;
import java.util.Map;
import static org.testfx.api.FxAssert.verifyThat;
import static org.testfx.matcher.control.LabeledMatchers.hasText;
public class RootTest extends ApplicationTest {
@Override
public void start(Stage stage) throws Exception {
Map<Object, Object> customProperties = new HashMap<>();
customProperties.put("n1", 8);
customProperties.put("s1", "test");
Injector.setConfigurationSource(customProperties::get);
RootView rootView = new RootView();
Scene scene = new Scene(rootView.getView());
stage.setScene(scene);
stage.show();
}
@Test
public void injection_test_label() {
// expect:
verifyThat(".label", hasText("test"));
}
}*/
| 929 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
ClientTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/ClientTest.java | package com.github.cypher.sdk;
import org.junit.Test;
import org.junit.Assert;
import java.io.IOException;
import java.util.Map;
public class ClientTest {
ApiMock api = new ApiMock();
Client client = new Client(api, "ex.example.test");
// Test the user cache
@Test
public void getUser() {
// Grab tha same user two times
User u1 = client.getUser("test");
client.getUser("some"); // Some disturbance
User u2 = client.getUser("test");
// Make sure the same object was returned both times
Assert.assertSame(u1, u2);
}
@Test
public void login() throws IOException {
// Initiate resources
api.loggedIn = false;
// login
client.login("user", "pass", "matrix.org");
// Make sure sdk called login method
Assert.assertTrue(api.loggedIn);
}
@Test
public void update() throws IOException {
client.update(1);
// Make sure the correct settings vere loaded
Assert.assertNull(
"Client shouldn't read settings from another namespace",
client.getSetting("other"));
Assert.assertTrue(
"client didn't read setting",
Boolean.parseBoolean(client.getSetting("shouldBeTrue")));
// Make sure rooms were loaded
Assert.assertEquals("Didn't read correct amount of rooms", client.getJoinRooms().size(), 2);
Assert.assertNotNull(client.getJoinRooms().keySet().contains("roomID1"));
Assert.assertNotNull(client.getJoinRooms().keySet().contains("roomID2"));
// Makes sure the SDK can handle since timestamps
client.update(1);
// Make sure setting was updated
Assert.assertFalse(
"client didn't overwrite setting",
Boolean.parseBoolean(client.getSetting("shouldBeTrue")));
// Make sure new rooms were added and old ones not removed
Assert.assertEquals("Didn't read correct amount of rooms", client.getJoinRooms().size(), 4);
Assert.assertNotNull(client.getJoinRooms().keySet().contains("roomID1"));
Assert.assertNotNull(client.getJoinRooms().keySet().contains("roomID2"));
Assert.assertNotNull(client.getJoinRooms().keySet().contains("roomID3"));
Assert.assertNotNull(client.getJoinRooms().keySet().contains("roomID4"));
// Todo: Test presence when it's implemented
// Todo: Test all types of rooms when implemented
}
@Test
public void getPublicRooms() throws IOException {
// Collect rooms
Map rooms = client.getPublicRooms("test");
// Make sure they were collected properly
Assert.assertTrue(rooms.size() == 2);
Assert.assertNotNull(rooms.get("ID1"));
Assert.assertNotNull(rooms.get("ID2"));
}
}
| 2,500 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
ApiMock.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/ApiMock.java | package com.github.cypher.sdk;
import com.github.cypher.sdk.api.ApiLayer;
import com.github.cypher.sdk.api.RestfulHTTPException;
import com.github.cypher.sdk.api.Session;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class ApiMock implements ApiLayer {
boolean loggedIn = false;
boolean textMessageSent = false;
@Override
public JsonObject sync(String filter, String since, boolean fullState, Presence setPresence, int timeout) throws RestfulHTTPException, IOException {
JsonObject data = new JsonObject();
// Emulate since token handeling
if (since == null || since.isEmpty()) {
data.addProperty("next_batch", "Test");
data.add("presence", getPrecenceData());
data.add("rooms", getRoomData());
data.add("account_data", getAccountData());
} else if ("Test".equals(since)) {
data.addProperty("next_batch", "");
data.add("presence", getNewPrecenceData());
data.add("rooms", getNewRoomData());
data.add("account_data", getNewAccountData());
}
return data;
}
private JsonObject getPrecenceData() {
JsonObject data = new JsonObject();
// Todo: Not testable as you cant retrieve users from client yet
return data;
}
private JsonObject getRoomData() {
JsonObject data = new JsonObject();
JsonObject join = new JsonObject();
join.add("roomID1", new JsonObject());
join.add("roomID2", new JsonObject());
data.add("join", join);
// TODO: "leave"-rooms (not implemented yet)
// TODO: "invite"-rooms (not implemented yet)
return data;
}
private JsonObject getAccountData() {
JsonObject data = new JsonObject();
JsonArray events = new JsonArray();
{ // Dummy with other namespace
JsonObject event = new JsonObject();
JsonObject settings = new JsonObject();
settings.addProperty("shouldBeTrue", true);
event.addProperty("type", "ex.example.test");
event.add("content", settings);
events.add(event);
}
{ // Real one
JsonObject event = new JsonObject();
JsonObject settings = new JsonObject();
settings.addProperty("other", true);
event.addProperty("type", "ex.example.noTest");
event.add("content", settings);
events.add(event);
}
data.add("events", events);
return data;
}
private JsonObject getNewPrecenceData() {
JsonObject data = new JsonObject();
// Todo: Not testable as you cant retrieve users from client yet
return data;
}
private JsonObject getNewRoomData() {
JsonObject data = new JsonObject();
JsonObject join = new JsonObject();
join.add("roomID2", new JsonObject());
join.add("roomID3", new JsonObject());
join.add("roomID4", new JsonObject());
data.add("join", join);
// TODO: "leave"-rooms
// TODO: "invite"-rooms
return data;
}
private JsonObject getNewAccountData() {
JsonObject data = new JsonObject();
JsonArray events = new JsonArray();
JsonObject event = new JsonObject();
JsonObject settings = new JsonObject();
settings.addProperty("shouldBeTrue", false);
event.addProperty("type", "ex.example.test");
event.add("content", settings);
events.add(event);
data.add("events", events);
return data;
}
@Override
public JsonObject getPublicRooms(String server) throws RestfulHTTPException, IOException {
JsonObject data = new JsonObject();
JsonArray chunk = new JsonArray();
JsonObject roomData = new JsonObject();
roomData.addProperty("room_id", "ID1");
chunk.add(roomData);
JsonObject roomData2 = new JsonObject();
roomData2.addProperty("room_id", "ID2");
chunk.add(roomData2);
data.add("chunk", chunk);
return data;
}
@Override
public void login(String username, String password, String homeserver) throws RestfulHTTPException, IOException {
if ("user".equals(username) && "pass".equals(password) && "matrix.org".equals(homeserver)) {
loggedIn = true; // Record that it was called and untempered with
}
}
@Override
public void register(String username, String password, String homeserver) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public JsonObject getRoomMessages(String roomId, String from, String to, boolean backward, Integer limit) throws RestfulHTTPException, IOException {
return null;
}
@Override
public JsonObject getRoomMembers(String roomId) throws RestfulHTTPException, IOException {
return null;
}
@Override
public JsonObject getUserProfile(String userId) throws RestfulHTTPException, IOException {
JsonObject response = new JsonObject();
response.addProperty("displayname", "Morpheus");
return response;
}
@Override
public JsonObject getUserAvatarUrl(String userId) throws RestfulHTTPException, IOException {
return null;
}
@Override
public void setUserAvatarUrl(URL avatarUrl) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public JsonObject getUserDisplayName(String userId) throws RestfulHTTPException, IOException {
return null;
}
@Override
public void setUserDisplayName(String displayName) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public JsonArray getUserPresence(String userId) throws IOException {
return null;
}
@Override
public JsonObject roomSendEvent(String roomId, String eventType, JsonObject content) throws RestfulHTTPException, IOException {
if ("!zion:matrix.org".equals(roomId) &&
"m.room.message".equals(eventType) &&
content.has("body") &&
content.has("msgtype") &&
"Down the rabbit hole".equals(content.get("body").getAsString()) &&
"m.text".equals(content.get("msgtype").getAsString())) {
JsonObject response = new JsonObject();
response.addProperty("event_id", "OISAJdiojd8s");
textMessageSent = true;
return response;
}
return null;
}
@Override
public Session getSession() {
return null;
}
@Override
public void setSession(Session session) {
// Not used by the tests
}
@Override
public void logout() throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public void refreshToken() throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public JsonObject getRoomIDFromAlias(String roomAlias) throws MalformedURLException, IOException {
return null;
}
@Override
public JsonObject deleteRoomAlias(String roomAlias) throws RestfulHTTPException, IOException {
return null;
}
@Override
public JsonObject putRoomAlias(String roomAlias, String roomId) throws RestfulHTTPException, IOException {
return null;
}
@Override
public JsonObject postCreateRoom(JsonObject roomCreation) throws RestfulHTTPException, IOException {
return null;
}
@Override
public JsonObject postJoinRoomIdorAlias(String roomId, JsonObject thirdPartySigned) throws RestfulHTTPException, IOException {
return null;
}
@Override
public void postLeaveRoom(String roomId) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public void postKickFromRoom(String roomId, String reason, String userId) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public void postInviteToRoom(String roomId, String address, String idServer, String medium) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public void postInviteToRoom(String roomId, String userId) throws RestfulHTTPException, IOException {
// Not used by the tests
}
@Override
public JsonObject get3Pid() throws RestfulHTTPException, IOException {
return null;
}
@Override
public InputStream getMediaContent(URL mediaUrl) throws RestfulHTTPException, IOException {
return null;
}
@Override
public InputStream getMediaContentThumbnail(URL mediaUrl, int size) throws RestfulHTTPException, IOException {
return null;
}
}
| 7,898 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
UserTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/UserTest.java | package com.github.cypher.sdk;
import com.github.cypher.sdk.api.RestfulHTTPException;
import com.github.cypher.sdk.api.Util;
import com.google.gson.JsonObject;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.URL;
public class UserTest {
private final ApiMock api = new ApiMock();
private final User user = new User(api, "@morpheus:matrix.org");
@Test
public void update() throws RestfulHTTPException, IOException {
// Required to make URL class accept mxc:// protocol
URL.setURLStreamHandlerFactory(new Util.MatrixMediaURLStreamHandlerFactory());
user.update();
Assert.assertEquals(
"User object did not parse display name",
user.getName(),
"Morpheus"
);
}
@Test
public void updateFromSync() {
JsonObject data = new JsonObject();
data.addProperty("type", "m.presence");
JsonObject content = new JsonObject();
content.addProperty("presence", "offline");
data.add("content", content);
user.update(data);
Assert.assertEquals("User object did not parse presence sync data", user.getPresence(), User.Presence.OFFLINE);
}
}
| 1,113 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
RoomTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/RoomTest.java | package com.github.cypher.sdk;
import com.github.cypher.sdk.api.RestfulHTTPException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class RoomTest {
private final ApiMock api = new ApiMock();
private final Room room = new Room(api, new Repository<User>((String id) -> {
return new User(api, id);
}), "!zion:matrix.org");
@Test
public void update() {
JsonObject data = new JsonObject();
data.addProperty("name", "testName");
data.addProperty("topic", "testTopic");
JsonObject timeline = new JsonObject();
JsonArray events = new JsonArray();
{ /* TEST MESSAGE EVENT */
JsonObject event = new JsonObject();
event.addProperty("type", "m.room.message");
event.addProperty("origin_server_ts", 490328209);
event.addProperty("sender", "@trinity:matrix.org");
event.addProperty("event_id", "!sjkdkj2098sdf0:matrix.org");
event.add("content", new JsonObject());
events.add(event);
}
{ /* TEST MEMBER EVENT */
JsonObject event = new JsonObject();
event.addProperty("type", "m.room.member");
event.addProperty("origin_server_ts", 9283578);
event.addProperty("sender", "@morpheus:matrix.org");
event.addProperty("event_id", "!ijxi12o924:matrix.org");
event.addProperty("state_key", "@neo:matrix.org");
JsonObject memberEventContent = new JsonObject();
memberEventContent.addProperty("membership", "join");
event.add("content", memberEventContent);
events.add(event);
}
timeline.add("events", events);
data.add("timeline", timeline);
room.update(data);
Assert.assertEquals("Room failed to process name", "testName", room.getName());
Assert.assertEquals("Room failed to process topic", "testTopic", room.getTopic());
Assert.assertTrue(
"Room failed to process member event",
room.getMembers().stream().anyMatch(m -> m.getUser().getId().equals("@neo:matrix.org"))
);
Assert.assertNotNull(
"Room failed to process message event",
room.getEvents().get("!sjkdkj2098sdf0:matrix.org")
);
}
@Test
public void sendTextMessage() throws RestfulHTTPException, IOException {
api.textMessageSent = false;
room.sendTextMessage("Down the rabbit hole");
Assert.assertTrue("Room did not send text message event", api.textMessageSent);
}
}
| 2,344 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
MessageTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/MessageTest.java | package com.github.cypher.sdk;
import com.google.gson.JsonObject;
import org.junit.Assert;
import org.junit.Test;
public class MessageTest {
@Test
public void createMessage() {
// Build json
JsonObject content = new JsonObject();
content.addProperty("body", "TestBody");
content.addProperty("msgtype", "TestType");
// Create message
Message m = new Message(null, 0, null, null, 0, content);
// Make sure json was processed
Assert.assertEquals("Message contructor failed to read body", "TestBody", m.getBody());
Assert.assertEquals("Message contructor failed to read type", "TestType", m.getType());
}
}
| 630 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
UtilTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/api/UtilTest.java | package com.github.cypher.sdk.api;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class UtilTest {
@Test
public void UrlBuilder() {
// Different scenarios
List<Map<String, String>> maps = new LinkedList<>();
Map<String, String> map;
map = new HashMap<>(1);
map.put("av", "23");
maps.add(map);
map = new HashMap<>(2);
map.put("av", "23");
map.put("ab", "true");
maps.add(map);
try{
assertEquals(
"UrlBuilder must build correct URL with one argument",
"https://matrix.org/_matrix/client/r0/login?av=23",
Util.UrlBuilder("matrix.org", Endpoint.LOGIN, null, maps.get(0)).toString()
);
assertEquals(
"UrlBuilder must build correct URL with no arguments",
"https://matrix.org/_matrix/client/r0/login",
Util.UrlBuilder("matrix.org", Endpoint.LOGIN, null, null).toString()
);
assertEquals(
"UrlBuilder must build correct URL with no arguments",
"https://matrix.org/_matrix/client/r0/rooms/%21cURbafjkfsMDVwdRDQ%3Amatrix.org/messages",
Util.UrlBuilder("matrix.org", Endpoint.ROOM_MESSAGES, new Object[] {"!cURbafjkfsMDVwdRDQ:matrix.org"}, null).toString()
);
assertEquals(
"UrlBuilder must build correct URL with multiple arguments",
"https://matrix.org/_matrix/client/r0/rooms/%21cURbafjkfsMDVwdRDQ%3Amatrix.org/messages?av=23&ab=true",
Util.UrlBuilder("matrix.org", Endpoint.ROOM_MESSAGES, new Object[] {"!cURbafjkfsMDVwdRDQ:matrix.org"}, maps.get(1)).toString()
);
}catch (MalformedURLException e) {
assertFalse(e.getMessage(), true);
}
}
}
| 1,764 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
SessionTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/api/SessionTest.java | package com.github.cypher.sdk.api;
import com.google.gson.JsonObject;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class SessionTest {
@Test
public void constructorParsing(){
// Crate lacking json object
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("user_id", "234");
jsonObject.addProperty("home_server", "matrix.org");
jsonObject.addProperty("refresh_token", "adj08aj9821321h9");
jsonObject.addProperty("device_id", "123");
// Make sure lacking object fails
boolean passedCreation;
try {
new Session(jsonObject);
passedCreation = true;
}catch (IOException err){
passedCreation = false;
}
assertFalse("Parsing should fail without access_token", passedCreation);
// Complete Object
jsonObject.addProperty("access_token", "555");
// Make sure complete object works
try{
Session s = new Session(jsonObject);
assertEquals("Access token should be 555", "555", s.getAccessToken());
assertEquals("Device id should be 123", "123", s.getDeviceId());
assertEquals("Homeserver should be matrix.org", "matrix.org", s.getHomeServer());
assertEquals("User id should be 234", "234", s.getUserId());
}catch (IOException err){
assertFalse("Parsing should not fail with all properties set", true);
}
}
}
| 1,384 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
EndpointTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/api/EndpointTest.java | package com.github.cypher.sdk.api;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class EndpointTest {
@Test
public void EndpointValues(){
// Make sure all endpoint build correct URL's
try {
for(Endpoint endpoint : Endpoint.values()){
new URL("https://matrix.org".concat(endpoint.toString()));
}
}catch (MalformedURLException e){
assertFalse(e.getMessage(), true);
}
}
}
| 487 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
RestfulHTTPExceptionTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/sdk/api/RestfulHTTPExceptionTest.java | package com.github.cypher.sdk.api;
import com.google.gson.JsonObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class RestfulHTTPExceptionTest {
@Rule
public ExpectedException expectedEc1 = ExpectedException.none();
@Test
public void ContructorWithOneJsonArgument(){
// Build json
JsonObject jObj = new JsonObject();
jObj.addProperty("errcode", "some_Error_Code");
// What to expect
expectedEc1.expect(RestfulHTTPException.class);
expectedEc1.expectMessage("some_Error_Code");
expectedEc1.expectMessage("400");
throw new RestfulHTTPException(400, jObj);
}
@Test
public void ContructorWithTwoJsonArguments(){
// Build json
JsonObject jObj = new JsonObject();
jObj.addProperty("errcode", "some_Error_Code");
jObj.addProperty("error", "SomeOtherError");
// What to Expect
expectedEc1.expect(RestfulHTTPException.class);
expectedEc1.expectMessage("400");
expectedEc1.expectMessage("SomeOtherError");
throw new RestfulHTTPException(400, jObj);
}
@Test
public void ContructorWithNoJsonArguments(){
// Build json
JsonObject jObj = new JsonObject();
// What to Expect
expectedEc1.expect(RestfulHTTPException.class);
expectedEc1.expectMessage("400");
throw new RestfulHTTPException(400, jObj);
}
}
| 1,315 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
ExecutorTest.java | /FileExtraction/Java_unseen/williamleven_Cypher/src/test/java/com/github/cypher/gui/ExecutorTest.java | package com.github.cypher.gui;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ExecutorTest {
@Test
public void executorTest() {
// Create and start executor
Executor executor = new Executor();
executor.start();
// Queue actions
final BooleanProperty action1 = new SimpleBooleanProperty(false);
executor.handle(() -> {
action1.set(true);
});
final BooleanProperty isSeparateThread = new SimpleBooleanProperty(false);
long testThread = Thread.currentThread().getId();
executor.handle(() -> {
isSeparateThread.setValue(Thread.currentThread().getId() != testThread);
});
// Wait for action to be done
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
executor.interrupt();
// Check if action were done
assertTrue("Executor didn't execute.", action1.get());
// Does not work on Travis:
// assertTrue("Executor doesn't seem to be running in its own thread", isSeparateThread.get());
}
}
| 1,081 | Java | .java | williamleven/Cypher | 8 | 1 | 0 | 2017-03-20T10:42:03Z | 2017-10-22T22:59:11Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.