(3);
IGNORED_CLASS_NAMES.add("dalvik.system.VMStack");
IGNORED_CLASS_NAMES.add("java.lang.Thread");
IGNORED_CLASS_NAMES.add(Logger.class.getCanonicalName());
}
private final String tag;
private final String messagePrefix;
private int minLogLevel = DEFAULT_MIN_LOG_LEVEL;
/**
* Creates a Logger using the class name as the message prefix.
*
* @param clazz the simple name of this class is used as the message prefix.
*/
public Logger(final Class> clazz) {
this(clazz.getSimpleName());
}
/**
* Creates a Logger using the specified message prefix.
*
* @param messagePrefix is prepended to the text of every message.
*/
public Logger(final String messagePrefix) {
this(DEFAULT_TAG, messagePrefix);
}
/**
* Creates a Logger with a custom tag and a custom message prefix. If the message prefix is set to
*
* null
*
* , the caller's class name is used as the prefix.
*
* @param tag identifies the source of a log message.
* @param messagePrefix prepended to every message if non-null. If null, the name of the caller is
* being used
*/
public Logger(final String tag, final String messagePrefix) {
this.tag = tag;
final String prefix = messagePrefix == null ? getCallerSimpleName() : messagePrefix;
this.messagePrefix = (prefix.length() > 0) ? prefix + ": " : prefix;
}
/** Creates a Logger using the caller's class name as the message prefix. */
public Logger() {
this(DEFAULT_TAG, null);
}
/** Creates a Logger using the caller's class name as the message prefix. */
public Logger(final int minLogLevel) {
this(DEFAULT_TAG, null);
this.minLogLevel = minLogLevel;
}
/**
* Return caller's simple name.
*
* Android getStackTrace() returns an array that looks like this: stackTrace[0]:
* dalvik.system.VMStack stackTrace[1]: java.lang.Thread stackTrace[2]:
* com.google.android.apps.unveil.env.UnveilLogger stackTrace[3]:
* com.google.android.apps.unveil.BaseApplication
*
*
This function returns the simple version of the first non-filtered name.
*
* @return caller's simple name
*/
private static String getCallerSimpleName() {
// Get the current callstack so we can pull the class of the caller off of it.
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (final StackTraceElement elem : stackTrace) {
final String className = elem.getClassName();
if (!IGNORED_CLASS_NAMES.contains(className)) {
// We're only interested in the simple name of the class, not the complete package.
final String[] classParts = className.split("\\.");
return classParts[classParts.length - 1];
}
}
return Logger.class.getSimpleName();
}
public void setMinLogLevel(final int minLogLevel) {
this.minLogLevel = minLogLevel;
}
public boolean isLoggable(final int logLevel) {
return logLevel >= minLogLevel || Log.isLoggable(tag, logLevel);
}
private String toMessage(final String format, final Object... args) {
return messagePrefix + (args.length > 0 ? String.format(format, args) : format);
}
public void v(final String format, final Object... args) {
if (isLoggable(Log.VERBOSE)) {
Log.v(tag, toMessage(format, args));
}
}
public void v(final Throwable t, final String format, final Object... args) {
if (isLoggable(Log.VERBOSE)) {
Log.v(tag, toMessage(format, args), t);
}
}
public void d(final String format, final Object... args) {
if (isLoggable(Log.DEBUG)) {
Log.d(tag, toMessage(format, args));
}
}
public void d(final Throwable t, final String format, final Object... args) {
if (isLoggable(Log.DEBUG)) {
Log.d(tag, toMessage(format, args), t);
}
}
public void i(final String format, final Object... args) {
if (isLoggable(Log.INFO)) {
Log.i(tag, toMessage(format, args));
}
}
public void i(final Throwable t, final String format, final Object... args) {
if (isLoggable(Log.INFO)) {
Log.i(tag, toMessage(format, args), t);
}
}
public void w(final String format, final Object... args) {
if (isLoggable(Log.WARN)) {
Log.w(tag, toMessage(format, args));
}
}
public void w(final Throwable t, final String format, final Object... args) {
if (isLoggable(Log.WARN)) {
Log.w(tag, toMessage(format, args), t);
}
}
public void e(final String format, final Object... args) {
if (isLoggable(Log.ERROR)) {
Log.e(tag, toMessage(format, args));
}
}
public void e(final Throwable t, final String format, final Object... args) {
if (isLoggable(Log.ERROR)) {
Log.e(tag, toMessage(format, args), t);
}
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/detection/env/Size.java
================================================
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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 com.helloworld.goodpoint.detection.env;
import android.graphics.Bitmap;
import android.text.TextUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/** Size class independent of a Camera object. */
public class Size implements Comparable, Serializable {
// 1.4 went out with this UID so we'll need to maintain it to preserve pending queries when
// upgrading.
public static final long serialVersionUID = 7689808733290872361L;
public final int width;
public final int height;
public Size(final int width, final int height) {
this.width = width;
this.height = height;
}
public Size(final Bitmap bmp) {
this.width = bmp.getWidth();
this.height = bmp.getHeight();
}
/**
* Rotate a size by the given number of degrees.
*
* @param size Size to rotate.
* @param rotation Degrees {0, 90, 180, 270} to rotate the size.
* @return Rotated size.
*/
public static Size getRotatedSize(final Size size, final int rotation) {
if (rotation % 180 != 0) {
// The phone is portrait, therefore the camera is sideways and frame should be rotated.
return new Size(size.height, size.width);
}
return size;
}
public static Size parseFromString(String sizeString) {
if (TextUtils.isEmpty(sizeString)) {
return null;
}
sizeString = sizeString.trim();
// The expected format is "x".
final String[] components = sizeString.split("x");
if (components.length == 2) {
try {
final int width = Integer.parseInt(components[0]);
final int height = Integer.parseInt(components[1]);
return new Size(width, height);
} catch (final NumberFormatException e) {
return null;
}
} else {
return null;
}
}
public static List sizeStringToList(final String sizes) {
final List sizeList = new ArrayList();
if (sizes != null) {
final String[] pairs = sizes.split(",");
for (final String pair : pairs) {
final Size size = Size.parseFromString(pair);
if (size != null) {
sizeList.add(size);
}
}
}
return sizeList;
}
public static String sizeListToString(final List sizes) {
String sizesString = "";
if (sizes != null && sizes.size() > 0) {
sizesString = sizes.get(0).toString();
for (int i = 1; i < sizes.size(); i++) {
sizesString += "," + sizes.get(i).toString();
}
}
return sizesString;
}
public static final String dimensionsAsString(final int width, final int height) {
return width + "x" + height;
}
public final float aspectRatio() {
return (float) width / (float) height;
}
@Override
public int compareTo(final Size other) {
return width * height - other.width * other.height;
}
@Override
public boolean equals(final Object other) {
if (other == null) {
return false;
}
if (!(other instanceof Size)) {
return false;
}
final Size otherSize = (Size) other;
return (width == otherSize.width && height == otherSize.height);
}
@Override
public int hashCode() {
return width * 32713 + height;
}
@Override
public String toString() {
return dimensionsAsString(width, height);
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/detection/tracking/MultiBoxTracker.java
================================================
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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 com.helloworld.goodpoint.detection.tracking;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.Pair;
import android.util.TypedValue;
import com.example.lib_task_api.Detector.Recognition;
import com.helloworld.goodpoint.detection.env.BorderedText;
import com.helloworld.goodpoint.detection.env.ImageUtils;
import com.helloworld.goodpoint.detection.env.Logger;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/** A tracker that handles non-max suppression and matches existing objects to new detections. */
public class MultiBoxTracker {
private static final float TEXT_SIZE_DIP = 10;
private static final float MIN_SIZE = 16.0f;
private static final int[] COLORS = {
Color.BLUE,
Color.RED,
Color.GREEN,
Color.YELLOW,
Color.CYAN,
Color.MAGENTA,
Color.WHITE,
Color.parseColor("#55FF55"),
Color.parseColor("#FFA500"),
Color.parseColor("#FF8888"),
Color.parseColor("#AAAAFF"),
Color.parseColor("#FFFFAA"),
Color.parseColor("#55AAAA"),
Color.parseColor("#AA33AA"),
Color.parseColor("#0D0068")
};
final List> screenRects = new LinkedList>();
private final Logger logger = new Logger();
private final Queue availableColors = new LinkedList();
private final List trackedObjects = new LinkedList();
private final Paint boxPaint = new Paint();
private final float textSizePx;
private final BorderedText borderedText;
private Matrix frameToCanvasMatrix;
private int frameWidth;
private int frameHeight;
private int sensorOrientation;
public MultiBoxTracker(final Context context) {
for (final int color : COLORS) {
availableColors.add(color);
}
boxPaint.setColor(Color.RED);
boxPaint.setStyle(Style.STROKE);
boxPaint.setStrokeWidth(10.0f);
boxPaint.setStrokeCap(Cap.ROUND);
boxPaint.setStrokeJoin(Join.ROUND);
boxPaint.setStrokeMiter(100);
textSizePx =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, context.getResources().getDisplayMetrics());
borderedText = new BorderedText(textSizePx);
}
public synchronized void setFrameConfiguration(
final int width, final int height, final int sensorOrientation) {
frameWidth = width;
frameHeight = height;
this.sensorOrientation = sensorOrientation;
}
public synchronized void drawDebug(final Canvas canvas) {
final Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(60.0f);
final Paint boxPaint = new Paint();
boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Style.STROKE);
for (final Pair detection : screenRects) {
final RectF rect = detection.second;
canvas.drawRect(rect, boxPaint);
canvas.drawText("" + detection.first, rect.left, rect.top, textPaint);
borderedText.drawText(canvas, rect.centerX(), rect.centerY(), "" + detection.first);
}
}
public synchronized void trackResults(final List results, final long timestamp) {
logger.i("Processing %d results from %d", results.size(), timestamp);
processResults(results);
}
private Matrix getFrameToCanvasMatrix() {
return frameToCanvasMatrix;
}
public synchronized void draw(final Canvas canvas) {
final boolean rotated = sensorOrientation % 180 == 90;
final float multiplier =
Math.min(
canvas.getHeight() / (float) (rotated ? frameWidth : frameHeight),
canvas.getWidth() / (float) (rotated ? frameHeight : frameWidth));
frameToCanvasMatrix =
ImageUtils.getTransformationMatrix(
frameWidth,
frameHeight,
(int) (multiplier * (rotated ? frameHeight : frameWidth)),
(int) (multiplier * (rotated ? frameWidth : frameHeight)),
sensorOrientation,
false);
for (final TrackedRecognition recognition : trackedObjects) {
final RectF trackedPos = new RectF(recognition.location);
getFrameToCanvasMatrix().mapRect(trackedPos);
boxPaint.setColor(recognition.color);
float cornerSize = Math.min(trackedPos.width(), trackedPos.height()) / 8.0f;
canvas.drawRoundRect(trackedPos, cornerSize, cornerSize, boxPaint);
// final String labelString =
// !TextUtils.isEmpty(recognition.title)
// ? String.format("%s %.2f", recognition.title, (100 * recognition.detectionConfidence))
// : String.format("%.2f", (100 * recognition.detectionConfidence));
final String labelString =
!TextUtils.isEmpty(recognition.title)
? String.format("%s %s", recognition.title,"" )
: "";
// borderedText.drawText(canvas, trackedPos.left + cornerSize, trackedPos.top,
// labelString);
borderedText.drawText(
canvas, trackedPos.left + cornerSize, trackedPos.top, labelString, boxPaint);
}
}
private void processResults(final List results) {
final List> rectsToTrack = new LinkedList>();
screenRects.clear();
final Matrix rgbFrameToScreen = new Matrix(getFrameToCanvasMatrix());
for (final Recognition result : results) {
if (result.getLocation() == null) {
continue;
}
final RectF detectionFrameRect = new RectF(result.getLocation());
final RectF detectionScreenRect = new RectF();
rgbFrameToScreen.mapRect(detectionScreenRect, detectionFrameRect);
logger.v(
"Result! Frame: " + result.getLocation() + " mapped to screen:" + detectionScreenRect);
screenRects.add(new Pair(result.getConfidence(), detectionScreenRect));
if (detectionFrameRect.width() < MIN_SIZE || detectionFrameRect.height() < MIN_SIZE) {
logger.w("Degenerate rectangle! " + detectionFrameRect);
continue;
}
rectsToTrack.add(new Pair(result.getConfidence(), result));
}
trackedObjects.clear();
if (rectsToTrack.isEmpty()) {
logger.v("Nothing to track, aborting.");
return;
}
for (final Pair potential : rectsToTrack) {
final TrackedRecognition trackedRecognition = new TrackedRecognition();
trackedRecognition.detectionConfidence = potential.first;
trackedRecognition.location = new RectF(potential.second.getLocation());
trackedRecognition.title = potential.second.getTitle();
trackedRecognition.color = COLORS[trackedObjects.size()];
trackedObjects.add(trackedRecognition);
if (trackedObjects.size() >= COLORS.length) {
break;
}
}
}
private static class TrackedRecognition {
RectF location;
float detectionConfidence;
int color;
String title;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/FoundItem.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FoundItem {
public FoundItem(String type, String serial_number, String brand, String color) {
this.type = type;
this.serial_number = serial_number;
this.brand = brand;
this.color = color;
}
@SerializedName("user_id")
@Expose
private String user_id;
@SerializedName("id")
@Expose
private String id;
@SerializedName("date")
@Expose
private String date;
@SerializedName("city")
@Expose
private String city;
@SerializedName("type")
@Expose
private String type;
@SerializedName("serial_number")
@Expose
private String serial_number;
@Expose
@SerializedName("brand")
private String brand;
@SerializedName("color")
@Expose
private String color;
@SerializedName("description")
@Expose
private String description;
/* public FoundItem(int user_id, int id, String date, String city, String type, String serial_number, String brand, String color, String description) {
this.id = id;
this.user_id = user_id;
this.date = date;
this.city = city;
this.type = type;
this.serial_number = serial_number;
this.brand = brand;
this.color = color;
this.description = description;
}*/
private static FoundItem FoundItem;
public static FoundItem getFoundItem()
{
if (FoundItem == null) {
FoundItem = new FoundItem();
}
return FoundItem;
}
private FoundItem()
{
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public void setDate(String date) {
this.date = date;
}
public String getDate() { return date; }
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSerial_number() {
return serial_number;
}
public void setSerial_number(String serial_number) {
this.serial_number = serial_number;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/FoundPerson.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FoundPerson {
@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
private double longitude;
private double latitude;
private String date;
private String city;
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
private static FoundPerson FoundPerson;
public static FoundPerson getFoundPerson()
{
if (FoundPerson == null) {
FoundPerson = new FoundPerson();
}
return FoundPerson;
}
private FoundPerson()
{
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/LostItem.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class LostItem {
public LostItem(String type, String serial_number, String brand, String color, String description) {
this.type = type;
this.serial_number = serial_number;
this.brand = brand;
this.color = color;
this.description = description;
}
public LostItem(String type, String serial_number, String brand, String color) {
this.type = type;
this.serial_number = serial_number;
this.brand = brand;
this.color = color;
}
@SerializedName("user_id")
@Expose
private String user_id;
@SerializedName("id")
@Expose
private String id;
@SerializedName("date")
@Expose
private String date;
@SerializedName("city")
@Expose
private String city;
@SerializedName("type")
@Expose
private String type;
@SerializedName("serial_number")
@Expose
private String serial_number;
@Expose
@SerializedName("brand")
private String brand;
@SerializedName("color")
@Expose
private String color;
@SerializedName("description")
@Expose
private String description;
/* public LostItem(int user_id, int id, String date, String city, String type, String serial_number, String brand, String color, String description) {
this.id = id;
this.user_id = user_id;
this.date = date;
this.city = city;
this.type = type;
this.serial_number = serial_number;
this.brand = brand;
this.color = color;
this.description = description;
}*/
private static LostItem lostItem;
public static LostItem getLostItem()
{
if (lostItem == null) {
lostItem = new LostItem();
}
return lostItem;
}
private LostItem()
{
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public void setDate(String date) {
this.date = date;
}
public String getDate() { return date; }
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSerial_number() {
return serial_number;
}
public void setSerial_number(String serial_number) {
this.serial_number = serial_number;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/LostObject.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class LostObject {
@SerializedName("id")
@Expose
private int id;
@SerializedName("user_id")
@Expose
private String user_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@SerializedName("date")
@Expose
private String date;
@SerializedName("city")
@Expose
private String city;
public LostObject(String user_id, String date, String city) {
this.user_id = user_id;
this.date = date;
this.city = city;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/LostPerson.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class LostPerson {
@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
private String date;
private String city;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
private static LostPerson lostPerson;
public static LostPerson getLostPerson()
{
if (lostPerson == null) {
lostPerson = new LostPerson();
}
return lostPerson;
}
private LostPerson()
{
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/NotificationItem.java
================================================
package com.helloworld.goodpoint.pojo;
import android.content.Intent;
import android.graphics.Bitmap;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
public class NotificationItem {
@SerializedName("id")
@Expose
String id;
@SerializedName("title")
@Expose
String title;
@SerializedName("description")
@Expose
String description;
@SerializedName("type")
@Expose
int type;
@SerializedName("date_time")
@Expose
Date date;
@SerializedName("is_sent")
@Expose
boolean sent;
@SerializedName("is_read")
@Expose
boolean read;
@SerializedName("user_id")
@Expose
int userId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public boolean isSent() {
return sent;
}
public void setSent(boolean sent) {
this.sent = sent;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/ObjectLocation.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ObjectLocation {
@SerializedName("longitude")
@Expose
double longitude;
@SerializedName("latitude")
@Expose
double latitude;
@SerializedName("user_id")
@Expose
int userId;
public ObjectLocation(double longitude, double latitude, int userId) {
this.userId = userId;
this.longitude = longitude;
this.latitude = latitude;
}
public int getUserId() {
return userId;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/RegUser.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RegUser {
@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;
@SerializedName("first_name")
@Expose
private String first_name;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("city")
@Expose
private String city;
@SerializedName("birthdate")
@Expose
private String birthdate;
@SerializedName("profile_pic")
@Expose
private String profile_pic;
public RegUser(String username, String password, String first_name, String phone, String city, String birthdate, String profile_pic) {
this.username = username;
this.password = password;
this.first_name = first_name;
this.phone = phone;
this.city = city;
this.birthdate = birthdate;
this.profile_pic = profile_pic;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
/*public String getProfile_pic() { return profile_pic; }
public void setProfile_pic(String profile_pic) { this.profile_pic = profile_pic; }*/
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/Token.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Token {
@SerializedName("refresh")
@Expose
private String refresh;
@SerializedName("access")
@Expose
private String access;
private static Token token;
public static Token getToken(){
if(token == null){
token = new Token();
}
return token;
}
public Token( String refresh, String access) {
this.refresh = refresh;
this.access = access;
}
public Token() {
}
public String getRefresh() {
return refresh;
}
public void setRefresh(String refresh) {
this.refresh = refresh;
}
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/User.java
================================================
package com.helloworld.goodpoint.pojo;
import android.graphics.Bitmap;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class User {
@SerializedName("id")
@Expose
private String id;
@SerializedName("username")
@Expose
private String username;
@SerializedName("email")
@Expose
private String email;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("city")
@Expose
private String city;
@SerializedName("birthdate")
@Expose
private String birthdate;
@SerializedName("profile_pic")
@Expose
private String profile_pic;
@SerializedName("id_card_pic")
@Expose
private String id_card_pic;
@SerializedName("losts")
@Expose
Listlosts;
@SerializedName("founds")
@Expose
Listfounds;
private Bitmap profile_bitmap;
List foundItem;
private static User user;
public static User getUser()
{
if (user == null) {
user = new User();
user.losts = new ArrayList<>();
user.founds = new ArrayList<>();
user.foundItem = new ArrayList<>();
}
return user;
}
public static void userLogout(){
user = null;
}
public List getLosts() {
return losts;
}
public List getFounds() {
return founds;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) { this.birthdate = birthdate; }
public String getProfile_pic() { return profile_pic; }
public void setProfile_pic(String profile_pic) { this.profile_pic = profile_pic; }
public Bitmap getProfile_bitmap() {
return profile_bitmap;
}
public void setProfile_bitmap(Bitmap profile_bitmap) {
this.profile_bitmap = profile_bitmap;
}
public String getId_card_pic() {
return id_card_pic;
}
public void setId_card_pic(String id_card_pic) {
this.id_card_pic = id_card_pic;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/pojo/UserMap.java
================================================
package com.helloworld.goodpoint.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UserMap {
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("phone")
@Expose
private String phone;
public UserMap(String name, String email, String phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/retrofit/ApiClient.java
================================================
package com.helloworld.goodpoint.retrofit;
import android.util.Log;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class ApiClient {
//base url
private static String BASE_URL ;
private static Retrofit retrofit = null;
//Create Builder ...
public static Retrofit getApiClient(String link) {
BASE_URL = link;
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/retrofit/ApiInterface.java
================================================
package com.helloworld.goodpoint.retrofit;
import com.google.gson.JsonObject;
import com.helloworld.goodpoint.pojo.FoundItem;
import com.helloworld.goodpoint.pojo.FoundPerson;
import com.helloworld.goodpoint.pojo.LostItem;
import com.helloworld.goodpoint.pojo.LostObject;
import com.helloworld.goodpoint.pojo.LostPerson;
import com.helloworld.goodpoint.pojo.NotificationItem;
import com.helloworld.goodpoint.pojo.ObjectLocation;
import com.helloworld.goodpoint.pojo.RegUser;
import com.helloworld.goodpoint.pojo.Token;
import com.helloworld.goodpoint.pojo.UserMap;
import java.util.List;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface ApiInterface {
@FormUrlEncoded
@POST("auth/signup/")
Call storePost(@Field("username") String emailInput
, @Field("password") String passwordInput, @Field("first_name") String usernameInput
, @Field("phone") String pInput, @Field("city") String cityInput
, @Field("birthdate") String Datee);
@Multipart
@POST("auth/signup/")
Call storePost(@Part("username") String emailInput
, @Part("password") String passwordInput, @Part("first_name") String usernameInput
, @Part("phone") String pInput, @Part("city") String cityInput
, @Part("birthdate") String Datee, @Part MultipartBody.Part profile_pic);
@FormUrlEncoded
@POST("api/token/")
Call getToken(@Field("username") String emailInput, @Field("password") String passwordInput);
@FormUrlEncoded
@POST("api/token/refresh/")
Call refresh(@Field("refresh") String refresh);
@POST("auth/signin/")
Call getData(@Header("Authorization") String token);
@Multipart
@PATCH("auth/setidcard/")
Call setIdCard(@Header("Authorization") String token, @Part MultipartBody.Part image);
//----------------------------------------------------------------------------------------------
@FormUrlEncoded
@POST("losts/lostobject/")
Call storeLostObj(@Field("user_id") String id, @Field("date") String Datee, @Field("city") String cityInput);
@FormUrlEncoded
@POST("losts/lostitem/")
Call storeLostItem(@Field("id") String obj_id, @Field("type") String Type, @Field("serial_number") String Serial
, @Field("brand") String brand, @Field("color") String ObjectColor
, @Field("description") String textArea_information);
@Multipart
@POST("losts/lostitem/")
Call storeLostItem(@Part("id") String obj_id, @Part("type") String Type, @Part("serial_number") String Serial
, @Part("brand") String brand, @Part("color") String ObjectColor
, @Part("description") String textArea_information, @Part MultipartBody.Part image);
@Multipart
@POST("losts/lostperson/")
Call storeLostPerson(@Part("date") String Date, @Part("city") String city, @Part("user_id") String user_id
, @Part("name") String name, @Part MultipartBody.Part images);
//----------------------------------------------------------------------------------------------
@FormUrlEncoded
@POST("losts/foundobject/")
Call storeFoundObj(@Field("user_id") String id, @Field("date") String Datee, @Field("city") String cityInput
, @Field("longitude") double longitude, @Field("latitude") double latitude);
@FormUrlEncoded
@POST("losts/founditem/")
Call storeFoundItem(@Field("id") String obj_id, @Field("type") String Type, @Field("serial_number") String Serial
, @Field("brand") String brand, @Field("color") String ObjectColor
, @Field("description") String textArea_information);
@Multipart
@POST("losts/foundperson/")
Call storeFoundPerson(@Part("user_id") String user_id, @Part("date") String Date, @Part("city") String city
, @Part("longitude") double longitude, @Part("latitude") double latitude, @Part("name") String name, @Part MultipartBody.Part pimage);
//----------------------------------------------------------------------------------------------
@GET("losts/map/")
Call> getPoint();
@GET("losts/founder/{id}")
Call getUserMap(@Path("id") int id);
//---------------------------------------------------------------------------------------------
@GET("losts/lostobject/{id}")
Call getObject(@Path("id") String id);
@GET("losts/LostItemFilter/")
Call> getLItem(@Query("type")String type);
@GET("losts/LostItemFilter/")
Call> getLostItem(@Query("id") int id);
@GET("losts/lost_person/id={id}/")
Call getLostPerson(@Path("id") int id);
@GET("losts/found_person/id={id}/")
Call getFoundPerson(@Path("id") int id);
@GET("losts/FoundItemFilter/")
Call> getFoundItem(@Query("id") int id);
//------------------------------------------------------------------------------------
@FormUrlEncoded
@POST("notification/")
Call storeNotification(@Field("user_id") String id, @Field("title") String title
, @Field("description") String description
, @Field("type") int type);
@GET("notification/user_id={id}/")
Call> getNotification(@Path("id") String user_id);
@FormUrlEncoded
@PATCH("notification/read/{id}/")
Call updateRead(@Path("id") String id, @Field("is_read") Boolean read);
@FormUrlEncoded
@PATCH("notification/sent/{id}/")
Call updateSent(@Path("id") String id, @Field("is_sent") Boolean sent);
@GET("notification/new/{user_id}/")
Call> getNewNotification(@Path("user_id") String user_id);
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/retrofit/Decode.java
================================================
package com.helloworld.goodpoint.retrofit;
import android.util.Base64;
import android.util.Log;
import java.io.UnsupportedEncodingException;
public class Decode {
private static String[] split;
public static String decoded(String JWTEncoded) throws Exception {
split = JWTEncoded.split("\\.");
Log.d("JWT_DECODED", "Header: " + getJson(split[0]));
Log.d("JWT_DECODED", "Body: " + getJson(split[1]));
Log.d("JWT_DECODED", "Signiture: " + getJson(split[2]));
return getJson(split[1]);
}
private static String getJson(String strEncoded) throws UnsupportedEncodingException {
byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE);
return new String(decodedBytes, "UTF-8");
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/ActionActivity.java
================================================
package com.helloworld.goodpoint.ui;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.ui.lostFoundObject.LostObjectDetailsActivity;
public class ActionActivity extends AppCompatActivity {
Button lost;
Button found;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lost = (Button) findViewById(R.id.button_lost);
found = (Button) findViewById(R.id.button_found);
}
public void lost_btn(View v){
startActivity(new Intent(ActionActivity.this, LostObjectDetailsActivity.class));
}
public void found_btn(View v){
startActivity(new Intent(ActionActivity.this, LostObjectDetailsActivity.class));
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/AdapterOfMatchFragment.java
================================================
package com.helloworld.goodpoint.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.helloworld.goodpoint.R;
public class AdapterOfMatchFragment extends ArrayAdapter {
private Context context;
private String Rtitle[];
private String Rstatus[];
private int Rimg[];
//String ObjStat[] ={},ObjDetails;
String status[]={"Has found" ,"Its owner has been found","Has found" ,"Its owner has been found",
"Has found" ,"Its owner has been found","Has found" ,"Its owner has been found" } ;
public AdapterOfMatchFragment(@NonNull Context context, String[] Rstatus) {
super(context, R.layout.row,Rstatus);
this.context = context;
//this.Rtitle = Rtitle;
this.Rstatus = Rstatus;
// this.Rimg = Rimg;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View r = convertView;
viewHolder viewholder =null;
if(r == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
r = layoutInflater.inflate(R.layout.row,null,true);
viewholder = new viewHolder(r);
r.setTag(viewholder);
}
else{
viewholder = (viewHolder) r.getTag();
}
viewholder.imageView.setImageResource(R.drawable.ic_baseline_gallery_24);
viewholder.stat.setText(status[position]);
viewholder.details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
context.startActivity(new Intent(context, DetailsActivity.class));
}
});
return r;
}
class viewHolder{
private ImageView imageView;
private TextView stat, details;
viewHolder(View v){
imageView = v.findViewById(R.id.obj);
stat = v.findViewById(R.id.status);
details = v.findViewById(R.id.details);
}
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/Alert.java
================================================
package com.helloworld.goodpoint.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.ui.select_multiple_faces.Selection;
public class Alert extends AppCompatActivity {
private Button next_btn;
private TextView text;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
next_btn = (Button) findViewById(R.id.login_btn);
text=(TextView)findViewById(R.id.text);
i=GlobalVar.ImgThatHaveMoreThanOneFace.size();
text.setText("There are ("+ i+ ") images that have multiple faces so press next to select only face ");
next_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Alert.this, Selection.class));
finish();
}
});
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/DetailsActivity.java
================================================
package com.helloworld.goodpoint.ui;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.helloworld.goodpoint.R;
public class DetailsActivity extends AppCompatActivity implements View.OnClickListener {
private static final int CALL_CODE = 1;
TextView main,sub,name,brand,color,addr,dlost,dfound,mname,mail,phone;
LinearLayout subLayout,nameLayout,brandLayout,colorLayout,addrLayout,matchLayout;
ImageView img;
Button call,sendMail;
private int id;
private int type;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
marginOrientation();
init();
// updateTable();
sendMail.setOnClickListener(this);
subLayout.setVisibility(View.GONE);
colorLayout.setVisibility(View.GONE);
brandLayout.setVisibility(View.GONE);
call.setOnClickListener(this);
}
private void updateTable() {
switch (type){
case 1:
subLayout.setVisibility(View.GONE);
brandLayout.setVisibility(View.GONE);
colorLayout.setVisibility(View.GONE);
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
}
}
private void init() {
main = findViewById(R.id.main_cat);
sub = findViewById(R.id.item_cat);
name = findViewById(R.id.lost_name);
brand = findViewById(R.id.brand_name);
color = findViewById(R.id.color_item);
addr = findViewById(R.id.address);
dlost = findViewById(R.id.date_of_lost);
dfound = findViewById(R.id.date_of_found);
mname = findViewById(R.id.name_of_matching);
mail = findViewById(R.id.mail_of_matching);
phone = findViewById(R.id.phone_of_matching);
subLayout = findViewById(R.id.sub_cat);
nameLayout = findViewById(R.id.person_name);
brandLayout = findViewById(R.id.brand_detail);
colorLayout = findViewById(R.id.color_detail);
addrLayout = findViewById(R.id.addr_loc);
matchLayout = findViewById(R.id.matched_detail);
img = findViewById(R.id.img_detail);
call = findViewById(R.id.call_btn);
sendMail = findViewById(R.id.mail_btn);
// id = getIntent().getIntExtra("id",0);
// type = getIntent().getIntExtra("type",0);
}
private void marginOrientation() {
int orientation = getResources().getConfiguration().orientation;
if(orientation == Configuration.ORIENTATION_LANDSCAPE){
LinearLayout layout = findViewById(R.id.parent_table_details);
LinearLayout.MarginLayoutParams layoutParams = (LinearLayout.MarginLayoutParams) layout.getLayoutParams();
float ver = getResources().getDimension(R.dimen._5sdp);
float hor = getResources().getDimension(R.dimen._15sdp);
int marginVer = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,ver,getResources().getDisplayMetrics());
int marginHor = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,hor,getResources().getDisplayMetrics());
layoutParams.setMargins(marginHor,marginVer,marginHor,marginVer);
layout.requestLayout();
}
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.call_btn:
callHim();
break;
case R.id.mail_btn:
sendEmail();
break;
}
}
private void callHim() {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phone.getText().toString()));
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},CALL_CODE);
return;
}
startActivity(callIntent);
}
private void sendEmail() {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:?subject=Matching item&to="+mail.getText().toString()));
try {
startActivity(Intent.createChooser(emailIntent,"Send mail..."));
}catch (ActivityNotFoundException e){
Log.e("MY_TAG",e.getMessage());
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case CALL_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
callHim();
else
Toast.makeText(this, "You should allow to access call", Toast.LENGTH_SHORT).show();
break;
}
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/ExternalActivity.java
================================================
package com.helloworld.goodpoint.ui;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.helloworld.goodpoint.R;
public class ExternalActivity extends AppCompatActivity {
EditText et;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_external);
et = findViewById(R.id.ngrok_link);
btn = findViewById(R.id.submit_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PrefManager p = new PrefManager(ExternalActivity.this);
p.setNGROKLink("https://"+et.getText().toString()+".ngrok.io");
}
});
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/FoundMapFragment.java
================================================
package com.helloworld.goodpoint.ui;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.pojo.ObjectLocation;
import com.helloworld.goodpoint.pojo.RegUser;
import com.helloworld.goodpoint.pojo.User;
import com.helloworld.goodpoint.pojo.UserMap;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.graphics.Color.BLUE;
public class FoundMapFragment extends Fragment implements GoogleMap.OnMarkerClickListener, View.OnClickListener {
private static final int MAP_CODE = 1;
private static final int CALL_CODE = 2;
private static final int CHECK_LOCATION_ENABLED_CODE = 3;
SupportMapFragment mapFragment;
FusedLocationProviderClient client;
Location curLocation;
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
List list;
Mapmarker_id;
AlertDialog.Builder dialog;
TextView name,email,phone;
Button call,mail;
String emailAddress;
private OnMapReadyCallback callback = new OnMapReadyCallback() {
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng curLatLng = new LatLng(curLocation.getLatitude(), curLocation.getLongitude());
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatLng, 15));
//list = getLocations();
for(ObjectLocation object: list) {
Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(object.getLatitude(), object.getLongitude())));
marker.setIcon(BitmapDescriptorFactory.defaultMarker(30));
marker_id.put(marker,object.getUserId());
}
googleMap.setOnMarkerClickListener(FoundMapFragment.this);
}
};
/*
private List getLocations() {
Listret = new ArrayList<>();
Random random = new Random();
for(int i=0;i<100;i++)
ret.add(new ObjectLocation(25+random.nextDouble()*10,22+random.nextDouble()*10,i));
return ret;
}
*/
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getPoints();
}
public boolean locationEnable() {
final LocationManager manager = (LocationManager) getContext().getSystemService(getContext().LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),CHECK_LOCATION_ENABLED_CODE);
//startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
private void runGoogleMap() {
if (ActivityCompat.checkSelfPermission(getContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, MAP_CODE);
}else if(!locationEnable()){
buildAlertMessageNoGps();
}else {
init();
client.getLastLocation()/*.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(@NonNull Location location) {
curLocation = location;
if (mapFragment != null) {
mapFragment.getMapAsync(callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
})*/.addOnCompleteListener(new OnCompleteListener() {
@SuppressLint("MissingPermission")
@Override
public void onComplete(@NonNull Task task) {
Location location = task.getResult();
if(location != null) {
curLocation = location;
if (mapFragment != null) {
mapFragment.getMapAsync(callback);
}
}else{
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10000)
.setFastestInterval(1000)
.setNumUpdates(1);
LocationCallback locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
curLocation = location;
if (mapFragment != null) {
mapFragment.getMapAsync(callback);
}
}
};
client.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
}
}
});
}
}
private void init() {
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
client = LocationServices.getFusedLocationProviderClient(getContext());
marker_id = new HashMap<>();
dialog = new AlertDialog.Builder(getContext());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode){
case MAP_CODE:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
runGoogleMap();
}else {
Toast.makeText(getContext(), "You should allow to access location", Toast.LENGTH_SHORT).show();
}
break;
case CALL_CODE:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
callHim();
}else {
Toast.makeText(getContext(), "You should allow to access call", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public boolean onMarkerClick(Marker marker) {
int id = marker_id.get(marker);
getUserMap(id);
Log.e("MYTAG",id+"");
return false;
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.call_button:
callHim();
break;
case R.id.mail_button:
sendEmail();
break;
}
}
private void callHim() {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phone.getText().toString()));
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, CALL_CODE);
return;
}
startActivity(callIntent);
}
private void sendEmail() {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:?subject=Lost object&to="+emailAddress));
try {
startActivity(Intent.createChooser(emailIntent,"Send mail..."));
}catch (ActivityNotFoundException e){
Log.e("MY_TAG",e.getMessage());
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CHECK_LOCATION_ENABLED_CODE:
runGoogleMap();
break;
}
}
public void getPoints()
{
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getContext()).getNGROKLink()).create(ApiInterface.class);
Call> call = apiInterface.getPoint();
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
list = response.body();
runGoogleMap();
// Toast.makeText(getContext(), ""+response.body().get(0).getLatitude(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call> call, Throwable t) {
}
});
}
public void getUserMap(int id)
{
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getContext()).getNGROKLink()).create(ApiInterface.class);
Call call2 = apiInterface.getUserMap(id);
call2.enqueue(new Callback() {
@Override
public void onResponse(Call call2, Response response) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View v = inflater.inflate(R.layout.custom_map_dialog,null);
name = v.findViewById(R.id.name_of_founder);
name.setText(response.body().getName());
email = v.findViewById(R.id.mail_of_founder);
email.setText(response.body().getEmail());
emailAddress = email.getText().toString();
phone = v.findViewById(R.id.phone_of_founder);
phone.setText(response.body().getPhone());
call = v.findViewById(R.id.call_button);
call.setOnClickListener(FoundMapFragment.this);
mail = v.findViewById(R.id.mail_button);
mail.setOnClickListener(FoundMapFragment.this);
dialog.setView(v);
dialog.setCancelable(true);
dialog.create().show();
// Toast.makeText(getContext(), response.body().getName(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/GlobalVar.java
================================================
package com.helloworld.goodpoint.ui;
import android.graphics.Bitmap;
import com.helloworld.goodpoint.pojo.LostItem;
import com.helloworld.goodpoint.ui.candidate.SubItem;
import com.helloworld.goodpoint.ui.select_multiple_faces.SubItemList;
import java.util.ArrayList;
import java.util.List;
public class GlobalVar {
public static List> allFaces = new ArrayList<>();
public static Bitmap realcameraImage ;
public static Bitmap realcameraIdCard ;
public static List ImgThatHaveMoreThanOneFace = new ArrayList<>();
public static List FinialFacesThatWillGoToDataBase = new ArrayList<>();
public static int flag;
public static List slist;
public static List sublist;
public static int position;
public static int p;
public static List losts;
public static List founds;
public static List lostList;
public static List percentList;
public static String type;
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/HomeActivity.java
================================================
package com.helloworld.goodpoint.ui;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.pojo.FoundItem;
import com.helloworld.goodpoint.pojo.FoundPerson;
import com.helloworld.goodpoint.pojo.LostItem;
import com.helloworld.goodpoint.pojo.LostObject;
import com.helloworld.goodpoint.pojo.LostPerson;
import com.helloworld.goodpoint.pojo.User;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import com.helloworld.goodpoint.ui.lostFoundObject.FoundObjectActivity;
import com.helloworld.goodpoint.ui.lostFoundObject.LostObjectDetailsActivity;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
AlertDialog.Builder dialog;
BottomNavigationView bottomNavigationView;
FloatingActionButton fab;
TextView namenavigator;
TextView mailnavigator;
CircleImageView imgnavigator;
Fragment selectedFragment;
List listObj;
List list1;
FoundPerson list3;
LostPerson list2;
List list;
boolean isGetLostItems=false, isGetFoundItems=false, isGetLostPersons=false, isGetFoundPersons=false;
SwipeRefreshLayout refreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getHomeLosts();
getHomeFounds();
setContentView(R.layout.activity_home);
/*refreshLayout = findViewById(R.id.swipe);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
selectedFragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
refreshLayout.setRefreshing(false);
}
});*/
init();
setToolBarAndDrawer();
setBottomNavigator();
/*if (savedInstanceState == null) {
//To make first fragment is home when opening the app
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fhome).commit();
}*/
selectedFragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
}
private void setBottomNavigator() {
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
fab = (FloatingActionButton) findViewById(R.id.fab);
//To Disable item under Fab
Menu menuNav = bottomNavigationView.getMenu();
MenuItem nav_item2 = menuNav.findItem(R.id.placeholder);
nav_item2.setEnabled(false);
bottomNavigationView.setBackgroundColor(0); //To hide the color of nav view
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
}
private void setToolBarAndDrawer() {
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(android.R.color.white));
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void init() {
drawerLayout = findViewById(R.id.drawer_layout);
toolbar = findViewById(R.id.toolbar);
navigationView = findViewById(R.id.nv);
navigationView.bringToFront();
View view = navigationView.getHeaderView(0);
namenavigator = (TextView) view.findViewById(R.id.namenav);
mailnavigator = (TextView) view.findViewById(R.id.mailnav);
imgnavigator = view.findViewById(R.id.circuler_profile_img);
namenavigator.setText(User.getUser().getUsername());
mailnavigator.setText(User.getUser().getEmail());
if (User.getUser().getProfile_bitmap() != null)
imgnavigator.setImageBitmap(User.getUser().getProfile_bitmap());
}
@Override
protected void onRestart() {
super.onRestart();
getHomeLosts();
getHomeFounds();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home_menu, menu);
menu.getItem(0).getIcon().mutate().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.notification){
Intent intent = new Intent(this, NotificationActivity.class);
intent.putExtra("ID",User.getUser().getId());
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.drawer_share:
break;
case R.id.drawer_rate:
break;
case R.id.drawer_feedback:
break;
case R.id.drawer_about_us:
break;
case R.id.drawer_setting:
break;
case R.id.drawer_logout:
dialog = createDialog("Logout", R.drawable.ic_baseline_exit_to_app_24);
dialog.create().show();
break;
default:
return false;
}
drawerLayout.closeDrawer(GravityCompat.START);
return false;
}
private AlertDialog.Builder createDialog(String title, int icon) {
return new AlertDialog.Builder(this)
.setTitle(title)
.setMessage("Are you sure?")
.setIcon(icon)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PrefManager prefManager = new PrefManager(getApplicationContext());
prefManager.setLogout();
User.userLogout();
startActivity(new Intent(HomeActivity.this, SigninActivity.class));
finish();
}
}).setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setCancelable(false);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
public void showPopup(View v) { //Fab Action
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(HomeActivity.this, R.style.BottomSheetTheme);
View bottomSheetView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.bottom_sheet_dialog, (LinearLayout) findViewById(R.id.bottom_sheet));
bottomSheetView.findViewById(R.id.hide_sheet).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetDialog.dismiss();
}
});
bottomSheetView.findViewById(R.id.ilost).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, LostObjectDetailsActivity.class));
bottomSheetDialog.dismiss();
}
});
bottomSheetView.findViewById(R.id.ifound).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, FoundObjectActivity.class));
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListner =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
selectedFragment = getSupportFragmentManager().getFragments().get(0);
switch (item.getItemId()) {
case R.id.miHome:
selectedFragment = new HomeFragment();
break;
case R.id.miMatch:
selectedFragment = new MatchFragment();
break;
case R.id.miProfile:
selectedFragment = new ProfileFragment();
break;
case R.id.miLocation:
selectedFragment = new FoundMapFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
public void getHomeLosts() {
List losts = new ArrayList<>();
losts = User.getUser().getLosts();
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
GlobalVar.losts = new ArrayList();
if (losts != null) {
for (int i = 0; i < losts.size(); i++) {
Call> call2 = apiInterface.getLostItem(losts.get(i));
call2.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
list1 = response.body();
if (response.body()!=null&&list1.size()!=0) {
String t = list1.get(0).getType() + " " + list1.get(0).getBrand() + "";
GlobalVar.losts.add(t);
}
isGetLostItems=true;
dataIsReady();
}
@Override
public void onFailure(Call> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
isGetLostItems=true;
dataIsReady();
}
});
Call call3 = apiInterface.getLostPerson(losts.get(i));
call3.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
list2 = response.body();
Log.e("TAG", "onResponse: "+response.body());
if (response.body()!=null) {
String t = list2.getName() + " is Missing";
GlobalVar.losts.add(t);
}
isGetLostPersons=true;
dataIsReady();
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
isGetLostPersons=true;
dataIsReady();
}
});
}
} else
Log.e("lost", "There is no objects of Losses.");
//Toast.makeText(getApplicationContext(), "There is no objects of Losses", Toast.LENGTH_LONG).show();
}
private void dataIsReady() {
if(isGetFoundItems && isGetFoundPersons && isGetLostItems && isGetLostPersons)
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
}
public void getHomeFounds() {
List founds = new ArrayList<>();
founds = User.getUser().getFounds();
GlobalVar.founds = new ArrayList();
if (!founds.isEmpty()) {
for (int i = 0; i < founds.size(); i++) {
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Call> call2 = apiInterface.getFoundItem(founds.get(i));
call2.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
list = response.body();
if (response.body()!=null&& list.size() !=0) {
String t = list.get(0).getType() + " " + list.get(0).getBrand() + "";
GlobalVar.founds.add(t);
}
isGetFoundItems=true;
dataIsReady();
}
@Override
public void onFailure(Call> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
isGetFoundItems=true;
dataIsReady();
}
});
Call call3 = apiInterface.getFoundPerson(founds.get(i));
call3.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
list3 = response.body();
Log.e("TAG", "onResponse: "+response.body());
if (response.body() != null) {
String t = list3.getName() + " is Founds";
GlobalVar.founds.add(t);
}
isGetFoundPersons=true;
dataIsReady();
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
isGetFoundPersons=true;
dataIsReady();
}
});
}
} else
Log.e("found", "There is no objects of Founds.");
//Toast.makeText(getApplicationContext(), "There is no objects of Founds.", Toast.LENGTH_LONG).show();
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/HomeFragment.java
================================================
package com.helloworld.goodpoint.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.adapter.MyExpandableListAdapter;
import com.helloworld.goodpoint.pojo.LostItem;
import com.helloworld.goodpoint.pojo.LostObject;
import com.helloworld.goodpoint.pojo.User;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HomeFragment extends Fragment {
List groupList;
List childList;
Map> objects; //To link group list with child list
ExpandableListView expandableListView;
ExpandableListAdapter expandableListAdapter;
TextView Daily_msg;
TextView Hi_msg;
List listObj;
LostItem list1;
String LossesObjects[];
// String FindingsItems[];
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
Daily_msg = v.findViewById(R.id.daily_message);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay >= 0 && timeOfDay < 12) {
Daily_msg.setText("Good Morning");
} else if (timeOfDay >= 12 && timeOfDay < 16) {
Daily_msg.setText("Good Afternoon");
} else if (timeOfDay >= 16 && timeOfDay < 21) {
Daily_msg.setText("Good Evening");
} else if (timeOfDay >= 21 && timeOfDay < 24) {
Daily_msg.setText("Good Night");
}
Hi_msg = v.findViewById(R.id.hi_message);
Hi_msg.setText("Hi, " + User.getUser().getUsername());
// Inflate the layout for this fragment
createGroupList();
createObjects(GlobalVar.losts,GlobalVar.founds);
expandableListView = v.findViewById(R.id.expanded_menu);
expandableListAdapter = new MyExpandableListAdapter(getActivity(), groupList, objects); //getActivity
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int i, int i1, long l) {
String selected = expandableListAdapter.getChild(i, i1).toString();
return true;
}
});
return v;
}
private void createObjects(List itemsL,List itemsF) {
objects = new HashMap>();
for (String group : groupList) {
if (group.equals(getString(R.string.Losses))) {
loadChild(itemsL);
} else if (group.equals(getString(R.string.Founds)))
loadChild(itemsF);
objects.put(group, childList);
}
}
private void loadChild(List AllObjects) {
childList = new ArrayList<>();
if (AllObjects != null) {
for (int i = 0; i < AllObjects.size(); i++)
childList.add(AllObjects.get(i));
} else
childList.add("b");
}
private void createGroupList() {
groupList = new ArrayList<>();
groupList.add(getString(R.string.Losses));
groupList.add(getString(R.string.Founds));
}
/* public String[] getHomeFounds() {
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getContext()).getNGROKLink()).create(ApiInterface.class);
Call> call = apiInterface.getHomeFounds_i(User.getUser().getId());
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
String id = jsonObject.getString("id");
Call> call2 = apiInterface.getFItem(id);
call2.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
}
@Override
public void onFailure(Call> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
Toast.makeText(getContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
Log.d("e", "message=" + FindingsItems);
return FindingsItems;
}
*/
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/ID_cardDetection.java
================================================
package com.helloworld.goodpoint.ui;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.mlkit.common.MlKitException;
import com.google.mlkit.common.model.LocalModel;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.common.internal.ImageConvertUtils;
import com.google.mlkit.vision.objects.DetectedObject;
import com.google.mlkit.vision.objects.ObjectDetection;
import com.google.mlkit.vision.objects.ObjectDetector;
import com.google.mlkit.vision.objects.custom.CustomObjectDetectorOptions;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.utils.Draw;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class ID_cardDetection extends AppCompatActivity {
private ObjectDetector objectDetector;
private ListenableFuture cameraProviderFuture;
private androidx.camera.view.PreviewView previewView;
private RelativeLayout relativeLayout;
private ImageButton IDCard;
private boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_d_card_detection);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
{
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA},20);
}
previewView = findViewById(R.id.PV);
relativeLayout = findViewById(R.id.ParentLayout);
IDCard = findViewById(R.id.IDCard);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
Log.e("ESRAA", "ExecutionException: "+e.getMessage());
}
}, ContextCompat.getMainExecutor(this));
LocalModel localModel = new LocalModel.Builder()
.setAssetFilePath("objectDetection.tflite").build();
CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel)
.setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE)
.enableClassification()
.setClassificationConfidenceThreshold(0.5f)
.setMaxPerObjectLabelCount(1)
.build();
objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
}
private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
Log.e("ESRAA", "IamHERE");
Preview preview = new Preview.Builder().build();
TextureView mTextureView = new TextureView(this);
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(480,480))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build();
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),
image -> {
int rotationDegrees = image.getImageInfo().getRotationDegrees();
@SuppressLint("UnsafeOptInUsageError") Image im= image.getImage();
if(im != null)
{
InputImage processImage= InputImage.fromMediaImage(im,rotationDegrees);
InputImage i = InputImage.fromMediaImage(im, image.getImageInfo().getRotationDegrees());
try {
GlobalVar.realcameraIdCard = ImageConvertUtils.getInstance().getUpRightBitmap(i);
} catch (MlKitException e) {
e.printStackTrace();
}
objectDetector.process(processImage)
.addOnSuccessListener(detectedObjects -> {
if(detectedObjects.size() == 0)
{
if (relativeLayout.getChildCount() > 1)
relativeLayout.removeViewAt(1);
String text ="There's no card found";
Draw D = new Draw(ID_cardDetection.this,text);
D.init(2);
relativeLayout.addView(D);
IDCard.setImageResource(R.drawable.ic_baseline_photo_camera_24);
flag = false;
}
else {
for (DetectedObject detectedObject : detectedObjects) {
String text;
detectedObject.getLabels().contains("Driver's license");
for (DetectedObject.Label label : detectedObject.getLabels()) {
if (relativeLayout.getChildCount() > 1)
relativeLayout.removeViewAt(1);
if (label.getText().equals("Driver's license")) {
text = "There's card found";
Draw D = new Draw(ID_cardDetection.this, text);
D.init(1);
relativeLayout.addView(D);
Log.e("ESRAA", "Object detected: " + text + "; ");
IDCard.setImageResource(R.drawable.ic_realcam);
flag = true;
} else {
text = "There's no card found";
Draw D = new Draw(ID_cardDetection.this, text);
D.init(2);
relativeLayout.addView(D);
IDCard.setImageResource(R.drawable.ic_baseline_photo_camera_24);
flag = false;
}
}
}
}
image.close();
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("ESRAA", "onFailure: "+e.getMessage());
image.close();
}
});
}
}
);
cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector,imageAnalysis, preview);
}
public void check_there(View view) {
if(flag)
{
Intent My = new Intent();
setResult(RESULT_OK,My);
finish();
}
else {
Toast.makeText(this,"There's no card found",Toast.LENGTH_SHORT).show();
}
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/IdCard.java
================================================
package com.helloworld.goodpoint.ui;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.helloworld.goodpoint.R;
public class IdCard extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert_id_card);
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/MainActivity.java
================================================
package com.helloworld.goodpoint.ui;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.JsonObject;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.pojo.Token;
import com.helloworld.goodpoint.pojo.User;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
PrefManager prefManager;
ImageView splash;
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
if (prefManager.isFirstTimeLaunch()) {
prefManager.setFirstTimeLaunch(true);
startActivity(new Intent(MainActivity.this, WelcomeActivity.class));
finish();
}else if(!prefManager.isLoginned().isEmpty()) {
rotateSplash();
t = startApp();
}else {
startActivity(new Intent(this,SigninActivity.class));
finish();
}
}
@Override
protected void onResume() {
super.onResume();
t.start();
}
@Override
protected void onPause() {
t.interrupt();
super.onPause();
}
private void init() {
prefManager = new PrefManager(getApplicationContext());
splash = findViewById(R.id.splash_icon);
}
private void rotateSplash() {
Animation animation = AnimationUtils.loadAnimation(this,R.anim.rotate_splash);
splash.startAnimation(animation);
}
private Thread startApp() {
return new Thread(new Runnable() {
@Override
public void run() {
//try {
//Thread.sleep(3000);
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Call call = apiInterface.refresh(new PrefManager(getApplicationContext()).isLoginned());
Token.getToken().setRefresh(new PrefManager(getApplicationContext()).isLoginned());
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful()) {
String token = response.body().getAccess();
Call call2 = apiInterface.getData("Bearer " + token);
call2.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
Log.d("e","res="+response.body().toString());
JSONObject jsonObject = new JSONObject(response.body().toString()).getJSONObject("user");
String id = jsonObject.getString("id");
String name = jsonObject.getString("username");
String email = jsonObject.getString("email");
String phone = jsonObject.getString("phone");
String city = jsonObject.getString("city");
String birthdate = jsonObject.getString("birthdate");
String Userimage = jsonObject.getString("profile_pic");
String idcardimage = jsonObject.getString("id_card_pic");
JSONArray jsonArray = jsonObject.getJSONArray("losts");
Log.e("blabla", jsonArray.length() + "");
for(int i=0;i call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, SigninActivity.class));
finish();
}
});
}else{
startActivity(new Intent(MainActivity.this, SigninActivity.class));
finish();
}
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, SigninActivity.class));
finish();
}
});
//} catch (InterruptedException e) {
// Log.e("InterruptedException: ", e.getMessage());
//}
}
});
}
class DownloadProfilePic extends AsyncTask {
private Bitmap download(String urlLink) throws IOException {
Bitmap bitmap = null;
URL url = null;
HttpURLConnection httpConn;
InputStream is = null;
Log.e("ProfilePic", urlLink);
try {
url = new URL(urlLink);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.connect();
is = httpConn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
}catch (MalformedURLException e){
Log.e("DownloadProfilePic", "download: "+e.getMessage());
}
return bitmap;
}
@Override
protected Bitmap doInBackground(String... urls) {
try {
return download(urls[0]);
} catch (IOException e) {
Log.e("TAG", "doInBackground: "+e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if(bitmap!=null)
User.getUser().setProfile_bitmap(bitmap);
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/MatchFragment.java
================================================
package com.helloworld.goodpoint.ui;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.helloworld.goodpoint.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link MatchFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MatchFragment extends Fragment {
ListView listView;
TextView details;
//String ObjStat[] ={},ObjDetails;
String status[]={"Has found" ,"Its owner has been found","Has found" ,"Its owner has been found",
"Has found" ,"Its owner has been found","Has found" ,"Its owner has been found" } ;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public MatchFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MatchFragment.
*/
// TODO: Rename and change types and number of parameters
public static MatchFragment newInstance(String param1, String param2) {
MatchFragment fragment = new MatchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_match, container, false);
listView = (ListView) view.findViewById(R.id.lisView);
AdapterOfMatchFragment myAdapter = new AdapterOfMatchFragment(getActivity(),status);
listView.setAdapter(myAdapter);
return view;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/NotificationActivity.java
================================================
package com.helloworld.goodpoint.ui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.util.SparseArray;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.app.ActivityCompat;
import androidx.loader.content.CursorLoader;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import com.google.gson.JsonObject;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.adapter.NotificationListAdapter;
import com.helloworld.goodpoint.pojo.NotificationItem;
import com.helloworld.goodpoint.pojo.Token;
import com.helloworld.goodpoint.pojo.User;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import com.helloworld.goodpoint.ui.candidate.CandidatePage;
import com.shashank.sony.fancytoastlib.FancyToast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NotificationActivity extends AppCompatActivity {
List list;
ListView listView;
TextView noNotification;
Bitmap img;
AlertDialog dialog;
AlertDialog.Builder builder;
View view;
Uri photoFromGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
init();
createList();
}
private void createList() {
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Call>call = apiInterface.getNotification(User.getUser().getId());
call.enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
list = response.body();
if(list == null)
list = new ArrayList<>();
showView();
}
@Override
public void onFailure(Call> call, Throwable t) {
Log.e("TAG", "onFailure: "+t.getMessage());
}
});
}
private void showView() {
if(list.isEmpty()){
noNotification.setVisibility(View.VISIBLE);
listView.setVisibility(View.GONE);
}else {
listView.setAdapter(new NotificationListAdapter(this, 0, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> adapterView, View v, int i, long l) {
int pos = list.size()-i-1;
NotificationListAdapter adapter = (NotificationListAdapter)listView.getAdapter();
adapter.getItem(pos).setRead(true);
adapter.notifyDataSetChanged();
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Callcall = apiInterface.updateRead(list.get(pos).getId(), true);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful())
{
Log.e("TAG", "onResponse: "+response.body().toString());
}
else {
try {
Log.e("TAG", "onFailure2: "+response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("TAG", "onFailure: "+t.getMessage());
}
});
if(list.get(pos).getType()==3){
//intent to candidate
startActivity(new Intent(NotificationActivity.this, CandidatePage.class));
return;
}
else if(list.get(pos).getType() == 1 || list.get(pos).getType() == 4){
//lost person and lost item
if(User.getUser().getId_card_pic().isEmpty()){
view = getLayoutInflater().inflate(R.layout.alert_id_card, null);
Button Choose = view.findViewById(R.id.Id_card);
Choose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(NotificationActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11);
}
else{
Intent I = new Intent(NotificationActivity.this,ID_cardDetection.class);
startActivityForResult(I, 10);
/* PopupMenu popupMenu = new PopupMenu(NotificationActivity.this, view);
popupMenu.getMenuInflater().inflate(R.menu.choose_photo, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.TakePhoto:
Intent I = new Intent(NotificationActivity.this,ID_cardDetection.class);
startActivityForResult(I, 10);
break;
case R.id.Gallery:
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 11);
break;
}
return true;
}
});
popupMenu.show();*/
}
}
});
builder = new AlertDialog.Builder(NotificationActivity.this);
builder.setMessage("Please , Upload an image of your id_card");
builder.setView(view);
dialog = builder.create();
dialog.show();
return;
}
}
Intent intent = new Intent(NotificationActivity.this,DetailsActivity.class);
intent.putExtra("id",list.get(pos).getId());
intent.putExtra("type",list.get(pos).getType());
startActivity(intent);
}
});
}
}
public Uri getImageUri(Bitmap bitmap_Image) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, "id card", null);
return Uri.parse(path);
}
private String getRealPathFromURI(Uri imageUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK&&data!=null)
{
switch(requestCode) {
case 10: {
img =(Bitmap) GlobalVar.realcameraIdCard;
photoFromGallery = getImageUri(img);
}
break;
/*case 11:
photoFromGallery = data.getData();
try {
img = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoFromGallery);
} catch (IOException e) {
e.printStackTrace();
}
break;*/
}
checkVaildIdcard();
}
}
private void checkVaildIdcard() {
TextView messageforuser = view.findViewById(R.id.messageforuser);
boolean flag_not_idCard = false;
FaceDetector faceDetector = new FaceDetector.Builder(this)
.setTrackingEnabled(false)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE).build();
if (!faceDetector.isOperational()) {
Toast.makeText(this, "Face Detection can't be setup", Toast.LENGTH_SHORT).show();
}
else {
Frame frame = new Frame.Builder().setBitmap(img).build();
SparseArray sparseArray = faceDetector.detect(frame);
if(sparseArray.size() != 1)
{
flag_not_idCard = true;
}
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
if(!textRecognizer.isOperational())
Toast.makeText(this, "textRecognizer can't be setup", Toast.LENGTH_SHORT).show();
else
{
Frame frametext = new Frame.Builder().setBitmap(img).build();
SparseArray sparseArraytext = textRecognizer.detect(frame);
TextBlock item;
if(sparseArraytext.size()>4 || sparseArraytext.size()<1)
{
flag_not_idCard = true;
}
else if(sparseArraytext.size()>=1) {
item = sparseArraytext.valueAt(sparseArraytext.size() - 1);
if(item.getValue().length() != 9)
flag_not_idCard = true;
}
Log.e("img", "num of img : "+sparseArray.size()+" num of text " +sparseArraytext.size());
}
if(flag_not_idCard)
{
messageforuser.setTextColor(0xFFB80D0D);
messageforuser.setText("Error, The card picture cannot be recognized\nplease upload your id card");
}
else{
dialog.dismiss();
builder = new AlertDialog.Builder(NotificationActivity.this);
builder.setMessage("Your id_card has been successfully taken").setNegativeButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Call call = apiInterface.refresh(Token.getToken().getRefresh());
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
File file = new File(getRealPathFromURI(photoFromGallery));
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part Pimage = MultipartBody.Part.createFormData("id_card_pic", file.getName(), requestBody);
CallidcardCall = apiInterface.setIdCard(response.body().getAccess(), Pimage);
idcardCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.d("TAG", "onResponse: Success");
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("TAG", "onFailure: "+t.getMessage());
}
});
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("TAG", "onFailure: "+t.getMessage());
}
});
}});
dialog = builder.create();
dialog.show();
}
}
}
private void init() {
list = new ArrayList<>();
listView = findViewById(R.id.notification_listview);
noNotification = findViewById(R.id.no_notification);
if(User.getUser().getId() == null || User.getUser().getId().isEmpty())
User.getUser().setId(getIntent().getExtras().getString("ID"));
if(Token.getToken().getRefresh() == null || Token.getToken().getRefresh().isEmpty())
Token.getToken().setRefresh(new PrefManager(this).isLoginned());
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/PrefManager.java
================================================
package com.helloworld.goodpoint.ui;
import android.content.Context;
import android.content.SharedPreferences;
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "androidhive-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
private static final String IS_LOGINNED = "Token";
private static final String LINK = "ngrok";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH,true);
}
public void setLogin(String token){
editor.putString(IS_LOGINNED, token);
editor.commit();
}
public void setLogout(){
editor.putString(IS_LOGINNED, "");
editor.commit();
}
public String isLoginned() {
return pref.getString(IS_LOGINNED,"");
}
public void setNGROKLink(String link){
editor.putString(LINK, link);
editor.commit();
}
public String getNGROKLink() {
return pref.getString(LINK,"http://127.0.0.1:8000/");
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/ProfileFragment.java
================================================
package com.helloworld.goodpoint.ui;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.pojo.LostItem;
import com.helloworld.goodpoint.pojo.Token;
import com.helloworld.goodpoint.pojo.User;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ProfileFragment extends Fragment {
TextView name_above,email_above,name,email,phone,city,date,losts,founds;
CircleImageView pic;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
name_above = v.findViewById(R.id.above_name);
email_above = v.findViewById(R.id.above_mail);
name = v.findViewById(R.id.username_p);
email = v.findViewById(R.id.e_mail);
phone = v.findViewById(R.id.phone_p);
city = v.findViewById(R.id.city_p);
date = v.findViewById(R.id.birth_date);
pic = v.findViewById(R.id.profile_pic);
losts = v.findViewById(R.id.lost_no);
founds = v.findViewById(R.id.found_no);
name_above.setText(User.getUser().getUsername());
email_above.setText(User.getUser().getEmail());
losts.setText(User.getUser().getLosts().size() + "");
founds.setText(User.getUser().getFounds().size() + "");
name.setText(User.getUser().getUsername());
email.setText(User.getUser().getEmail());
phone.setText(User.getUser().getPhone());
city.setText(User.getUser().getCity());
date.setText(User.getUser().getBirthdate());
if(User.getUser().getProfile_bitmap() != null)
pic.setImageBitmap(User.getUser().getProfile_bitmap());
return v;
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/SigninActivity.java
================================================
package com.helloworld.goodpoint.ui;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.JsonObject;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.pojo.Token;
import com.helloworld.goodpoint.pojo.User;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import com.helloworld.goodpoint.ui.forgetPasswordScreens.MakeSelection;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SigninActivity extends AppCompatActivity implements View.OnClickListener {
private EditText Email, Pass;
private TextInputLayout tilUserName, tilEmail, tilPassword, tilCity, tilPhone;
private TextView ForgetPass;
private CheckBox RememberMe;
private Button Sigin, CreateNewAccount;
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
// "(?=.*[a-zA-Z])" + //any letter
// "(?=.*[@#$%^&+=])" + //at least 1 special character
// "(?=\\S+$)" + //no white spaces
".{8,}" + //at least 8 characters
"$");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
//getActionBar().hide();
setContentView(R.layout.activity_signin);
inti();
String f;
}
protected void inti() {
Email = findViewById(R.id.email);
Pass = findViewById(R.id.pass);
tilPassword = findViewById(R.id.tilPass);
ForgetPass = findViewById(R.id.forgetPass);
Sigin = findViewById(R.id.signin);
CreateNewAccount = findViewById(R.id.NewAccount);
RememberMe = findViewById(R.id.checkbox);
Sigin.setOnClickListener(this);
CreateNewAccount.setOnClickListener(this);
ForgetPass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MakeSelection.class);
startActivityForResult(myIntent, 0);
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.signin:
if (validAccount() && validatePassword()) {
loginUser(RememberMe.isChecked());
//startActivity(new Intent(SigninActivity.this, HomeActivity.class));
} else
Toast.makeText(this, "Invalid account", Toast.LENGTH_SHORT).show();
//startActivity(new Intent(SigninActivity.this, HomeActivity.class));
break;
case R.id.NewAccount:
startActivity(new Intent(this, SignupActivity.class));
break;
}
}
private boolean validatePassword() {
String passwordInput = Pass.getText().toString().trim();
if (passwordInput.isEmpty()) {
tilPassword.setError("Field can't be empty");
return false;
} else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
tilPassword.setError("Must contains digits, lower&upper case letters and length > 8");
/*if(!passwordInput.matches("[0-9]+"))
Pass.setError("must contain at least 1 digit");
else if(!passwordInput.matches("[a-z]+"))
Pass.setError("must contain at least 1 lower case letter");
else if(!passwordInput.matches("[A-Z]+"))
Pass.setError("must contain at least 1 upper case letter");
else
Pass.setError("must contain at least 8 characters");*/
return false;
} else {
tilPassword.setError(null);
return true;
}
}
private boolean validateEmail() {
String emailInput = Email.getText().toString().trim();
if (emailInput.isEmpty()) {
Email.setError("Field can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
Email.setError("Please enter a valid email address");
return false;
} else {
Email.setError(null);
return true;
}
}
private boolean validAccount() {
//check validation
if (validateEmail()) return true;
else return false;
}
public void loginUser(boolean Remember) {
String emailInput = Email.getText().toString().trim();
String passwordInput = Pass.getText().toString().trim();
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Call call = apiInterface.getToken(emailInput, passwordInput);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
String token = response.body().getAccess();
Token.getToken().setAccess(response.body().getAccess());
Token.getToken().setRefresh(response.body().getRefresh());
if (Remember) {
new PrefManager(getApplicationContext()).setLogin(response.body().getRefresh());
}
Call call2 = apiInterface.getData("Bearer " + token);
call2.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
Log.d("e","res="+response.body().toString());
JSONObject jsonObject = new JSONObject(response.body().toString()).getJSONObject("user");
String id = jsonObject.getString("id");
String name = jsonObject.getString("username");
String email = jsonObject.getString("email");
String phone = jsonObject.getString("phone");
String city = jsonObject.getString("city");
String birthdate = jsonObject.getString("birthdate");
String Userimage = jsonObject.getString("profile_pic");
String idcardimage = jsonObject.getString("id_card_pic");
JSONArray jsonArray = jsonObject.getJSONArray("losts");
Log.e("blabla", jsonArray.length() + "");
for(int i=0;i call, Throwable t) {
Toast.makeText(SigninActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
else
Toast.makeText(SigninActivity.this, "Invalid account.", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(SigninActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
class DownloadProfilePic extends AsyncTask {
AlertDialog.Builder builder;
AlertDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
builder = new AlertDialog.Builder(SigninActivity.this);
builder.setCancelable(false);
View view = getLayoutInflater().inflate(R.layout.progress_bar_alert, null);
builder.setView(view);
dialog = builder.create();
dialog.show();
}
private Bitmap download(String urlLink) throws IOException {
Bitmap bitmap = null;
URL url = null;
HttpURLConnection httpConn;
InputStream is = null;
Log.e("ProfilePic", urlLink);
try {
url = new URL(urlLink);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.connect();
is = httpConn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
}catch (MalformedURLException e){
Log.e("DownloadProfilePic", "download: "+e.getMessage());
}
return bitmap;
}
@Override
protected Bitmap doInBackground(String... urls) {
try {
return download(urls[0]);
} catch (IOException e) {
Log.e("TAG", "doInBackground: "+e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
dialog.dismiss();
if(bitmap!=null)
User.getUser().setProfile_bitmap(bitmap);
Intent intent = new Intent(SigninActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
}
================================================
FILE: app/src/main/java/com/helloworld/goodpoint/ui/SignupActivity.java
================================================
package com.helloworld.goodpoint.ui;
import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Patterns;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.loader.content.CursorLoader;
import com.google.android.material.textfield.TextInputLayout;
import com.helloworld.goodpoint.R;
import com.helloworld.goodpoint.pojo.RegUser;
import com.helloworld.goodpoint.retrofit.ApiClient;
import com.helloworld.goodpoint.retrofit.ApiInterface;
import com.shashank.sony.fancytoastlib.FancyToast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Pattern;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SignupActivity extends AppCompatActivity {
private TextView DateT;
private TextInputLayout tilUserName, tilEmail, tilPassword, tilCity, tilPhone;
private EditText UserName, Email, Password, Phone;
AutoCompleteTextView city;
private DatePickerDialog.OnDateSetListener DateSet;
private int year, month, Day;
private ImageView image;
Button CreateAccount;
List list;
Bitmap Bitmap_Image ; Uri imageUri;
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[a-zA-Z])" + //any letter
//"(?=.*[@#$%^&+=])" + //at least 1 special character
//"(?=\\S+$)" + //no white spaces
".{8,}" + //at least 4 characters
"$");
public SignupActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//getSupportActionBar().setTitle("Sing up");
inti();
if(savedInstanceState != null )
{
Bitmap_Image = savedInstanceState.getParcelable("BitmapImage");
if(Bitmap_Image != null){
image.setImageBitmap(Bitmap_Image);
}
}
DateT.setOnClickListener(new View.OnClickListener() {
// @RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View view) {
DatePickerDialog dialog = new DatePickerDialog(
SignupActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
DateSet,
year, month, Day
);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
DateSet = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int y, int m, int d) {
m++;
if (y > year || (y == year && m - 1 > month)|| (y == year && m - 1 == month && d > Day) ) {
String Date = y + "-" + m + "-" + d;
//String Date = d + "/" + m + "/" + y;
String todayDate = year + "-" + (month + 1) + "-" + Day;
//String todayDate = Day + "/" + (month + 1) + "/" + year;
DateT.setText(todayDate);
FancyToast.makeText(SignupActivity.this,"Invalid date",FancyToast.LENGTH_LONG, FancyToast.ERROR,false).show();
}
else {
String Date = y + "-" + m + "-" + d;
//String Date = d + "/" + m + "/" + y;
DateT.setText(Date);
}
}
};
CreateAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!confirmInput(view) ){
registerUser();
//startActivity(new Intent(SignupActivity.this,check_registration.class));
}
}
});
}
protected void inti() {
UserName = findViewById(R.id.edName);
Email = findViewById(R.id.edEmail);
Password = findViewById(R.id.edPass);
city = findViewById(R.id.edCity);
Phone =findViewById(R.id.edPhone);
tilUserName = findViewById(R.id.tilName);
tilEmail = findViewById(R.id.tilEmail);
tilPassword = findViewById(R.id.tilPass);
tilCity = findViewById(R.id.tilcity);
tilPhone =findViewById(R.id.tilPhone);
DateT = findViewById(R.id.Date);
image = findViewById(R.id.im);
registerForContextMenu(image);
CreateAccount = findViewById(R.id.createAccount);
Calendar cal = Calendar.getInstance();//To get today's date
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
Day = cal.get(Calendar.DAY_OF_MONTH);
String TodayDate = year + "-" + (month + 1) + "-" + Day;
//String TodayDate = Day + "/" + (month + 1) + "/" + year;
DateT.setText(TodayDate);/**/
prepareList List = new prepareList();
list = List.prepareList(this);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
city.setThreshold(1);
city.setAdapter(adapter);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.menu_main, menu);
Toast.makeText(this, "onCreateContextMenu", Toast.LENGTH_SHORT);
//menu.getItem(2).setEnabled(false);
menu.findItem(R.id.Delete).setVisible(false);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},11);
}
else {
switch (item.getItemId()) {
case R.id.action_capture:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cameraIntent, 10);
}
break;
case R.id.action_choose:
//Toast.makeText(this,"Hello",Toast.LENGTH_SHORT).show();
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 11);
break;
}
}
return super.onContextItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == RESULT_OK) {
Bitmap_Image = (Bitmap) data.getExtras().get("data");
imageUri = getImageUri(Bitmap_Image);
image.setImageBitmap(Bitmap_Image);
}
if (requestCode == 11 && resultCode == RESULT_OK) {
imageUri = data.getData();
try {
Bitmap_Image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
Toast.makeText(this,"Dina",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
image.setImageURI(imageUri);
}
}
private boolean validateEmail() {
String emailInput = Email.getText().toString().trim();
if (emailInput.isEmpty()) {
Email.setError("Field can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
Email.setError("Please enter a valid email address");
return false;
} else {
Email.setError(null);
return true;
}
}
public boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c) | c !=' ' ) {
return false;
}
}
return true;
}/**/
private boolean validateUsername() {
String usernameInput = UserName.getText().toString().trim();
if (usernameInput.isEmpty()) {
UserName.setError("Field can't be empty");
return false;
} else if (usernameInput.length() > 15) {
UserName.setError("Username too long");
return false;
}
else if (usernameInput.length() < 2) {
UserName.setError("Username too short");
return false;
}else if (isAlpha(usernameInput)) {
UserName.setError("Using only Letters");
return false;
} else {
UserName.setError(null);
return true;
}
}
private boolean find_Digit(String s){
String n ;
for(int i = 1; i < s.length(); i++){
n = s.substring(i-1,i);
if(n.matches("[0-9]"))
return true;
}
return false;
}
private boolean validatePassword() {
String passwordInput = Password.getText().toString().trim();
if (passwordInput.isEmpty()) {
tilPassword.setError("Field can't be empty");
return false;
} else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
/*if(!find_Digit(passwordInput) )
tilPassword.setError("must contain at least 1 digit");
else if(!passwordInput.matches("[a-z]"))
tilPassword.setError("must contain at least 1 lower case letter");
else if(!passwordInput.matches("[A-Z]"))
tilPassword.setError("must contain at least 1 upper case letter");
else*/
tilPassword.setError("Must contains digits, lower&upper case letters and length > 8");
return false;
} else {
tilPassword.setError(null);
return true;
}
}
private boolean validateCity() {
String cityInput = city.getText().toString().trim();
if (cityInput.isEmpty()) {
city.setError("Field can't be empty");
return false;
} else if (!list.contains(cityInput)) {
city.setError("Please Enter valid city!");
return false;
} else {
city.setError(null);
return true;
}
}//
private boolean validatePhone() {
String pInput = Phone.getText().toString().trim();
if (pInput.isEmpty()) {
Phone.setError("Field can't be empty");
return false;
} else if (pInput.length() != 11) {
Phone.setError("Please enter a valid phone number");
return false;
} else {
/*try{
int i = Integer.parseInt(pInput);
tilPhone.setError("Please enter a valid phone number");
}
catch (Exception e){
tilPhone.setError(null);
}*/
Phone.setError(null);
return true;
}
}//| !validatePhone()
public boolean confirmInput(View v) {
if (!validateEmail() | !validateUsername() | !validatePassword() | !validatePhone() |!validateCity()) {
return true;
}
/*String input = "Email: " + Email.getText().toString();
input += "\n";
input += "Username: " + UserName.getText().toString();
input += "\n";
input += "Password: " + Password.getText().toString();
Toast.makeText(this, input, Toast.LENGTH_SHORT).show();*/
return false;
}/**/
protected void prepareList() {
list = new ArrayList<>();
list.add(getString(R.string.Cairo));
list.add(getString(R.string.Alexandria));
list.add(getString(R.string.ShubraElKheima));
list.add(getString(R.string.Giza));
list.add(getString(R.string.PortSaid));
list.add(getString(R.string.Suez));
list.add(getString(R.string.ElMahallaElKubra));
list.add(getString(R.string.Luxor));
list.add(getString(R.string.Mansoura));
list.add(getString(R.string.Tanta));
list.add(getString(R.string.Asyut));
list.add(getString(R.string.Ismailia));
list.add(getString(R.string.Faiyum));
list.add(getString(R.string.Zagazig));
list.add(getString(R.string.Damietta));
list.add(getString(R.string.Aswan));
list.add(getString(R.string.Minya));
list.add(getString(R.string.BeniSuef));
list.add(getString(R.string.Hurghada));
list.add(getString(R.string.Qena));
list.add(getString(R.string.Sohag));
list.add(getString(R.string.ShibinElKom));
list.add(getString(R.string.Banha));
list.add(getString(R.string.Arish));
}
public void onSaveInstanceState(@NonNull Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putParcelable("BitmapImage",Bitmap_Image);
}
public Uri getImageUri(Bitmap bitmap_Image) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap_Image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap_Image, "Profile", null);
return Uri.parse(path);
}
private String getRealPathFromURI(Uri imageUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, imageUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
public void registerUser() {
String emailInput = Email.getText().toString().trim();
String passwordInput = Password.getText().toString().trim();
String usernameInput = UserName.getText().toString().trim();
String pInput = Phone.getText().toString().trim();
String cityInput = city.getText().toString().trim();
String Datee = DateT.getText().toString().trim();
ApiInterface apiInterface = ApiClient.getApiClient(new PrefManager(getApplicationContext()).getNGROKLink()).create(ApiInterface.class);
Call