Commit 38c27d8c authored by satya's avatar satya

first commit

parent 26c1c420
/build
\ No newline at end of file
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-android-extensions'
id 'org.jetbrains.kotlin.kapt'
id 'com.google.gms.google-services'
id 'dagger.hilt.android.plugin'
}
apply plugin: "realm-android"
android {
signingConfigs {
release {
storePassword 'seatel_Cambodia'
keyPassword 'seatel_Cambodia'
keyAlias 'seatel_cambodia'
storeFile file('/Users/seatel/Documents/seashop.jks')
}
}
compileSdk 33
defaultConfig {
applicationId "com.seatel.mobilehall"
minSdk 23
targetSdk 33
versionCode 201907111
versionName "2.3.10"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
signingConfig signingConfigs.release
}
buildTypes {
release {
buildConfigField 'String', 'CLIENT_ID', '"eyJhbGciOiJIUzI1NiJ9.c2VhdGVsLWFwaS1kZXY.NsFhP0C7pqeONbcGAf42lQLLe6AIgy1QdOUOrg0uqcI"'
buildConfigField 'String', 'BASE_URL', '"https://api.yes.com.kh/"'
//production version
buildConfigField 'String', 'CLIENT_SECRET', '"MjExNzM0NWNiNTA3NDZmNzg4NmE0NTNlYjYyMWNkODk="'
minifyEnabled false
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
proguardFile '/Users/ryan/Documents/Project/Seatel_android_project/sea-tel-android/app/proguard-rules.pro'
}
debug {
buildConfigField 'String', 'CLIENT_ID', '"eyJhbGciOiJIUzI1NiJ9.c2VhdGVsLWFwaS1kZXY.NsFhP0C7pqeONbcGAf42lQLLe6AIgy1QdOUOrg0uqcI"'
buildConfigField 'String', 'BASE_URL', '"http://api-dev.yes.com.kh/"'
buildConfigField 'String', 'CLIENT_SECRET', '"MjExNzM0NWNiNTA3NDZmNzg4NmE0NTNlYjYyMWNkODk="'
debuggable true
buildConfigField 'Boolean', 'enableCrashlytics', 'false'
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
ext.alwaysUpdateBuildId = false
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
resources {
excludes += ['META-INF/DEPENDENCIES']
}
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding = true
}
/*realm {
syncEnabled = true
}*/
sourceSets {
main {
assets {
srcDirs 'src/main/assets'
}
}
}
lint {
baseline = file("lint-baseline.xml")
}
lintOptions {
abortOnError false
}
}
configurations {
customImplementation
}
dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.navigation:navigation-fragment-ktx:2.4.2'
implementation 'androidx.navigation:navigation-ui-ktx:2.4.2'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'com.google.code.gson:gson:2.9.0'
implementation 'com.github.bumptech.glide:glide:4.13.0'
implementation 'com.google.firebase:firebase-messaging-ktx:23.1.2'
implementation 'androidx.work:work-runtime-ktx:2.8.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.13.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.github.bigstark:fresco-parallax-drawee-view:1.2.1'
implementation 'com.facebook.android:facebook-android-sdk:4.42.0'
implementation 'com.mcxiaoke.volley:library:1.0.19'
implementation 'com.jaredrummler:android-device-names:1.1.7'
implementation 'com.google.android.material:material:1.6.1'
implementation 'com.google.maps.android:android-maps-utils:0.5'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.android.gms:play-services-analytics:17.0.0'
implementation 'com.google.android.gms:play-services-measurement-api:21.1.0'
implementation 'com.google.android.gms:play-services-vision:20.1.3'
//firebase
implementation platform('com.google.firebase:firebase-bom:31.2.3')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-ml-vision:24.0.3'
implementation 'com.google.firebase:firebase-ml-vision-barcode-model:16.1.2'
implementation 'com.github.markomilos:paginate:0.5.1'
implementation 'com.github.markusressel:PageIndicatorView:v0.9.6'
api 'io.anyline:anylinesdk:18.1@aar'
customImplementation('io.anyline:anylinesdk:18.1@aar')
api 'org.apache.httpcomponents:httpcore:4.4.6'
api 'org.apache.httpcomponents:httpmime:4.3.6'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
implementation 'id.zelory:compressor:3.0.1'
api 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.23'
// implementation 'io.realm:realm-gradle-plugin:10.11.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0-native-mt'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.github.smarteist:autoimageslider:1.4.0'
implementation("io.coil-kt:coil:2.2.2")
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'com.google.android.exoplayer:exoplayer:2.18.4'
implementation "com.airbnb.android:lottie:6.0.0"
// Realm
// implementation 'io.realm.kotlin:library-base:1.8.0'
// implementation 'io.realm.kotlin:library-sync:1.8.0'
// Hilt
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
// Coroutine Lifecycle Scopes
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.1'
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"
// implementation("com.google.android.play:app-update:2.1.0")
// implementation("com.google.android.play:app-update-ktx:2.1.0")
// test
testImplementation 'junit:junit'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
{
"project_info": {
"project_number": "947235480452",
"firebase_url": "https://yes-seatel-5bc80-default-rtdb.firebaseio.com",
"project_id": "yes-seatel-5bc80",
"storage_bucket": "yes-seatel-5bc80.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:947235480452:android:84778b65a0ae0be49ef3d1",
"android_client_info": {
"package_name": "com.seatel.mobilehall"
}
},
"oauth_client": [
{
"client_id": "947235480452-n3sh6i46dhathoa9mktkui5cjdoh1jgv.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCbKq3NIALi7OA3iXEReARd8HF-ecRKOxs"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "947235480452-n3sh6i46dhathoa9mktkui5cjdoh1jgv.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "947235480452-rji8lcnpdd1uv4skdo0eqoum58801j0t.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "com.seatel.seashop"
}
}
]
}
}
}
],
"configuration_version": "1"
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 7.1.2" type="baseline" client="gradle" dependencies="false" name="AGP (7.1.2)" variant="fatal" version="7.1.2">
<issue
id="NotSibling"
message="`@+id/txt_data_used` is not a sibling in the same `RelativeLayout`"
errorLine1=" android:layout_toEndOf=&quot;@+id/txt_data_used&quot;"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/layout/item_device_installment.xml"
line="96"
column="17"/>
</issue>
</issues>
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Realm
-dontnote io.realm.internal.SyncObjectServerFacade
-keep class io.realm.annotations.RealmModule
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.internal.Keep
-keep @io.realm.internal.Keep class * { *; }
-keep class io.realm.internal.KeepMember
-keep @io.realm.internal.KeepMember class * { @io.realm.internal.KeepMember *; }
-dontwarn javax.**
-dontwarn io.realm.**
-keep class io.realm.RealmCollection
-keep class io.realm.OrderedRealmCollection
-keepclasseswithmembernames class io.realm.**
-dontnote android.security.KeyStore
-dontwarn okio.Okio
-dontwarn okio.DeflaterSink
-dontnote com.android.org.conscrypt.SSLParametersImpl
-dontnote org.apache.harmony.xnet.provider.jsse.SSLParametersImpl
-dontnote sun.security.ssl.SSLContextImpl
#Gson models have to keep otherwise it will be crash
-keep class com.seatel.mobilehall.model.** { *; }
-keepattributes Signature
-keepattributes *Annotation*
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**
# Okio
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
-dontwarn okio.**
#-dontwarn com.squareup.okhttp3.**
#-keep class com.squareup.okhttp3.** { *; }
#-keep interface com.squareup.okhttp3.* { *; }
-dontwarn javax.annotation.**
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
-dontwarn com.google.**
-dontwarn com.android.**
-keep public class com.google.** { *; }
-keep public class com.android.** { *; }
#-dontwarn com.chipmong.**
-dontwarn com.seatel.mobilehall.ui.**
#-dontwarn com.unionpay.mobile.android.**
#-keep public class com.unionpay.mobile.android.** { *; }
-dontwarn org.apache.commons.**
-keep class org.apache.http.** { *; }
-dontwarn org.apache.http.**
-keep class com.facebook.** { *; }
-dontwarn com.facebook.**
# Preference objects are inflated via reflection
-keep public class android.support.v7.preference.Preference {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keep public class * extends android.support.v7.preference.Preference {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keep class androidx.appcompat.widget.** { *; }
{
"version": 3,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "com.seatel.mobilehall",
"variantName": "release",
"elements": [
{
"type": "SINGLE",
"filters": [],
"attributes": [],
"versionCode": 201907105,
"versionName": "2.3.5",
"outputFile": "app-release.apk"
}
],
"elementType": "File"
}
\ No newline at end of file
package com.seatel.seatel
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.seatel", appContext.packageName)
}
}
\ No newline at end of file
This diff is collapsed.
{
"camera": {
"captureResolution": "1080p"
},
"flash": {
"mode": "auto",
"alignment": "bottom_right"
},
"viewPlugin": {
"plugin": {
"id": "Barcode_ID",
"barcodePlugin": {
}
},
"cutoutConfig": {
"style": "rect",
"maxWidthPercent": "80%",
"maxHeightPercent": "80%",
"alignment": "center",
"ratioFromSize": {
"width": 100,
"height": 80
},
"strokeWidth": 1,
"cornerRadius": 3,
"strokeColor": "EC008C",
"outerColor": "000000",
"outerAlpha": 0.3,
"feedbackStrokeColor": "0099FF"
},
"scanFeedback": {
"style": "rect",
"strokeColor": "0099FF",
"fillColor": "220099FF",
"animationDuration": 150,
"blinkOnResult": true,
"beepOnResult": true,
"vibrateOnResult": true
},
"cancelOnResult": true
}
}
\ No newline at end of file
{
"camera" : {
"captureResolution" : "1080p",
"zoomGesture": true
},
"flash" : {
"mode": "manual",
"alignment": "bottom_right",
"imageOn": "flash_on",
"imageOff": "flash_off"
},
"viewPlugin" : {
"cutoutConfig" : {
"style": "rect",
"maxWidthPercent": "90%",
"maxHeightPercent": "90%",
"alignment": "center",
"strokeWidth": 2,
"cornerRadius": 4,
"strokeColor": "EC008C",
"outerColor": "000000",
"outerAlpha": 0.3,
"cropPadding": {
"x": -30,
"y": -90
},
"cropOffset": {
"x": 0,
"y": 90
},
"feedbackStrokeColor": "EC008C"
},
"scanFeedback" : {
"style": "rect",
"visualFeedbackRedrawTimeout": 100,
"strokeColor": "EC008C",
"fillColor" : "220099FF",
"beepOnResult": true,
"vibrateOnResult": true,
"strokeWidth": 2
},
"cancelOnResult" : true
}
}
package com.seatel.mobilehall.data.network
import com.seatel.mobilehall.util.Resource
import retrofit2.Response
abstract class BaseApiResponse {
suspend fun <T> safeApiCall(apiCall: suspend () -> Response<T>): Resource<T> {
try {
val response = apiCall()
if (response.isSuccessful) {
val body = response.body()
body?.let {
return Resource.Success(body)
}
}
return error("${response.code()} ${response.message()}")
} catch (e: Exception) {
return error(e.message ?: e.toString())
}
}
private fun <T> error(errorMessage: String): Resource<T> =
Resource.Error("Api Call Failed $errorMessage")
}
\ No newline at end of file
package com.seatel.mobilehall.data.network
import android.content.Context
import android.content.pm.PackageInfo
import com.jaredrummler.android.device.DeviceName.DeviceInfo
import com.jaredrummler.android.device.DeviceName
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import java.io.*
import java.lang.Exception
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.concurrent.Callable
import java.util.concurrent.Executors
object Devices {
var mMarketName: DeviceInfo? = null
val deviceModel: String
get() {
val mModel: String
mModel = Build.MODEL
return mModel
}
fun getDeviceID(context: Context): String {
val mModel: String
mModel = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
return mModel
}
fun getDeviceInfo(context: Context?) {
if (mMarketName == null) {
DeviceName.with(context)
.request { info, error ->
if (error == null && null != info) {
mMarketName = info
}
}
}
}
fun getDevicePublicIP(context: Context?): String? {
var value: String? = null
val es = Executors.newSingleThreadExecutor()
val result = es.submit(Callable {
try {
val url = URL("http://whatismyip.akamai.com/")
val urlConnection = url.openConnection() as HttpURLConnection
try {
val `in`: InputStream = BufferedInputStream(urlConnection.inputStream)
val r = BufferedReader(InputStreamReader(`in`))
val total = StringBuilder()
var line: String?
while (r.readLine().also { line = it } != null) {
total.append(line).append('\n')
}
urlConnection.disconnect()
return@Callable total.toString()
} finally {
urlConnection.disconnect()
}
} catch (e: IOException) {
Log.e("Public IP: ", e.message!!)
}
null
})
try {
value = result.get()
} catch (e: Exception) {
// failed
}
es.shutdown()
return value
}
val marketName: String
get() = if (mMarketName != null) {
mMarketName!!.marketName
} else {
""
}
val deviceOSVersion: String
get() {
val mOSVersion: String
mOSVersion = Build.VERSION.RELEASE
return mOSVersion
}
val deviceSDKVersion: Int
get() {
val mSdkVersion: Int
mSdkVersion = Build.VERSION.SDK_INT
return mSdkVersion
}
val deviceName: String
get() {
val manufacturer = Build.MANUFACTURER
val model = Build.MODEL
return if (model.startsWith(manufacturer)) {
capitalize(model)
} else capitalize(manufacturer) + " " + model
}
private fun capitalize(str: String): String {
if (TextUtils.isEmpty(str)) {
return str
}
val arr = str.toCharArray()
var capitalizeNext = true
var phrase = ""
for (c in arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += Character.toUpperCase(c)
capitalizeNext = false
continue
} else if (Character.isWhitespace(c)) {
capitalizeNext = true
}
phrase += c
}
return phrase
}
fun getAppVersionName(context: Context): String {
try {
return context.packageManager.getPackageInfo(
context.packageName, 0
).versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return "0.0"
}
fun getAppVersionCode(context: Context): Int {
val manager = context.packageManager
var info: PackageInfo? = null
try {
info = manager.getPackageInfo(
context.packageName, 0
)
return info.versionCode
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return 0
}
val deviceBrand: String
get() {
var mBrand = "UNKNOWN"
mBrand = Build.BOARD
return mBrand
}
val deviceProductName: String
get() {
var mBrand = "UNKNOWN"
mBrand = Build.PRODUCT
return mBrand
}
/***
* This Method user for get Application Hast Key in Base 64
*
* @param context
*/
fun getAppHashKey(context: Context) {
try {
val info = context.packageManager.getPackageInfo(
context.packageName, PackageManager.GET_SIGNATURES
)
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
}
} catch (e: PackageManager.NameNotFoundException) {
} catch (e: NoSuchAlgorithmException) {
}
}
val isEmulator: Boolean
get() = (Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
|| "google_sdk" == Build.PRODUCT)
}
\ No newline at end of file
package com.seatel.mobilehall.data.network
import android.content.Context
import com.google.gson.Gson
import com.seatel.mobilehall.data.prefs.LanguagePreference
import com.seatel.mobilehall.ui.lang.model.LanguageModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.lang.LanguageManager
import org.json.JSONObject
class GetLanguage(context: Context?) : SeatelJSONObjectRequest(context) {
override fun getFunctionName(): String {
return Constant.ALL_LANGUAGE
}
override fun onResponse(response: JSONObject?) {
super.onResponse(response)
val version = response?.optString("version", "0.1")
LanguagePreference.getInstance(context)?.setLanguageVersion(version)
LanguageManager.getInstance(context).clearAll()
LanguageManager.getInstance(context).updateLanguage(response)
val languageModels = ArrayList<LanguageModel>()
languageModels.add(LanguageModel(1, "ភាសាខ្មែរ", "km"))
languageModels.add(LanguageModel(2, "English", "en"))
languageModels.add(LanguageModel(3, "中文", "zh"))
LanguagePreference.getInstance(context)
?.setAppSharedLanguagePreference(Gson().toJson(languageModels))
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.network;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
* Created by Danny on 2/13/2018.
*/
public class InternetBroadcastReceiver extends BroadcastReceiver {
private static final int TYPE_WIFI = 1;
private static final int TYPE_MOBILE = 2;
private static final int TYPE_NOT_CONNECTED = 0;
private static final String CONNECT_TO_WIFI = "WIFI";
private static final String CONNECT_TO_MOBILE = "MOBILE";
private static final String NOT_CONNECT = "NOT_CONNECT";
public final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private OnInternetConnectionChangeListener onInternetConnectionChangeListener;
public void setOnInternetConnectionChangeListener(OnInternetConnectionChangeListener onInternetConnectionChangeListener) {
this.onInternetConnectionChangeListener = onInternetConnectionChangeListener;
}
@Override
public void onReceive(Context context, Intent intent) {
String status = getConnectivityStatusString(context);
Log.i("CONNECTION_CHANGE", "STATUS" + status);
if (status.equals(NOT_CONNECT)) {
Log.i("CONNECTION_CHANGE ", "INTERNET DISCONNECT");
// check !isConnected , cuz don't want to call back redundant
if (onInternetConnectionChangeListener != null) {
onInternetConnectionChangeListener.onDisconnected();
}
} else {
Log.i("CONNECTION_CHANGE ", "INTERNET CONNECTED");
// check !isConnected , cuz don't want to call back redundant
if (onInternetConnectionChangeListener != null) {
onInternetConnectionChangeListener.onConnected();
}
}
}
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = getConnectivityStatus(context);
String status = null;
if (conn == TYPE_WIFI) {
//status = "Wifi enabled";
status = CONNECT_TO_WIFI;
} else if (conn == TYPE_MOBILE) {
//status = "Mobile data enabled";
System.out.println(CONNECT_TO_MOBILE);
status = getNetworkClass(context);
} else if (conn == TYPE_NOT_CONNECTED) {
status = NOT_CONNECT;
}
return status;
}
public static String getNetworkClass(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null || !info.isConnected())
return "-"; //not connected
if (info.getType() == ConnectivityManager.TYPE_WIFI)
return "WIFI";
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
int networkType = info.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
return "4G";
default:
return "UNKNOWN";
}
}
return "UNKNOWN";
}
public interface OnInternetConnectionChangeListener {
void onDisconnected();
void onConnected();
}
}
package com.seatel.mobilehall.data.network;
import android.content.Context;
import android.util.Log;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.seatel.mobilehall.BuildConfig;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.UnsupportedEncodingException;
/**
* Created by Danny on 12/28/2017.
*/
public abstract class SeatelJSONArrayRequest extends SeatelRequest<JSONArray> {
public SeatelJSONArrayRequest(Context context) {
super(context);
}
@Override
protected Response<JSONArray> onParseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
try {
if (BuildConfig.DEBUG) {
Log.i("RESPONSE<<<:", this.getClass().getSimpleName() + " (" + getContext().getClass().getSimpleName() + ")");
Log.i("RESPONSE<<<:", this.getClass().getSimpleName() + " Status Code : " + response.statusCode);
Log.i("RESPONSE<<<:", this.getClass().getSimpleName() + " Data Response : " + jsonString);
}
} catch (Exception e) {
e.printStackTrace();
}
return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
package com.seatel.mobilehall.data.network;
import android.content.Context;
import android.util.Log;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.seatel.mobilehall.BuildConfig;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
/**
* Created by Danny on 12/28/2017.
*/
public abstract class SeatelJSONObjectRequest extends SeatelRequest<JSONObject> {
public SeatelJSONObjectRequest(Context context) {
super(context);
}
@Override
protected Response<JSONObject> onParseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
try {
if (BuildConfig.DEBUG && !jsonString.isEmpty()) {
Log.i("RESPONSE<<<", this.getClass().getSimpleName()
+ " (" + getContext().getClass().getSimpleName() + ") "
+ response.statusCode + " " + new JSONObject(jsonString).toString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
package com.seatel.mobilehall.data.network;
import android.content.Context;
import android.text.TextUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.VolleyError;
import com.seatel.mobilehall.BuildConfig;
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences;
import com.seatel.mobilehall.util.Constant;
import com.seatel.mobilehall.util.lang.LanguageManager;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Danny on 12/29/2017.
*/
public abstract class SeatelRequest<T> extends SeatelSuperRequest<T> {
SeatelRequest(Context context) {
super(context);
}
@Override
public Map<String, String> getAuthHeader() {
Map<String, String> stringStringMap = new HashMap<>();
String token = SeatelSharePreferences.Companion.getInstance(getContext()).getAccessToken();
if (!token.isEmpty())
stringStringMap.put("User ", SeatelSharePreferences.Companion.getInstance(getContext()).getAccessToken());
else stringStringMap.put("x-api-key", BuildConfig.CLIENT_ID);
return stringStringMap;
}
@Override
public String getBaseController() {
return Constant.BASE_CONTROLLER;
}
@Override
public String getLanguageCode() {
String languageCode = LanguageManager.Companion.getInstance(getContext()).getLanguageCode();
if (TextUtils.equals(languageCode.toLowerCase(), "kh")) {
return "KM";
} else if (TextUtils.equals(languageCode.toLowerCase(), "ch")) {
return "ZH";
} else {
return languageCode;
}
}
@Override
public String getBaseUrl() {
return BuildConfig.BASE_URL + getBaseController() + ((getFunctionName() != null) ? getFunctionName() : "");
}
@Override
public void onError(VolleyError error) {
if (error instanceof AuthFailureError) {
if (error.networkResponse.statusCode == 401) {
// SeatelUtils.showSessionExpired(getContext());
}
} else {
super.onError(error);
}
}
}
package com.seatel.mobilehall.data.network;
import android.content.Context;
import android.util.Log;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.seatel.mobilehall.BuildConfig;
import java.io.UnsupportedEncodingException;
/**
* Created by mac on 10/2/2018 AD.
*/
public class SeatelStringRequest extends SeatelRequest {
public SeatelStringRequest(Context context) {
super(context);
}
@Override
public String getFunctionName() {
return null;
}
@Override
protected Response<String> onParseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
try {
if (BuildConfig.DEBUG) {
Log.i("RESPONSE<<<:", this.getClass().getSimpleName() + " (" + getContext().getClass().getSimpleName() + ")");
Log.i("RESPONSE<<<:", this.getClass().getSimpleName() + " Status Code : " + response.statusCode);
Log.i("RESPONSE<<<:", this.getClass().getSimpleName() + " Data Response : " + parsed);
}
} catch (Exception e) {
e.printStackTrace();
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
}
package com.seatel.mobilehall.data.network;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
/**
* Created by Kevin on 9/26/2016.
*/
public abstract class SeatelSuperRequest<T> extends CoreRequest<T> {
private String contentType = "application/json; charset=utf-8";
private int method = Request.Method.GET;
public abstract String getLanguageCode();
public SeatelSuperRequest(Context context) {
super(context);
}
/**
* default GET
*/
@Override
public int getMethod() {
return method;
}
public void setMethod(int method) {
this.method = method;
}
@Override
public abstract String getBaseUrl();
public abstract String getBaseController();
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
@Override
public Map<String, String> onCreateHeader(Map<String, String> header) {
header = new HashMap<>();
header.put("X-App-Version", Devices.INSTANCE.getAppVersionName(getContext()));
header.put("X-Language", getLanguageCode().toLowerCase());
header.put("X-Latitude", "");
header.put("X-Longitude", "");
header.put("X-Timestamp", getTimestamp());
header.put("X-Timezone", getLocalTimezone());
header.put("X-Platform", "android");
header.put("X-OS-Version", Devices.INSTANCE.getDeviceOSVersion());
header.put("X-UDID", Devices.INSTANCE.getDeviceID(getContext()));
header.put("X-App-Signature", getAppSignatures());
if (getMethod() == Request.Method.POST || getMethod() == Request.Method.PUT) {
if (getContentType() != null)
header.put("Content-Type", contentType);
}
header.putAll(getAuthHeader());
Log.d("HEADER:>>>", this.getClass().getSimpleName() + "(" + getContext().getClass().getSimpleName() + ") : " + header.toString());
return header;
}
public String getTimestamp() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
TimeZone tz = TimeZone.getTimeZone("UTC");
df.setTimeZone(tz);
return df.format(new Date());
}
public abstract String getFunctionName();
public String getAppSignatures() {
return "";
}
public String getLocalTimezone() {
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
return tz.getID();
}
@Override
public void execute() {
super.execute();
try {
Log.d("EXECUTE:>>>", this.getClass().getSimpleName() + "(" + getContext().getClass().getSimpleName() + ") : "
+ getMethodName(getMethod()) + " " + getRequestUrl());
if (!TextUtils.isEmpty(onGetBodyRequest()))
Log.d("EXECUTE:>>>", this.getClass().getSimpleName() + " JSON data " + new JSONObject(onGetBodyRequest()).toString(1));
else
Log.d("EXECUTE:>>>", this.getClass().getSimpleName() + " JSON data null");
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getErrorMessageFrom(VolleyError volleyError, String defaultMsg) {
if (volleyError instanceof NoConnectionError) {
return "Please check your internet connection and try again!";
} else if (volleyError instanceof TimeoutError) {
return "Please check your internet connection and try again!";
}
try {
String errorMessage = new String(volleyError.networkResponse.data);
JSONObject jsonObject = new JSONObject(errorMessage);
JSONArray jsonArrayError = jsonObject.optJSONArray("errors");
if (jsonArrayError != null && jsonArrayError.length() > 0) {
JSONObject jsonObjectError = jsonArrayError.getJSONObject(0);
return jsonObjectError.optString("message", defaultMsg);
} else {
jsonObject.optString("message", defaultMsg);
}
return jsonObject.optString("message", defaultMsg);
} catch (Exception e) {
try {
String msg = new String(volleyError.networkResponse.data);
if (TextUtils.isEmpty(msg)) {
msg = defaultMsg;
}
return msg;
} catch (Exception ee) {
return defaultMsg;
}
}
}
public static String getErrorMessageFrom(VolleyError volleyError) {
return getErrorMessageFrom(volleyError, "");
}
public abstract Map<String, String> getAuthHeader();
/**
* use for display method request name as string only
*/
private String getMethodName(int method) {
if (method == Request.Method.GET)
return "GET";
if (method == Request.Method.POST)
return "POST";
if (method == Request.Method.PUT)
return "PUT";
if (method == Request.Method.DELETE)
return "DELETE";
if (method == Request.Method.HEAD)
return "HEAD";
if (method == Request.Method.OPTIONS)
return "OPTIONS";
if (method == Request.Method.TRACE)
return "TRACE";
if (method == Request.Method.PATCH)
return "PATCH";
return "UNKNOWN METHOD";
}
}
package com.seatel.mobilehall.data.network.repository
import com.seatel.mobilehall.data.network.BaseApiResponse
import com.seatel.mobilehall.data.network.retrofit.RetrofitInstance
import com.seatel.mobilehall.ui.home.model.BannersModel
import com.seatel.mobilehall.util.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
class HomeRepository : BaseApiResponse() {
suspend fun getBanners(lang: String) = RetrofitInstance.seatelApi.getBanners(lang)
suspend fun requestBanners(lang: String): Flow<Resource<List<BannersModel>>> {
return flow {
emit(Resource.Loading())
emit(safeApiCall {
RetrofitInstance.seatelApi.getBanners(lang)
})
}.flowOn(Dispatchers.IO)
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.network.repository
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.seatel.mobilehall.data.network.viewmodel.HomeViewModel
class ViewModelProviderFactory(
val app: Application, val repository: HomeRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
// if (modelClass.isAssignableFrom())
return HomeViewModel(app, repository) as T
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.network.retrofit
import com.seatel.mobilehall.ui.home.model.BannersModel
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface API {
@GET("app-promotions/banners")
suspend fun getBanners(
@Query("lang") lang: String
): Response<List<BannersModel>>
}
\ No newline at end of file
package com.seatel.mobilehall.data.network.retrofit
import com.seatel.mobilehall.BuildConfig
import com.seatel.mobilehall.data.network.Devices
import com.seatel.mobilehall.ui.application.MyApplication
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class RetrofitInstance {
companion object {
private val interceptor: HttpLoggingInterceptor =
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
private val client = OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(Interceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("X-App-Version", Devices.getAppVersionName(MyApplication.appContext))
.addHeader("X-Language", "en").addHeader("X-Latitude", "")
.addHeader("X-Longitude", "").addHeader("X-Timestamp", "")
.addHeader("X-Timezone", "").addHeader("X-Platform", "Android")
.addHeader("X-OS-Version", "1.1.1").addHeader("X-UDID", "")
.addHeader("X-App-Signature", "")
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("x-api-key", BuildConfig.CLIENT_ID).build()
chain.proceed(request)
}).addInterceptor(interceptor).build()
private val retrofit = Retrofit.Builder().baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).client(client).build()
val seatelApi by lazy {
retrofit.create(API::class.java)
}
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.network.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.seatel.mobilehall.data.network.repository.HomeRepository
import com.seatel.mobilehall.ui.home.model.BannersModel
import com.seatel.mobilehall.util.Resource
import kotlinx.coroutines.launch
class HomeViewModel(
app: Application, private val homeRepository: HomeRepository
) : AndroidViewModel(app) {
private val _bannerResponse = MutableLiveData<Resource<List<BannersModel>>>()
val bannersResponse: LiveData<Resource<List<BannersModel>>> = _bannerResponse
fun fetchBanners(lang: String) = viewModelScope.launch {
homeRepository.requestBanners(lang).collect {
_bannerResponse.value = it
}
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.prefs
import android.content.Context
import android.content.SharedPreferences
class LanguagePreference(context: Context) {
private var sharedPref: SharedPreferences? = null
init {
this.sharedPref = context.getSharedPreferences("SeatelLanguage", Context.MODE_PRIVATE)
}
companion object {
@Volatile
private var instance: LanguagePreference? = null
fun getInstance(context: Context): LanguagePreference? {
if (instance == null) // NOT thread safe!
instance = LanguagePreference(context)
return instance
}
}
fun getAppSharedLanguageCodePreference(): String? {
return sharedPref?.getString("LANGUAGE_CODE", "")
}
fun setAppSharedLanguageCodePreference(languageCode: String) {
sharedPref?.edit()?.putString("LANGUAGE_CODE", languageCode)?.apply()
}
fun setLanguageVersion(languageVersion: String?) {
sharedPref?.edit()?.putString("LANGUAGES_VERSION", languageVersion)?.apply()
}
fun getLanguageVersion(): String? {
return sharedPref?.getString("LANGUAGES_VERSION", "")
}
fun getAppSharedLanguagePreference(): String? {
return sharedPref?.getString("LANGUAGE", "")
}
fun setAppSharedLanguagePreference(languages: String) {
sharedPref?.edit()?.putString("LANGUAGE", languages)?.apply()
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.prefs
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Bitmap
class ProfileSharedPreference(context: Context) {
private var sharedPref: SharedPreferences? = null
init {
this.sharedPref = context.getSharedPreferences("SeatelPreferences", Context.MODE_PRIVATE)
}
companion object {
@Volatile
private var instance: ProfileSharedPreference? = null
fun getInstance(context: Context): ProfileSharedPreference? {
if (instance == null) // NOT thread safe!
instance = ProfileSharedPreference(context)
return instance
}
}
fun getDocumentType(): String? {
return sharedPref?.getString("DOCUMENT_TYPE", "")
}
fun setDocumentType(documentType: String?) {
sharedPref?.edit()?.putString("DOCUMENT_TYPE", documentType)?.apply()
}
fun getId(): String? {
return sharedPref?.getString("ID", "")
}
fun setId(id: String?) {
sharedPref?.edit()?.putString("ID", id)?.apply()
}
fun getName(): String? {
return sharedPref?.getString("NAME", "")
}
fun setName(name: String?) {
sharedPref?.edit()?.putString("NAME", name)?.apply()
}
fun getGender(): String? {
return sharedPref?.getString("GENDER", "")
}
fun setGender(gender: String?) {
sharedPref?.edit()?.putString("GENDER", gender)?.apply()
}
fun getDay(): String? {
return sharedPref?.getString("DAY", "")
}
fun setDay(day: String?) {
sharedPref?.edit()?.putString("DAY", day)?.apply()
}
fun getMonth(): String? {
return sharedPref?.getString("MONTH", "")
}
fun setMonth(month: String?) {
sharedPref?.edit()?.putString("MONTH", month)?.apply()
}
fun getYear(): String? {
return sharedPref?.getString("YEAR", "")
}
fun setYear(year: String?) {
sharedPref?.edit()?.putString("YEAR", year)?.apply()
}
fun getDob(): String? {
return sharedPref?.getString("DOB", "")
}
fun setDob(dob: String?) {
sharedPref?.edit()?.putString("DOB", dob)?.apply()
}
fun setFrontId(fontId: String?) {
sharedPref?.edit()?.putString("FONTID", fontId)?.apply()
}
fun getFrontId(): String? {
return sharedPref?.getString("FONTID", "")
}
fun setBackId(backId: String?) {
sharedPref?.edit()?.putString("BACKID", backId)?.apply()
}
fun getBackId(): String? {
return sharedPref?.getString("BACKID", "")
}
fun setProfileImage(profileImage: String?) {
sharedPref?.edit()?.putString("PROFILE", profileImage)?.apply()
}
fun getProfileImage(): String? {
return sharedPref?.getString("PROFILE", "")
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.prefs
import android.content.Context
import android.content.SharedPreferences
class SeatelSharePreferences(context: Context) {
private var sharedPref: SharedPreferences? = null
init {
this.sharedPref = context.getSharedPreferences("SeatelPreferences", Context.MODE_PRIVATE)
}
companion object {
@Volatile
private var instance: SeatelSharePreferences? = null
fun getInstance(context: Context): SeatelSharePreferences? {
if (instance == null) // NOT thread safe!
instance = SeatelSharePreferences(context)
return instance
}
}
fun getLoginSuccess(): String? {
return sharedPref?.getString("IS_LOGIN_SUCCESS", "")
}
fun setLoginSuccess(isSuccess: String?) {
sharedPref?.edit()?.putString("IS_LOGIN_SUCCESS", isSuccess)?.apply()
}
fun getMainPhoneLogin(): String? {
return sharedPref?.getString("MAIN_PHONE_NUMBER_LOGIN", "")
}
fun setMainPhoneLogin(phoneLogin: String) {
sharedPref?.edit()?.putString("MAIN_PHONE_NUMBER_LOGIN", phoneLogin)?.apply()
}
fun getAccessToken(): String? {
return sharedPref?.getString("ACCESS_TOKEN", "")
}
fun setAccessToken(accessToken: String) {
sharedPref?.edit()?.putString("ACCESS_TOKEN", accessToken)?.apply()
}
fun getNoneSeatelNumber(): Boolean? {
return sharedPref?.getBoolean("IS_NONE_SEATEL_NUMBER", false)
}
fun setNoneSeatelNumber(noneSeatelNumber: Boolean) {
sharedPref?.edit()?.putBoolean("IS_NONE_SEATEL_NUMBER", noneSeatelNumber)?.apply()
}
fun getPasswordLogin(): String? {
return sharedPref?.getString("PASSWORD_NUMBER_LOGIN", "")
}
fun setPasswordLogin(passwordLogin: String) {
sharedPref?.edit()?.putString("PASSWORD_NUMBER_LOGIN", passwordLogin)?.apply()
}
fun getPhoneLogin(): String? {
return sharedPref?.getString("PHONE_NUMBER_LOGIN", "")
}
fun setPhoneLogin(phoneLogin: String) {
sharedPref?.edit()?.putString("PHONE_NUMBER_LOGIN", phoneLogin)?.apply()
}
fun setShowClaimFreeSim(freeSim: Boolean?) {
sharedPref?.edit()?.putBoolean("CLAIM_FREE_SIM_SHOW", freeSim!!)
?.apply()
}
fun getShowClaimFreeSim(): Boolean? {
return sharedPref?.getBoolean("CLAIM_FREE_SIM_SHOW", false)
}
fun setUserInfo(userInfo: String?) {
sharedPref?.edit()?.putString("USER_INFO", userInfo)?.apply()
}
fun getUserInfo(): String? {
return sharedPref?.getString("USER_INFO", "")
}
fun clearAll() {
sharedPref!!.edit().clear().apply()
}
fun setUsername(username: String?) {
sharedPref?.edit()?.putString("USER_NAME", username)?.apply()
}
fun getUsername(): String? {
return sharedPref?.getString("USER_NAME", "")
}
fun setUserPhone(userPhone: String) {
sharedPref?.edit()?.putString("USER_PHONE", userPhone)?.apply()
}
fun getUserPhone(): String? {
return sharedPref?.getString("USER_PHONE", "")
}
fun getRegisterPush(): Boolean {
return sharedPref?.getBoolean("IS_REGISTER_PUSH", false)!!
}
fun setRegisterPush(isSuccess: Boolean?) {
sharedPref?.edit()?.putBoolean("IS_REGISTER_PUSH", isSuccess!!)
?.apply()
}
fun setIsPostPaid(isPostPaid: Boolean?) {
sharedPref?.edit()?.putBoolean("IS_ACCOUNT_POST_PAID", isPostPaid!!)
?.apply()
}
fun getIsPostPaid(): Boolean? {
return sharedPref?.getBoolean("IS_ACCOUNT_POST_PAID", false)
}
fun setPhoneFilterCategories(data: String?) {
sharedPref?.edit()?.putString("PhONE_FILTER_CATEGORIES", data)
?.apply()
}
fun getPhoneFilterCategories(): String? {
return sharedPref?.getString("PhONE_FILTER_CATEGORIES", "")
}
fun setSubPlan(value: String?) {
sharedPref?.edit()?.putString("SUB_PLAN", value)?.apply()
}
fun getSubPlan(): String? {
return sharedPref?.getString("SUB_PLAN", "")
}
fun setHasInstalmentPlan(value: Boolean?) {
sharedPref?.edit()?.putBoolean("HAS_INSTALMENT_PLAN", value!!)
?.apply()
}
fun isHasInstalmentPlan(): Boolean? {
return sharedPref?.getBoolean("HAS_INSTALMENT_PLAN", false)
}
fun setMainScreenData(mainScreenData: String?) {
sharedPref?.edit()?.putString("MAIN_SCREEN_DATA", mainScreenData)
?.apply()
}
fun getMainScreenData(): String? {
return sharedPref?.getString("MAIN_SCREEN_DATA", "")
}
fun setProvinceData(province: Set<String?>?) {
sharedPref?.edit()?.putStringSet("PROVINCE", province)?.apply()
}
fun getProvinceData(): Set<String?>? {
return sharedPref?.getStringSet("PROVINCE", null)
}
fun setHomeCategory(homeCategory: String) {
sharedPref?.edit()?.putString("HOME_CATEGORY", homeCategory)?.apply()
}
fun getHomeCategory(): String? {
return sharedPref?.getString("HOME_CATEGORY", "")
}
}
\ No newline at end of file
package com.seatel.mobilehall.data.realm
import io.realm.RealmObject
open class WordRealmObject : RealmObject() {
private var value: String? = null
private var key: String? = null
private var languageCode: String? = null
private var version: String? = null
fun getValue(): String? {
return value
}
fun setValue(value: String) {
this.value = value
}
fun getKey(): String? {
return key
}
fun setKey(key: String) {
this.key = key
}
fun getLanguageCode(): String? {
return languageCode
}
fun setLanguageCode(languageCode: String) {
this.languageCode = languageCode
}
fun getVersion(): String? {
return version
}
fun setVersion(version: String) {
this.version = version
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.application
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.PackageManager
import android.util.Log
import android.util.Base64
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
class AppSignatureHelper(context: Context) : ContextWrapper(context) {
companion object {
val TAG = AppSignatureHelper::class.java.simpleName
private val HASH_TYPE = "SHA-256"
val NUM_HASHED_BYTES = 9
val NUM_BASE64_CHAR = 11
}
fun getAppSignatures(): ArrayList<String> {
val appCodes = ArrayList<String>()
return try {
// Get all package signatures for the current package
val packageName = packageName
val packageManager = packageManager
val signatures = packageManager.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES).signatures
// For each signature create a compatible hash
signatures
.mapNotNull { hash(packageName, it.toCharsString()) }
.mapTo(appCodes) { it }
return appCodes
} catch (e: PackageManager.NameNotFoundException) {
Log.e(TAG, "Unable to find package to obtain hash.", e)
ArrayList<String>()
}
}
private fun hash(packageName: String, signature: String): String? {
val appInfo = "$packageName $signature"
return try {
val messageDigest = MessageDigest.getInstance(HASH_TYPE)
messageDigest.update(appInfo.toByteArray(StandardCharsets.UTF_8))
var hashSignature = messageDigest.digest()
// truncated into NUM_HASHED_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES)
// encode into Base64
var base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING or Base64.NO_WRAP)
base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR)
Log.d(TAG, "pkg: $packageName -- hash: $base64Hash")
base64Hash
} catch (e: NoSuchAlgorithmException) {
Log.e(TAG, "hash:NoSuchAlgorithm", e)
null
}
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.application
import android.content.Context
import android.os.StrictMode
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.facebook.drawee.backends.pipeline.Fresco
import dagger.hilt.android.HiltAndroidApp
import io.realm.Realm
import io.realm.RealmConfiguration
@HiltAndroidApp
class MyApplication : MultiDexApplication() {
private lateinit var realmConfiguration: RealmConfiguration
override fun onCreate() {
super.onCreate()
MyApplication.appContext = applicationContext
Realm.init(this)
Fresco.initialize(this)
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
}
//Clear Realm Table
private fun initRealm() {
realmConfiguration = RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.build()
Realm.setDefaultConfiguration(realmConfiguration)
}
companion object {
/**
* isInternetConnected default value is true becuz don't wan't to show snackbar when app open
* with internet have connected
*/
var isInternetConnected = true
var isUpdatedLangauge = false
var isFirstInstall = false
var isPushTokenRegister = -1
var isAddnewNumberDone = false
var badgeCartCount = 0
var isUnlimitedInternet = false
var flagAppResume = false
var flagAppResumeFirst = -1
var appRunning = false
lateinit var appContext: Context
}
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this)
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.base.activity
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.seatel.mobilehall.data.network.InternetBroadcastReceiver
abstract class CoreActivity : AppCompatActivity(),
InternetBroadcastReceiver.OnInternetConnectionChangeListener {
private var intentFilter: IntentFilter? = null
private var receiver: InternetBroadcastReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
intentFilter = IntentFilter()
intentFilter!!.addAction(InternetBroadcastReceiver.CONNECTIVITY_ACTION)
receiver = InternetBroadcastReceiver()
receiver!!.setOnInternetConnectionChangeListener(this)
}
override fun onResume() {
super.onResume()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onResume")
registerReceiver(receiver, intentFilter)
}
override fun onPause() {
super.onPause()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onPause")
unregisterReceiver(receiver)
}
override fun onStop() {
super.onStop()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onStop")
}
override fun onStart() {
super.onStart()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onStart")
}
override fun onRestart() {
super.onRestart()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onRestart")
}
override fun onPostResume() {
super.onPostResume()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onPostResume")
}
override fun onDestroy() {
super.onDestroy()
Log.i("Activity Lifecycle", javaClass.simpleName + "=======> onDestroy")
}
override fun onDisconnected() {
onInternetDisconnect()
}
override fun onConnected() {
onInternetConnect()
}
abstract fun onInternetDisconnect()
abstract fun onInternetConnect()
}
\ No newline at end of file
package com.seatel.mobilehall.ui.base.adapter
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.R
abstract class BaseAdapter<V : RecyclerView.ViewHolder> : RecyclerView.Adapter<V>() {
private var lastPosition = -1
private var delay: Handler? = null
fun setMyAnimation(itemView: View, position: Int, animation: Animation) {
delay = Handler(Looper.getMainLooper())
delay?.postDelayed({
if (position > lastPosition) {
itemView.visibility = View.VISIBLE
/* val animation = AnimationUtils.loadAnimation(
itemView.context,
R.anim.anim_recycler_item
) as Animation*/
itemView.startAnimation(animation)
lastPosition = position
}
delay?.removeCallbacksAndMessages(this)
delay = null
}, 500 + (position * 20).toLong())
}
fun setAnimations(itemView: View, position: Int) {
delay = Handler(Looper.getMainLooper())
delay?.postDelayed({
if (position > lastPosition) {
itemView.visibility = View.VISIBLE
val animation = AnimationUtils.loadAnimation(
itemView.context,
R.anim.anim_recycler_item
) as Animation
itemView.startAnimation(animation)
lastPosition = position
}
delay?.removeCallbacksAndMessages(this)
delay = null
}, 500 + (position * 20).toLong())
}
fun getLastPosition(): Int {
return lastPosition
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.base.adapter;
import android.content.Context;
import android.view.View;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.seatel.mobilehall.R;
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest;
import com.seatel.mobilehall.util.customview.ErrorHandleView;
import org.json.JSONObject;
import java.util.HashMap;
/**
* Created by Danny on 1/25/2018.
*/
public abstract class BaseCartAdapter extends RecyclerView.Adapter {
private Context context;
private final ErrorHandleView errorHandleView;
private int offset = 0;
private boolean isLoadingData;
private boolean isDone;
private OnDataResponse onDataResponse;
private RecyclerView mRecyclerView;
public BaseCartAdapter(Context context, ErrorHandleView errorHandleView) {
setContext(context);
this.errorHandleView = errorHandleView;
}
public BaseCartAdapter(Context context, ErrorHandleView errorHandleView, RecyclerView recyclerView, final SwipeRefreshLayout swipeRefreshLayout) {
this(context, errorHandleView);
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(context, R.color.colorPrimary));
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
setOffset(0);
onRequestData(onDataResponse);
swipeRefreshLayout.setRefreshing(false);
}
});
}
mRecyclerView = recyclerView;
if (recyclerView != null) {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastVisibleItem;
lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (!isLoadingData && lastVisibleItem > getItemCount() - 5 && !isDone) {
setOffset(getItemCount());
onRequestData(onDataResponse);
}
}
});
}
}
public void onReloadData() {
setOffset(0);
onRequestData(onDataResponse);
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
/**
* call this function need to override getUrlRequestFunctionName()
*/
public void onRequestData(final OnDataResponse onDataResponse) {
this.onDataResponse = onDataResponse;
setDone(false);
isLoadingData = true;
if (errorHandleView != null)
errorHandleView.setViewMode(ErrorHandleView.Mode.LOADING);
new SeatelJSONObjectRequest(getContext()) {
@Override
public String getFunctionName() {
return getUrlRequestFunctionName();
}
@Override
public void onGetUrlParams(RequestParams requestParams) {
requestParams.put("limit", getLimit());
requestParams.put("offset", offset);
HashMap<String, String> tmpParams = new HashMap<>();
getRequestParams(tmpParams);
for (String key : tmpParams.keySet()) {
requestParams.put(key, tmpParams.get(key));
}
super.onGetUrlParams(requestParams);
}
}.setOnErrorListener(new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
isLoadingData = false;
setDone(true);
if (errorHandleView != null) {
if (mRecyclerView != null) {
mRecyclerView.setVisibility(View.INVISIBLE);
}
if (error instanceof NoConnectionError)
errorHandleView.setViewMode(ErrorHandleView.Mode.NO_INTERNET);
else if (error instanceof TimeoutError)
errorHandleView.setViewMode(ErrorHandleView.Mode.TIME_OUT);
else {
if (offset == 0) {
errorHandleView.setErrorMessage(context.getString(R.string.no_item_on_my_cart));
errorHandleView.setViewMode(ErrorHandleView.Mode.NO_DATA);
} else errorHandleView.setVisibility(View.GONE);
}
} else {
if (offset == 0) {
errorHandleView.setErrorMessage(context.getString(R.string.no_item_on_my_cart));
errorHandleView.setViewMode(ErrorHandleView.Mode.NO_DATA);
} else errorHandleView.setVisibility(View.GONE);
}
}
}).execute(new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
isLoadingData = false;
onDataResponse.onResponse(response);
if (errorHandleView != null)
if (getItemCount() == 0 && isDone) {
errorHandleView.setErrorMessage(context.getString(R.string.no_item_on_my_cart));
errorHandleView.setViewMode(ErrorHandleView.Mode.NO_DATA);
} else {
if (mRecyclerView != null) {
mRecyclerView.setVisibility(View.VISIBLE);
}
errorHandleView.setVisibility(View.GONE);
}
}
});
}
public abstract String getUrlRequestFunctionName();
public void getRequestParams(HashMap<String, String> params) {
}
/**
* if your adapter need load more data you need to call this function to true when data response < getLimit()
*
* @param done if true not load data anymore
*/
public void setDone(boolean done) {
isDone = done;
}
public int getLimit() {
return 20;
}
public interface OnDataResponse {
void onResponse(JSONObject onResponse);
}
}
package com.seatel.mobilehall.ui.base.adapter
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
/**
*
*
* @author Noel
* @version
* @created on 18-Oct-18
*/
abstract class BaseListFragment : BaseFragment() {
protected var mRecyclerView: RecyclerView? = null
protected var mLayoutManager: RecyclerView.LayoutManager? = null
protected lateinit var mAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>
private var totalItemCount: Int = 0
private var lastVisibleItem: Int = 0
protected var isAllLoadedItem: Boolean = false
protected var loading: Boolean = true
private val visibleThreshold = 5
// protected var limit = 20
protected var offset = 0
protected var isScrolling = false
protected var isScrollDown = false
private val onScrollListener: RecyclerView.OnScrollListener =
object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (mRecyclerView?.layoutManager is LinearLayoutManager) {
if (dy > 0) {
// if (isFirstLoadData && !loading) {
// loadFirstData()
// } else {
if (!loading && !isAllLoadedItem) {
val linearLayoutManager =
mRecyclerView?.layoutManager as LinearLayoutManager
totalItemCount = linearLayoutManager.itemCount
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition()
if (totalItemCount <= lastVisibleItem + visibleThreshold) {
loading = true
loadMore()
}
// }
}
isScrollDown = true
onScrollUp()
} else {
isScrollDown = false
onScrollDown()
}
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
when (newState) {
RecyclerView.SCROLL_STATE_IDLE -> {
onStopScroll()
isScrolling = false
}
RecyclerView.SCROLL_STATE_DRAGGING -> {
onScrolling()
isScrolling = true
}
}
}
}
abstract fun initRecyclerView(): RecyclerView
abstract fun initLayoutManager(): RecyclerView.LayoutManager
abstract fun initAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initListRecycler()
init()
initEvent()
}
protected fun initListRecycler() {
mRecyclerView = initRecyclerView()
mLayoutManager = initLayoutManager()
mAdapter = initAdapter()
mRecyclerView?.setHasFixedSize(true)
mRecyclerView?.layoutManager = mLayoutManager
mRecyclerView?.adapter = mAdapter
}
open fun init() {
}
open fun initEvent() {
mRecyclerView?.addOnScrollListener(onScrollListener)
}
open fun loadMore() {
}
protected fun returnDefaultLimitOffset() {
offset = 0
isAllLoadedItem = false
loading = false
}
open fun limit(): Int {
return 20
}
protected open fun onScrollUp() {
}
protected open fun onScrollDown() {
}
protected open fun onScrolling() {}
protected open fun onStopScroll() {}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.base.adapter
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.Filter
import android.widget.Filterable
import com.seatel.mobilehall.ui.home.viewholder.BaseViewHolder
abstract class BaseRecyclerAdapter<T>() : RecyclerView.Adapter<BaseViewHolder<T>>(), Filterable{
var mData: List<T> = ArrayList()
var mDataDisplay: List<T> = ArrayList()
var onItemClickListener: OnItemClickListener<T>? = null
constructor(mData: List<T>) : this() {
this.mData = mData
this.mDataDisplay = mData
}
companion object {
const val ITEM_HEADER = 0
const val ITEM_CONTENT = 1
}
fun setData(mData: List<T>) {
this.mData = mData
notifyDataSetChanged()
}
fun getItem(): List<T> {
return mDataDisplay
}
open fun getItem(position: Int): T {
return mDataDisplay[position]
}
override fun getItemCount() = mDataDisplay.size
override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(holder.itemView, holder.adapterPosition, getItem(holder.adapterPosition))
}
holder.binData(this)
}
override fun onViewRecycled(holder: BaseViewHolder<T>) {
super.onViewRecycled(holder)
holder.onViewRecycler()
}
interface OnItemClickListener<in T> {
fun onItemClick(v: View, position: Int, data: T)
fun onItemLongClick(position: Int, data: T){}
fun onChildViewClick(position: Int, data: T){}
}
@Suppress("UNCHECKED_CAST")
/**
* Single Click
*/
class RecyclerTouchListener<T>(context: Context, recycleView: RecyclerView, private val mItemClickListener: OnItemClickListener<T>) : RecyclerView.OnItemTouchListener {
private val mGestureDetector: GestureDetector
init {
mGestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
override fun onLongPress(e: MotionEvent) {
val child = recycleView.findChildViewUnder(e.x, e.y)
if (child != null && true && recycleView.adapter is BaseRecyclerAdapter<*>) {
val baseAdapter = recycleView.adapter as BaseRecyclerAdapter<*>
mItemClickListener.onItemLongClick(recycleView.getChildAdapterPosition(child), baseAdapter.getItem(recycleView.getChildAdapterPosition(child)) as T)
}
}
})
}
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
val child = rv.findChildViewUnder(e.x, e.y)
if (child != null && mGestureDetector.onTouchEvent(e) && rv.adapter is BaseRecyclerAdapter<*>) {
val baseAdapter = rv.adapter as BaseRecyclerAdapter<*>
mItemClickListener.onItemClick(child, rv.getChildAdapterPosition(child), (baseAdapter.getItem(rv.getChildAdapterPosition(child)) as T?)!!)
}
return false
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
}
}
override fun getFilter(): Filter? {
return null
}
}
package com.seatel.mobilehall.ui.base.fragment
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.login.model.ProfileModel
import com.google.gson.Gson
abstract class BaseFragment : Fragment() {
private lateinit var mContext: Context
private var mLayoutId: Int = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return LayoutInflater.from(mContext).inflate(getFragmentLayoutId(), container, false)
}
fun setFragmentLayout(layoutId: Int) {
this.mLayoutId = layoutId
}
fun getFragmentLayoutId(): Int {
return mLayoutId
}
fun getmContext(): Context {
return mContext
}
fun setmContext(mContext: Context) {
this.mContext = mContext
}
open fun isKeyboardHided(): Boolean {
return false
}
open fun hideKeyBoard() {
}
open fun onBackPress() {}
/*Show toast*/
protected fun showToast(msg: String) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show()
}
/*Log debug*/
protected fun showLog(key: String, value: String) {
Log.d(key, value)
}
fun getMainPhoneLogin(): String {
return SeatelSharePreferences.getInstance(requireContext())?.getMainPhoneLogin()!!
}
fun getPhoneLogin(): String {
return SeatelSharePreferences.getInstance(requireContext())?.getPhoneLogin()!!
}
fun getProfile(): ProfileModel {
return if (!TextUtils.isEmpty(
SeatelSharePreferences.getInstance(requireContext())?.getUserInfo()
)
)
Gson().fromJson(
SeatelSharePreferences.getInstance(requireContext())?.getUserInfo(),
ProfileModel::class.java
)
else ProfileModel()
}
fun isPostPaidAccount(): Boolean {
return SeatelSharePreferences.getInstance(requireContext())?.getIsPostPaid()!!
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.base.interactor
import com.android.volley.VolleyError
import org.json.JSONObject
interface RegisterPushTokenInteractor{
interface View{
fun onRegisterPushTokenSucceed(response: JSONObject)
fun onRegisterPushTokenFailed(error:VolleyError)
}
interface Presenter{
fun onRegisterPushToken(token: String, phoneNumber: String)
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.base.presenter
import android.content.Context
import com.android.volley.Request
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.base.interactor.RegisterPushTokenInteractor
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import org.json.JSONException
import org.json.JSONObject
class RegisterPushTokenPresenter(
private var mContext: Context,
private var mPushToken: RegisterPushTokenInteractor.View
) : RegisterPushTokenInteractor.Presenter {
override fun onRegisterPushToken(token: String, phoneNumber: String) {
postPinVerifyRequest(token, phoneNumber).setOnErrorListener { error ->
mPushToken.onRegisterPushTokenFailed(error)
}.setOnResponseListener { response ->
mPushToken.onRegisterPushTokenSucceed(response as JSONObject)
}.execute()
}
private fun postPinVerifyRequest(
token: String,
phoneNumber: String
): SeatelJSONObjectRequest {
return object : SeatelJSONObjectRequest(mContext) {
override fun onGetBodyRequest(): String {
val data = JSONObject()
try {
data.put(
"deviceId",
SeatelUtils.getDeviceId(mContext)
)
data.put("token", token)
data.put("phoneNumber", phoneNumber)
} catch (e: JSONException) {
e.printStackTrace()
}
return data.toString()
}
override fun getFunctionName(): String {
return Constant.REGISTER_PUSH_TOKEN
}
override fun getMethod(): Int {
return Request.Method.PUT
}
}
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.home.activity
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.seatel.mobilehall.R
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_ali_pay_mpay_payment.*
import kotlinx.android.synthetic.main.activity_base.*
import java.util.*
class AliPayMpayPaymentActivity : BaseActivity() {
private lateinit var mUrlPay: String
private var mAmount: Double = 0.0
private var isABAPay = false
private var isShowValentineDayPromotion = false
private var isOpenDeepLink = false
private val mWebViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
if (url != null && view != null) {
onPageFinish(view, url)
}
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
if (url.contains("about:blank"))
view.goBack()
showHideLoading(false)
}
override fun onReceivedError(
view: WebView,
request: WebResourceRequest,
error: WebResourceError
) {
// view.loadUrl("about:blank")
super.onReceivedError(view, request, error)
showHideLoading(false)
// if (!isOpenDeepLink)
// closeWingPaymentWithError()
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
if (isABAPay) {
val url = request?.url.toString()
val host = request?.url?.host.toString()
val scheme = request?.url?.scheme.toString()
if (isPaywayDeeplink(host, scheme)) {
openDeeplink(url)
return false
}
if (isOpenDeepLink)
return false
view?.loadUrl(url)
return true
} else {
return super.shouldOverrideUrlLoading(view, request)
}
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (isABAPay) {
val uri = Uri.parse(url)
val host = uri.host
val scheme = uri.scheme
if (isPaywayDeeplink(host!!, scheme!!)) {
if (url != null) {
openDeeplink(url)
}
return false
}
if (isOpenDeepLink)
return false
view?.loadUrl(url!!)
return true
} else {
return super.shouldOverrideUrlLoading(view, url)
}
}
}
private fun openDeeplink(url: String) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
val packageManager = this.packageManager
val resolvedActivities = packageManager.queryIntentActivities(intent, 0)
if (resolvedActivities.size > 0)
startActivity(intent)
else gotoPlayStore()
isOpenDeepLink = true
}
private fun gotoPlayStore() {
try {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.paygo24.ibank")
)
)
} catch (obj: android.content.ActivityNotFoundException) {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.paygo24.ibank")
)
)
}
}
private fun isPaywayDeeplink(host: String, scheme: String): Boolean {
return host.equals(Constant.ABA_HOST, true) && scheme.equals(Constant.ABA_SCHEME, true)
}
private fun closeWingPaymentWithError() {
showHideLoading(false)
SeatelAlertDialog.with(this, getString(R.string.message_wing_error)).setCancelable(true)
.setPositiveButton(getString(R.string.yes)) { _, _ ->
exitWingPayment(false)
}.show()
}
private fun closePaymentProgress() {
if (web_view_wing.canGoBack()) {
web_view_wing.goBack()
} else {
showHideLoading(false)
SeatelAlertDialog.with(this, getString(R.string.cancel_process_payment))
.setCancelable(true).setPositiveButton(getString(R.string.yes)) { _, _ ->
exitWingPayment(false)
}.setNegativeButton(getString(R.string.cancel)) { dailog, _ ->
dailog.dismiss()
}.show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ali_pay_mpay_payment)
activityEnterRightAnimation()
text_view_titleBar.text = intent.getStringExtra("title_payment")!!
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
activityEnterFadeInAnimation()
showHideLoading(true)
init()
}
private fun showHideLoading(isShow: Boolean) {
if (isShow) {
error_view.visibility = View.VISIBLE
error_view.setViewMode(ErrorHandleView.Mode.LOADING)
} else {
error_view.visibility = View.GONE
}
}
override fun getToolbarTitle(): String {
return ""
}
private fun init() {
isShowValentineDayPromotion = intent.getBooleanExtra("show_valentine_promotion", false)
isABAPay = intent.getBooleanExtra("is_aba_pay", false)
mAmount = intent.getDoubleExtra("top_amount", 0.0)
web_view_wing.isVerticalScrollBarEnabled = true
web_view_wing!!.settings.javaScriptEnabled = true
web_view_wing!!.webViewClient = mWebViewClient
mUrlPay = intent.getStringExtra("payment_url").toString()
web_view_wing!!.loadUrl(mUrlPay)
}
private fun onPageFinish(webView: WebView, url: String) {
when {
url.contains("result=success") -> {
exitWingPayment(true)
}
url.contains("result=error") -> {
exitWingPayment(false)
}
}
}
private fun exitWingPayment(isSuccess: Boolean) {
showHideLoading(false)
if (isSuccess) {
val intent = Intent(this, PaymentActivity::class.java)
intent.putExtra("show_valentine_promotion", isShowValentineDayPromotion)
setResult(Activity.RESULT_OK, intent)
}
activityExitLeftAnimation()
finish()
}
override fun onResume() {
super.onResume()
web_view_wing.onResume()
isOpenDeepLink = false
}
override fun onPause() {
super.onPause()
web_view_wing.onPause()
}
override fun onBackPressed() {
closePaymentProgress()
}
companion object {
fun lunch(
context: Context,
url: String,
amount: Double,
title: String,
ShowValentineDayPromotion: Boolean = false,
isABA: Boolean = false
) {
val i = Intent(context, AliPayMpayPaymentActivity::class.java)
i.putExtra("payment_url", url)
i.putExtra("top_amount", amount)
i.putExtra("title_payment", title)
i.putExtra("is_aba_pay", isABA)
i.putExtra("show_valentine_promotion", ShowValentineDayPromotion)
(context as Activity).startActivityForResult(i, Constant.REQUEST_WING)
}
}
}
package com.seatel.mobilehall.ui.home.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import com.seatel.mobilehall.R
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_ali_pay_mpay_payment.*
import kotlinx.android.synthetic.main.activity_base.*
import java.util.*
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
open class AliPayPaymentActivity : BaseActivity() {
private lateinit var mUrlPay: String
private var mAmount: Double = 0.0
private var isABAPay = false
private var isShowValentineDayPromotion = false
private var isOpenDeepLink = false
fun getWebClient(): WebViewClient {
return mWebViewClient
}
private val mWebViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
if (url != null && view != null) {
Log.d("---PageStarted", "onPageStarted: $url")
onPageFinish(view, url)
}
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
hideProgress()
}
override fun onReceivedError(
view: WebView,
request: WebResourceRequest,
error: WebResourceError
) {
super.onReceivedError(view, request, error)
// closeWingPaymentWithError()
hideProgress()
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url = request?.url.toString()
val host = request?.url?.host.toString()
val scheme = request?.url?.scheme.toString()
Log.d("TAG::>>>", "shouldOverrideUrlLoading: $url $host $scheme")
if (isPaywayDeeplink(host, scheme)) {
openDeeplink(url)
return false
}
return isOverrideUrlLoading(view, request)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
val uri = Uri.parse(url)
val host = uri.host
val scheme = uri.scheme
Log.d("TAG::>>>", "shouldOverrideUrlLoading: $uri $host $scheme")
if (isPaywayDeeplink(host!!, scheme!!)) {
if (url != null) {
openDeeplink(url)
}
return false
}
return isOverrideUrlLoading(view, url)
}
}
open fun isOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
return false
}
open fun isOverrideUrlLoading(view: WebView?, url: String?): Boolean {
return false
}
private fun openDeeplink(url: String) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
val packageManager = this.packageManager
val resolvedActivities = packageManager.queryIntentActivities(intent, 0)
if (resolvedActivities.size > 0)
startActivity(intent)
else gotoPlayStore()
isOpenDeepLink = true
}
private fun gotoPlayStore() {
try {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.paygo24.ibank")
)
)
} catch (obj: android.content.ActivityNotFoundException) {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=com.paygo24.ibank")
)
)
}
}
private fun isPaywayDeeplink(host: String, scheme: String): Boolean {
return host.equals(Constant.ABA_HOST, true) && scheme.equals(Constant.ABA_SCHEME, true)
}
private fun closeWingPaymentWithError() {
showHideLoading(false)
SeatelAlertDialog.with(this, getString(R.string.message_wing_error)).setCancelable(true)
.setPositiveButton(getString(R.string.yes)) { _, _ ->
exitWingPayment(false)
}.show()
}
private fun closePaymentProcress() {
if (web_view_wing.canGoBack()) {
web_view_wing.goBack()
} else {
showHideLoading(false)
SeatelAlertDialog.with(this, getString(R.string.cancel_process_payment))
.setCancelable(true).setPositiveButton(getString(R.string.yes)) { _, _ ->
exitWingPayment(false)
}.setNegativeButton(getString(R.string.cancel)) { dailog, _ ->
dailog.dismiss()
}.show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ali_pay_mpay_payment)
activityEnterRightAnimation()
text_view_titleBar.text = intent.getStringExtra("title_payment")!!
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
activityEnterFadeInAnimation()
// showHideLoading(true)
showProgress()
init()
}
private fun showHideLoading(isShow: Boolean) {
if (isShow) {
error_view.visibility = View.VISIBLE
error_view.setViewMode(ErrorHandleView.Mode.LOADING)
} else {
error_view.visibility = View.GONE
}
}
override fun getToolbarTitle(): String {
return ""
}
private fun init() {
isShowValentineDayPromotion = intent.getBooleanExtra("show_valentine_promotion", false)
isABAPay = intent.getBooleanExtra("is_aba_pay", false)
mAmount = intent.getDoubleExtra("top_amount", 0.0)
web_view_wing.isVerticalScrollBarEnabled = true
web_view_wing!!.settings.javaScriptEnabled = true
web_view_wing!!.webViewClient = mWebViewClient
mUrlPay = intent.getStringExtra("payment_url").toString()
web_view_wing!!.loadUrl(mUrlPay)
Log.d("---alipayment", "init: $mUrlPay")
}
private fun onPageFinish(webView: WebView, url: String) {
when {
url.contains("result=success") -> {
exitWingPayment(true)
}
url.contains("result=error") -> {
exitWingPayment(false)
}
}
}
private fun exitWingPayment(isSuccess: Boolean) {
showHideLoading(false)
if (isSuccess) {
val intent = Intent(this, PaymentActivity::class.java)
intent.putExtra("show_valentine_promotion", isShowValentineDayPromotion)
setResult(Activity.RESULT_OK, intent)
}
activityExitLeftAnimation()
finish()
}
override fun onResume() {
super.onResume()
web_view_wing.onResume()
isOpenDeepLink = false
}
override fun onPause() {
super.onPause()
web_view_wing.onPause()
}
override fun onBackPressed() {
closePaymentProcress()
}
companion object {
fun lunch(
context: Context,
url: String,
amount: Double,
title: String,
ShowValentineDayPromotion: Boolean = false,
isABA: Boolean = false
) {
val i = Intent(context, AliPayPaymentActivity::class.java)
i.putExtra("payment_url", url)
i.putExtra("top_amount", amount)
i.putExtra("title_payment", title)
i.putExtra("is_aba_pay", isABA)
i.putExtra("show_valentine_promotion", ShowValentineDayPromotion)
(context as Activity).startActivityForResult(i, Constant.REQUEST_WING)
}
}
}
package com.seatel.mobilehall.ui.home.activity
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.RelativeLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.util.BottomNavigationBehavior
import com.seatel.mobilehall.R
import kotlinx.android.synthetic.main.activity_data_pack_detail.*
@SuppressLint("Registered")
open class BaseProductAndServiceActivity : BaseActivity(), SwipeRefreshLayout.OnRefreshListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_data_pack_detail)
activityEnterRightAnimation()
if (isShowAddToCardButton()) {
addShowButtonFooter()
}
swipe_refresh_layout.setColorSchemeColors(
ContextCompat.getColor(
this,
R.color.colorPrimary
)
)
//swipe_refresh_layout.setOnRefreshListener(this)
swipe_refresh_layout.isRefreshing = false
swipe_refresh_layout.isEnabled = false
}
private fun addShowButtonFooter() {
val navigation = findViewById<RelativeLayout>(R.id.data_pack_bottom_navigation)
val navigationBackground =
findViewById<RelativeLayout>(R.id.data_pack_bottom_navigation_background)
val layoutParams = navigation.layoutParams as CoordinatorLayout.LayoutParams
val layoutParamsBackground =
navigationBackground.layoutParams as CoordinatorLayout.LayoutParams
scroll_data_pack.viewTreeObserver.addOnGlobalLayoutListener {
val bottomNavigationBehavior = BottomNavigationBehavior(440)
val bottomNavigationBehaviorBackground = BottomNavigationBehavior(300)
bottomNavigationBehavior.showBottomNavigationView(navigation)
bottomNavigationBehaviorBackground.showBottomNavigationView(navigationBackground)
if (getHeight(scroll_data_pack) < getHeight(recycler_view_product_service) + 30) {
layoutParams.behavior = bottomNavigationBehavior
layoutParamsBackground.behavior = bottomNavigationBehaviorBackground
}
scroll_data_pack.viewTreeObserver.removeOnGlobalLayoutListener { this }
}
}
fun setShowButton(show: Boolean) {
addShowButtonFooter()
}
open fun isShowAddToCardButton(): Boolean {
return true
}
override fun onBackPressed() {
super.onBackPressed()
activityExitLeftAnimation()
}
override fun getStringToolbarTitle(): String? {
return getString(R.string.data_pack_title)
}
override fun onRefresh() {
}
}
\ No newline at end of file
package com.seatel.mobilehall.ui.home.activity
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.adapter.BuyTopUpCardAdapter
import com.seatel.mobilehall.ui.home.interactor.BuyTopUpCardInteractor
import com.seatel.mobilehall.ui.home.model.BuyTopUpCartModel
import com.seatel.mobilehall.ui.home.model.CartModel
import com.seatel.mobilehall.ui.home.model.CartRequestModel
import com.seatel.mobilehall.ui.home.presenter.BuyTopUpCardPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.customview.CustomEditText
import com.seatel.mobilehall.util.customview.DialogAddCart
import com.seatel.mobilehall.util.manager.OrderingManager
import kotlinx.android.synthetic.main.activity_buy_top_up_card.*
import kotlinx.android.synthetic.main.layout_default_progress.*
import org.json.JSONObject
open class BuyTopUpCardActivity : BaseActivity(), BuyTopUpCardInteractor.View,
BuyTopUpCardAdapter.ShowCustomKeyBoard {
private val buyTopUpCartModel: ArrayList<BuyTopUpCartModel> = ArrayList()
private var buyTopUpCardAdapter: BuyTopUpCardAdapter? = null
private var buyTopUpCardPresenter: BuyTopUpCardPresenter? = null
private var isSendingRequest = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_buy_top_up_card)
init()
addItems()
initEvent()
}
override fun onDestroy() {
super.onDestroy()
buyTopUpCardPresenter?.onDestroy()
}
private fun init() {
buyTopUpCardPresenter = BuyTopUpCardPresenter(this)
activityEnterRightAnimation()
buyTopUpCardAdapter = BuyTopUpCardAdapter(this, buyTopUpCartModel, this)
recycler_view_buy_top_up_card.adapter = buyTopUpCardAdapter
recycler_view_buy_top_up_card.layoutManager = LinearLayoutManager(this)
addItems()
}
private fun addCardToCart(buyTopUpCartModel: BuyTopUpCartModel) {
val items = ArrayList<CartRequestModel.Scratch>()
val item = CartRequestModel.Scratch(buyTopUpCartModel.price)
item.quantity = buyTopUpCartModel.order
items.add(item)
val data: CartRequestModel<CartRequestModel.Scratch> = CartRequestModel(
SeatelSharePreferences.getInstance(this)?.getPhoneLogin(), true, items
)
buyTopUpCardPresenter?.onAddCardToCard(this, data)
}
override fun focusOnEditText(edit: CustomEditText) {
keyboard_view_top_up_card.setmMaxLenght(4)
keyboard_view_top_up_card.showKeyBoard(edit)
}
override fun hideKeyBoard() {
keyboard_view_top_up_card.hideKeyBoard()
}
private fun initEvent() {
buyTopUpCardAdapter?.onItemViewClick = object : BuyTopUpCardAdapter.OnItemViewClick {
override fun onAddCartClick(position: Int, data: BuyTopUpCartModel) {
if (!isSendingRequest) {
addCardToCart(data)
}
}
override fun onBuyNowClick(position: Int, data: BuyTopUpCartModel) {
if (data != null)
buyTopupCard(data)
}
}
}
private fun buyTopupCard(data: BuyTopUpCartModel) {
val dataDeviceOrder = ArrayList<CartModel>()
val myData = CartModel()
// val item = CartRequestModel.Device()
myData.unitPrice = data.price
myData.scratchCardAmount = data.price
myData.type = Constant.SRATCH_CARD
myData.quantity = data.order
myData.totalPrice = (data.price * data.order)
myData.isSelected = true
myData.scratchCardIcon =
"https://api.yes.com.kh/icons//scratch_card_${data.price.toInt()}.png"
dataDeviceOrder.add(myData)
OrderingManager.getInstance().clear()
OrderingManager.getInstance().cartsModels.addAll(dataDeviceOrder)
OrderActivity.launch(this,true)
}
private fun addItems() {
buyTopUpCartModel.clear()
// buyTopUpCartModel.add(BuyTopUpCartModel(50))
// buyTopUpCartModel.add(BuyTopUpCartModel(20))
buyTopUpCartModel.add(BuyTopUpCartModel(10))
buyTopUpCartModel.add(BuyTopUpCartModel(5))
buyTopUpCartModel.add(BuyTopUpCartModel(2))
buyTopUpCartModel.add(BuyTopUpCartModel(1))
buyTopUpCardAdapter?.notifyDataSetChanged()
}
override fun getStringToolbarTitle(): String? {
return getString(R.string.top_up_card)
}
override fun onBackPressed() {
if (keyboard_view_top_up_card.isShown) hideKeyBoard()
else {
super.onBackPressed()
activityExitLeftAnimation()
}
}
companion object {
const val REQUEST_CODE = 1000
fun lunch(context: Activity) {
val intent = Intent(context, BuyTopUpCardActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK
context.startActivityForResult(intent, REQUEST_CODE)
}
}
var dialog: DialogAddCart? = null
@SuppressLint("InflateParams")
private fun showDialogItemAddToCart() {
dialog = DialogAddCart(this)
dialog?.onItemClick = object : DialogAddCart.OnItemClick {
override fun onButtonAddToCartClick(view: View) {
MyCartActivity.launch(this@BuyTopUpCardActivity)
finish()
}
override fun onButtonContinueBuyClick(view: View) {
addItems()
}
}
dialog?.show()
}
override fun showWaiting() {
isSendingRequest = true
progress.visibility = View.VISIBLE
}
override fun hideWaiting() {
isSendingRequest = false
progress.visibility = View.GONE
}
override fun showAddCardToCardFailed(throwable: VolleyError) {
SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(throwable)).show()
}
override fun showAddCardToCardSuccess(data: JSONObject?) {
showDialogItemAddToCart()
}
}
package com.seatel.mobilehall.ui.home.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.android.volley.VolleyError
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelSuperRequest
import com.seatel.mobilehall.ui.base.activity.BaseActivity
import com.seatel.mobilehall.ui.home.interactor.TopupTransactionInteractor
import com.seatel.mobilehall.ui.home.presenter.TopupTransactionPresenter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.ErrorHandleView
import kotlinx.android.synthetic.main.activity_confirmation.*
class ConfirmationActivity : BaseActivity(), TopupTransactionInteractor.View{
private var mPhoneNumber: String = ""
private var mAmountTopup: Double = 0.0
private var isFromPin = false
private var mPinTopup: String = "0"
//Topup
private lateinit var mTopupTransactionPresenter: TopupTransactionPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityEnterFadeInAnimation()
setContentView(R.layout.activity_confirmation)
mPhoneNumber = intent.getStringExtra(Constant.PHONE_NUMBER).toString()
mAmountTopup = intent.getDoubleExtra(Constant.MPAY_AMOUNT, 0.0)
isFromPin = intent.getBooleanExtra(Constant.LAUNCH_FROM, false)
mPinTopup = intent.getStringExtra(Constant.PIN_NUMBER).toString()
mTopupTransactionPresenter = TopupTransactionPresenter(this,this)
ctv_value_price.text = SeatelUtils.displayAmountNoDecial(this, "$$mAmountTopup")
ctv_phone_number.text = mPhoneNumber
image_view_back.setOnClickListener {
onBackPressed()
}
button_ok.setOnClickListener {
if (isFromPin) {
error_view.setViewMode(ErrorHandleView.Mode.LOADING)
mTopupTransactionPresenter.onTopup(
mPhoneNumber.replace(" ", ""),
mPinTopup,
"",
"pin",
"",
"",
mAmountTopup
)
} else {
// //Test fixed amount
// mAmountTopup = 0.01
// PaymentActivity.lunch(this, mPhoneNumber, mAmountTopup)
finish()
}
button_ok.isEnabled = false
}
}
override fun onTopupSucceed(paymentType: String, remark: String, amount: Double) {
TopUpSuccessActivity.lunch(
this,
Constant.TOPUP_SUCCESS,
mAmountTopup.toString(),
mPhoneNumber
)
finish()
}
override fun onTopupFailed(error: VolleyError) {
error_view.visibility = View.GONE
SeatelAlertDialog.with(this, SeatelSuperRequest.getErrorMessageFrom(error)).show()
button_ok.isEnabled = true
}
override fun onBackPressed() {
super.onBackPressed()
super.activityExitFadeOutAnimation()
}
companion object {
fun lunch(
context: Context,
phoneNumber: String,
amountTopup: Double,
fromPin: Boolean,
pinNumber: String
) {
val intent = Intent(context, ConfirmationActivity::class.java)
intent.putExtra(Constant.PHONE_NUMBER, phoneNumber)
intent.putExtra(Constant.MPAY_AMOUNT, amountTopup)
intent.putExtra(Constant.LAUNCH_FROM, fromPin)
intent.putExtra(Constant.PIN_NUMBER, pinNumber)
context.startActivity(intent)
}
}
override fun isDisplayBackgroundBlur(): Boolean {
return true
}
override fun isDisplayToolbar(): Boolean {
return false
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment