Skip to content

Instantly share code, notes, and snippets.

@mhd-zulqarnain
Created November 6, 2019 13:37
Show Gist options
  • Save mhd-zulqarnain/cf920a9a1af1fcc7fe1051e5c14b05c5 to your computer and use it in GitHub Desktop.
Save mhd-zulqarnain/cf920a9a1af1fcc7fe1051e5c14b05c5 to your computer and use it in GitHub Desktop.
offline
package com.squadtechs.markhor.foodapp.trader.fragments.trader_fragment_add_non_food_item
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import com.google.android.material.textfield.TextInputEditText
import com.google.gson.Gson
import com.squadtechs.markhor.foodapp.R
import com.squadtechs.markhor.foodapp.main_utils.MainUtils
import com.squadtechs.markhor.foodapp.main_utils.NetworkUtils
import com.squadtechs.markhor.foodapp.main_utils.SharedPrefs
import com.squadtechs.markhor.foodapp.main_utils.UiHelper
import com.squadtechs.markhor.foodapp.trader.activity_trader_main.TraderMainCallBack
import com.squadtechs.markhor.foodapp.trader.fragments.trader_fragment_add_non_food_images.TraderFragmentAddImages
import com.squadtechs.markhor.foodapp.web_services.RetrofitClient
import com.squadtechs.markhor.foodapp.web_services.model.BaseModel
import com.squadtechs.markhor.foodapp.web_services.model.base_response.BaseModelListl
import com.squadtechs.markhor.foodapp.web_services.model.sign_up.SignInModel
import com.squadtechs.markhor.foodapp.web_services.model.trader_home.GetCategoryByIdModel
import com.squadtechs.markhor.foodapp.web_services.model.trader_item.*
import retrofit2.Callback
import java.io.ByteArrayOutputStream
import java.util.*
import kotlin.collections.HashMap
private const val TAG = "TraderFragmentNON"
class TraderFragmentAddNonFoodItem : Fragment() {
private lateinit var mView: View
private lateinit var btnNext: Button
private lateinit var txtTitle: TextView
private lateinit var linearDeliveryPrice: LinearLayout
private lateinit var map: HashMap<String, String>
private lateinit var obj: TraderMainCallBack
private lateinit var doYouDeliver: String
private lateinit var edtDeliveryPrice: EditText
private lateinit var edtPrice: EditText
private lateinit var edtProductName: EditText
private lateinit var edtDescription: EditText
private var listIteamAs: String = "Women Fashion"
private var size: String = ""
private var deliveryPrice: String = ""
private var isOptional: Boolean = false
private lateinit var API: String
private lateinit var etCategoryBySeller: TextInputEditText
private lateinit var etCategoryByCategory: TextInputEditText
private lateinit var etCusine: TextInputEditText
private lateinit var lvRadioCustomerDish: LinearLayout
private lateinit var seller: SignInModel
var product_id = -1
var categoryId = -1
var typeId = -1
var parent_id = -1
var selected_categoryId = ""
var selected_typeId = ""
var selected_parent_id = ""
var newProduct =
NewProductGeneral()
var prvOfflinebyCategory = ArrayList<GetCategoryByIdModel>()
var vrTypeOfflineByCategory = ArrayList<TypeGeneral>()
var vreOfflineByCategory = ArrayList<VariationItem>()
val varitaionList = ArrayList<String>()
var selectedvaritaionList = ArrayList<String>()
private var isEdit = false
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mView = inflater.inflate(R.layout.trader_fragment_add_non_food_item, container, false)
initViews()
// populateSizeSpinner()
setListeners()
return mView
}
private fun initViews() {
txtTitle = mView.findViewById(R.id.txt_title)
linearDeliveryPrice = mView.findViewById(R.id.linear_delivery_price)
btnNext = mView.findViewById(R.id.btn_next)
lvRadioCustomerDish = mView.findViewById(R.id.lvRadioCustomerDish)
etCategoryBySeller = mView.findViewById(R.id.et_list_dish_as)
etCategoryByCategory = mView.findViewById(R.id.et_list_sub_cat_by_parent)
etCusine = mView.findViewById(R.id.et_list_select_cusine)
seller = SharedPrefs.getInstance()!!.getUser(activity!!)!!
doYouDeliver = activity!!.getSharedPreferences(
"user_credentials",
Context.MODE_PRIVATE
).getString("delivery_type", "none") as String
if (doYouDeliver.equals("yes")) {
linearDeliveryPrice.visibility = View.VISIBLE
}
edtProductName = mView.findViewById(R.id.edt_product_name)
edtDescription = mView.findViewById(R.id.edt_product_description)
edtDeliveryPrice = mView.findViewById(R.id.edt_dish_delivery_price)
edtPrice = mView.findViewById(R.id.edt_product_price)
if (activity!!.getSharedPreferences(
"add_item_preferences",
Context.MODE_PRIVATE
).getBoolean(
"is_edit",
false
)
) {
txtTitle.text = "Edit Item"
}
val isEditBool = activity!!.getSharedPreferences(
"add_item_preferences",
Context.MODE_PRIVATE
).getBoolean("is_edit", false)
isEdit = isEditBool
val foodId = activity!!.getSharedPreferences(
"add_item_preferences",
Context.MODE_PRIVATE
).getString("food_id", "0")!!.toInt()
if (isEdit) {
getProducts(foodId)
product_id = foodId
} else {
getSubCategoryForSeller()
// getCuisine()
}
}
@SuppressLint("SetTextI18n")
private fun sendData() {
val price = edtPrice.text.toString().trim()
deliveryPrice = edtDeliveryPrice.text.toString()
val description = edtDescription.text.toString().trim()
val title = edtProductName.text.toString().trim()
if (price.equals("") || description.equals("") || title.equals("") || varitaionList.size == 0
) {
Toast.makeText(activity!!, "Fill all fields first", Toast.LENGTH_SHORT).show()
} else {
val pd = MainUtils.getLoadingDialog(activity!!, "Adding", "Please wait", false)
// pd.show()
map = HashMap<String, String>()
if (activity!!.getSharedPreferences(
"add_item_preferences",
Context.MODE_PRIVATE
).getBoolean(
"is_edit",
false
)
) {
newProduct.created_by = seller.id.toInt()
newProduct.category_id = categoryId.toString()
newProduct.name = title
newProduct.products_variation_type_id = typeId.toString()
newProduct.description = description
newProduct.price = price
newProduct.parent_id = parent_id.toString()
// newProduct.first_image = toByte((imgDish.drawable as BitmapDrawable).bitmap)
// newProduct.first_image_type = "JPEG"
changeFragment(TraderFragmentAddImages())
} else {
newProduct.created_by = seller.id.toInt()
newProduct.category_id = categoryId.toString()
newProduct.name = title
newProduct.products_variation_type_id = typeId.toString()
newProduct.description = description
newProduct.price = price
newProduct.parent_id = parent_id.toString()
changeFragment(TraderFragmentAddImages())
}
}
}
private fun setListeners() {
btnNext.setOnClickListener {
sendData()
}
}
fun getProducts(id: Int) {
MainUtils.showAlertLoadingDialog(activity!!, "Loading", "Please Wait!!", false)
try {
if (NetworkUtils.isNetworkAvailable(activity!!)) {
RetrofitClient.getInstance()!!.getService().getProducts(
id
).enqueue(object : Callback<BaseModel<GetProductResponse>> {
override fun onResponse(
call: retrofit2.Call<BaseModel<GetProductResponse>>,
response: retrofit2.Response<BaseModel<GetProductResponse>>
) {
if (response.isSuccessful) {
if (response.body() != null) {
Log.e(TAG, "response.body()?.toString ${response.body()}")
if (response.body()?.status == true) {
//setting edit data
val product = response.body()!!.data
selectedvaritaionList.addAll(
product!!.productsVariationIds.split(
" "
)
)
// selected_product_id = product.cuisine_id
selected_typeId = product.productsVariationTypeId
selected_categoryId = product.subCategoryId
selected_parent_id = product.parentId
categoryId = selected_categoryId.toInt()
typeId = selected_typeId.toInt()
parent_id = product.parentId.toInt()
newProduct.first_image = product.firstImage
newProduct.parent_id = product.parentId
newProduct.second_image = product.secondImage
newProduct.third_image = product.thirdImage
// uri = product.first_image
edtProductName.setText(product.name)
edtDescription.setText(product.description)
edtPrice.setText(product.price)
/* Picasso.get()
.load(product.first_image)
.error(R.drawable.no_imag_found)
.into(imgDish)*/
getSubCategoryForSeller()
getSubCategory(parent_id)
// getCuisine()
} else {
Toast.makeText(
activity!!,
response.body()!!.message,
Toast.LENGTH_SHORT
).show()
MainUtils.hideAlertLoadingDialog()
}
} else {
MainUtils.hideAlertLoadingDialog()
}
} else {
MainUtils.hideAlertLoadingDialog()
}
}
override fun onFailure(
call: retrofit2.Call<BaseModel<GetProductResponse>>,
t: Throwable
) {
Log.e(TAG, "t.message ${t.message}")
Log.e(TAG, "t.localizedMessage ${t.localizedMessage}")
Log.e(TAG, "t.stackTrace ${t.stackTrace}")
Log.e(TAG, "t.cause ${t.cause}")
}
})
} else {
Toast.makeText(
activity!!,
context?.resources?.getString(R.string.error_no_network),
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
Log.e(TAG, "Exception e.message ${e.message}")
} finally {
// MainUtils.hideAlertLoadingDialog()
}
}
fun getSubCategoryForSeller() {
MainUtils.showAlertLoadingDialog(activity!!, "Loading", "Please Wait!!", false)
try {
if (NetworkUtils.isNetworkAvailable(activity!!)) {
RetrofitClient.getInstance()!!.getService().getSubCategoryForSeller(
seller.id.toInt()
).enqueue(object : Callback<BaseModelListl<ProductsVariation>> {
override fun onResponse(
call: retrofit2.Call<BaseModelListl<ProductsVariation>>,
response: retrofit2.Response<BaseModelListl<ProductsVariation>>
) {
if (response.isSuccessful) {
if (response.body() != null) {
if (response.body()?.status == true) {
if (selected_parent_id != "") {
response.body()!!.data!!.forEach {
if (it.id == selected_parent_id) {
selected_parent_id = it.name
}
}
} else
getPrvOfflinebyCategory(response.body()!!.data!![0].id.toInt())
// getVariationsByCategory(response.body()!!.data!![0].id.toInt())
dynamicSubCategoryForSeller(response.body()!!.data!!)
} else {
Toast.makeText(
activity!!,
response.body()!!.message,
Toast.LENGTH_SHORT
).show()
MainUtils.hideAlertLoadingDialog()
}
} else {
Log.e(TAG, "t.message error")
}
} else {
Log.e(TAG, "t.message error")
}
}
override fun onFailure(
call: retrofit2.Call<BaseModelListl<ProductsVariation>>,
t: Throwable
) {
Log.e(TAG, "t.message ${t.message}")
Log.e(TAG, "t.localizedMessage ${t.localizedMessage}")
Log.e(TAG, "t.stackTrace ${t.stackTrace}")
Log.e(TAG, "t.cause ${t.cause}")
}
})
} else {
Toast.makeText(
activity!!,
context?.resources?.getString(R.string.error_no_network),
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
Log.e(TAG, "Exception e.message ${e.message}")
MainUtils.hideAlertLoadingDialog()
} finally {
// MainUtils.hideAlertLoadingDialog()
}
}
fun getSubCategory(id: Int) {
MainUtils.showAlertLoadingDialog(activity!!, "Loading", "Please Wait!!", false)
try {
if (NetworkUtils.isNetworkAvailable(activity!!)) {
RetrofitClient.getInstance()!!.getService().getSubCategory(
id
).enqueue(object : Callback<BaseModelListl<GetCategoryByIdModel>> {
override fun onResponse(
call: retrofit2.Call<BaseModelListl<GetCategoryByIdModel>>,
response: retrofit2.Response<BaseModelListl<GetCategoryByIdModel>>
) {
if (response.isSuccessful) {
if (response.body() != null) {
Log.e(TAG, "response.body()?.toString ${response.body()}")
if (response.body()?.status == true) {
prvOfflinebyCategory.addAll(response.body()!!.data!!)
if (selected_categoryId != "") {
response.body()!!.data!!.forEach {
if (it.id == selected_categoryId) {
selected_categoryId = it.name
}
}
} else
getPrvOfflinebyCategory(response.body()!!.data!![0].id.toInt())
dynamicSubCategory(response.body()!!.data!!)
MainUtils.hideAlertLoadingDialog()
} else {
Toast.makeText(
activity!!,
response.body()!!.message,
Toast.LENGTH_SHORT
).show()
MainUtils.hideAlertLoadingDialog()
}
} else {
MainUtils.hideAlertLoadingDialog()
Log.e(TAG, "t.message error")
}
} else {
MainUtils.hideAlertLoadingDialog()
Log.e(TAG, "t.message error")
}
}
override fun onFailure(
call: retrofit2.Call<BaseModelListl<GetCategoryByIdModel>>,
t: Throwable
) {
Log.e(TAG, "t.message ${t.message}")
Log.e(TAG, "t.localizedMessage ${t.localizedMessage}")
Log.e(TAG, "t.stackTrace ${t.stackTrace}")
Log.e(TAG, "t.cause ${t.cause}")
MainUtils.hideAlertLoadingDialog()
}
})
} else {
Toast.makeText(
activity!!,
context?.resources?.getString(R.string.error_no_network),
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
Log.e(TAG, "Exception e.message ${e.message}")
MainUtils.hideAlertLoadingDialog()
} finally {
// MainUtils.hideAlertLoadingDialog()
}
}
fun getVariationTypeByCategory(id: Int) {
val progressDialog =
MainUtils.showAlertLoadingDialog(activity!!, "Loading", "Please Wait!!", false)
try {
if (NetworkUtils.isNetworkAvailable(activity!!)) {
RetrofitClient.getInstance()!!.getService().getVariationTypeByCategory(id)
.enqueue(object : Callback<BaseModelListl<TypeGeneral>> {
override fun onResponse(
call: retrofit2.Call<BaseModelListl<TypeGeneral>>,
response: retrofit2.Response<BaseModelListl<TypeGeneral>>
) {
if (response.isSuccessful) {
if (response.body() != null) {
Log.e(TAG, "response.body()?.toString ${response.body()}")
if (response.body()?.status == true) {
vrTypeOfflineByCategory.addAll(response.body()!!.data!!)
if (selected_typeId != "") {
// getVariationByTypeID(selected_typeId.toInt())
response.body()!!.data!!.forEach {
if (it.id == selected_typeId) {
selected_typeId = it.typeName!!
}
}
}
getvrTypeOfflineByCategory(response.body()!!.data!![0].categoryId!!.toInt())
dynamicVariationTypeByCategory(response.body()!!.data!!)
} else {
Toast.makeText(
activity!!,
response.body()!!.message,
Toast.LENGTH_SHORT
).show()
MainUtils.hideAlertLoadingDialog()
}
} else {
}
} else {
}
}
override fun onFailure(
call: retrofit2.Call<BaseModelListl<TypeGeneral>>,
t: Throwable
) {
Log.e(TAG, "t.message ${t.message}")
Log.e(TAG, "t.localizedMessage ${t.localizedMessage}")
Log.e(TAG, "t.stackTrace ${t.stackTrace}")
Log.e(TAG, "t.cause ${t.cause}")
}
})
} else {
Toast.makeText(
activity!!,
context?.resources?.getString(R.string.error_no_network),
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
Log.e(TAG, "Exception e.message ${e.message}")
MainUtils.hideAlertLoadingDialog()
} finally {
// MainUtils.hideAlertLoadingDialog()
}
}
fun getVariationsByCategory(id: Int) {
// MainUtils.showAlertLoadingDialog(activity!!, "Loading", "Please Wait!!", false)
try {
if (NetworkUtils.isNetworkAvailable(activity!!)) {
RetrofitClient.getInstance()!!.getService().getVariationsByCategoryGeneral(id)
.enqueue(object : Callback<BaseModelListl<VariationItem>> {
override fun onResponse(
call: retrofit2.Call<BaseModelListl<VariationItem>>,
response: retrofit2.Response<BaseModelListl<VariationItem>>
) {
if (response.isSuccessful) {
if (response.body() != null) {
Log.e(TAG, "response.body()?.toString ${response.body()}")
if (response.body()?.status == true) {
// vreOfflineByCategory.addAll(response.body()!!.data!!)
addCheckBox(response.body()!!.data!!)
} else {
Toast.makeText(
activity!!,
response.body()!!.message,
Toast.LENGTH_SHORT
).show()
MainUtils.hideAlertLoadingDialog()
}
} else {
MainUtils.hideAlertLoadingDialog()
}
} else {
MainUtils.hideAlertLoadingDialog()
}
}
override fun onFailure(
call: retrofit2.Call<BaseModelListl<VariationItem>>,
t: Throwable
) {
Log.e(TAG, "t.message ${t.message}")
Log.e(TAG, "t.localizedMessage ${t.localizedMessage}")
Log.e(TAG, "t.stackTrace ${t.stackTrace}")
MainUtils.hideAlertLoadingDialog()
Log.e(TAG, "t.cause ${t.cause}")
}
})
} else {
Toast.makeText(
activity!!,
context?.resources?.getString(R.string.error_no_network),
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
Log.e(TAG, "Exception e.message ${e.message}")
MainUtils.hideAlertLoadingDialog()
} finally {
// MainUtils.hideAlertLoadingDialog()
}
}
//get categories if already in list
fun getPrvOfflinebyCategory(id: Int) {
val filtered = prvOfflinebyCategory.filter {
it.parent_id.toInt() == id
}
if (filtered.size == 0)
getSubCategory(id)
else{
dynamicSubCategory(filtered)
// getPrvOfflinebyCategory(filtered[0].id.toInt())
}
}
fun getvrTypeOfflineByCategory(id: Int) {
val filtered = vrTypeOfflineByCategory.filter {
it.categoryId!!.toInt() == id
}
if (filtered.size == 0)
getVariationTypeByCategory(id)
else {
dynamicVariationTypeByCategory(filtered)
// getvrTypeOfflineByCategory(filtered[0].categoryId!!.toInt())
}
}
fun getvreOfflineByCategory(id: Int) {
val filtered = vreOfflineByCategory.filter {
it.category_id.toInt() == id
}
if (filtered.size == 0)
getSubCategory(id)
else
addCheckBox(filtered)
}
///end
fun dynamicSubCategoryForSeller(categories: List<ProductsVariation>) {
val lst = ArrayList<String>()
for (item in categories)
lst.add(item.name)
UiHelper.setupFloatingSpinner(
etCategoryBySeller, lst, selected_parent_id,
{ selectedItem, selectedIndex ->
val item = selectedItem as String
categories.forEach { obj ->
if (obj.name == item) {
parent_id = obj.id.toInt()
getPrvOfflinebyCategory(obj.id.toInt())
// getSubCategory(obj.id.toInt())
return@forEach
}
}
}, activity!!
)
}
fun dynamicSubCategory(categories: List<GetCategoryByIdModel>) {
val lst = ArrayList<String>()
for (item in categories)
lst.add(item.name)
if (isEdit) {
getVariationTypeByCategory(categoryId)
}
UiHelper.setupFloatingSpinner(
etCategoryByCategory, lst, selected_categoryId,
{ selectedItem, selectedIndex ->
val item = selectedItem as String
categories.forEach { obj ->
if (obj.name == item) {
categoryId = obj.id.toInt()
getvrTypeOfflineByCategory(categoryId)
return@forEach
}
}
}, activity!!
)
}
fun dynamicVariationTypeByCategory(cusine: List<TypeGeneral>) {
val lst = ArrayList<String>()
for (item in cusine)
lst.add(item.typeName!!)
if (isEdit) {
getVariationsByCategory(typeId)
}
UiHelper.setupFloatingSpinner(
etCusine, lst, selected_typeId,
{ selectedItem, selectedIndex ->
val item = selectedItem as String
cusine.forEach { obj ->
if (obj.typeName == item) {
typeId = obj.categoryId!!.toInt()
getVariationsByCategory(typeId)
return@forEach
}
}
}, activity!!
)
}
private fun addCheckBox(
additionalData: List<VariationItem>
) {
if (isAdded() && isVisible() && getUserVisibleHint()) {
lvRadioCustomerDish.removeAllViews()
varitaionList.clear()
val cbMap = HashMap<Int, String>()
var count = 0
var lnr = LinearLayout(activity!!)
val param = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f)
param.setMargins(5, 5, 5, 25)
lnr.setWeightSum(2f)
additionalData.forEach { obj ->
count = count + 1
val mCheckBox = CheckBox(activity)
mCheckBox.text = obj.variation_name
mCheckBox.id = obj.id.toInt()
mCheckBox.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.text_12)
)
mCheckBox.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.text_12)
)
if (isEdit) {
selectedvaritaionList.forEach {
if (obj.id == it) {
mCheckBox.isChecked = true
cbMap.put(it.toInt(), it)
}
}
}
if (count < 3) {
lnr.addView(mCheckBox, param)
} else {
lvRadioCustomerDish.addView(lnr)
lnr = LinearLayout(activity!!)
lnr.setWeightSum(2f)
count = 1
lnr.addView(mCheckBox, param)
}
mCheckBox.setOnCheckedChangeListener(object :
CompoundButton.OnCheckedChangeListener {
override fun onCheckedChanged(p0: CompoundButton?, ischeck: Boolean) {
val cid = mCheckBox.id
if (ischeck) {
cbMap.put(cid, cid.toString())
} else {
if (cbMap.get(cid) != null) {
cbMap.remove(cid)
}
}
varitaionList.clear()
cbMap.forEach { obj ->
varitaionList.add(obj.value)
}
Log.e(TAG, varitaionList.toString())
}
})
if (isEdit) {
varitaionList.clear()
cbMap.forEach { obj ->
varitaionList.add(obj.value)
}
}
}
}
MainUtils.hideAlertLoadingDialog()
}
private fun changeFragment(fragment: Fragment) {
val json = Gson().toJson(newProduct)
val editor =
activity!!.getSharedPreferences("new_product", Context.MODE_PRIVATE).edit()
editor.putString("object", json)
editor.putString("isEdit", "0")
editor.putString("type", "general")
var variant = ""
varitaionList.forEach {
variant += "$it "
}
variant = removeLastChatFromString(variant)
editor.putString("varaints", variant)
if (isEdit) {
editor.putString("isEdit", "1")
editor.putString("product_id", product_id.toString())
}
editor.apply()
val transaction = activity!!.supportFragmentManager.beginTransaction()
transaction.replace(R.id.main_frame, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
fun removeLastChatFromString(_str: String): String {
var str = _str
if (str.isNotEmpty() && str[str.length - 1] == ' ') {
str = str.substring(0, str.length - 1)
}
return str
}
private fun toByte(bitmap: Bitmap): String {
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream)
val image = stream.toByteArray()
return Base64.encodeToString(image, Base64.DEFAULT)
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
obj = activity!! as TraderMainCallBack
}
override fun onDetach() {
super.onDetach()
MainUtils.hideAlertLoadingDialog()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment