Handle Edittext in AlertDialog in android - android

i have a edittext in Alert Dialog.....my operation is performing well if ediitext is not empty.....i want to set focus when ediitext is empty in alertdialog ..
need help thanks in advance
i tried the following code please have a look:---
buynow.setOnClickListener {
val mBuild: AlertDialog.Builder = AlertDialog.Builder(this#Product_details)
val mView: View = layoutInflater.inflate(R.layout.buynowdialog, null)
val titleimage=mView.findViewById<TextView>(R.id.titleimage2) as TextView
val imagerate=mView.findViewById<ImageView>(R.id.imagebuy) as ImageView
titleimage.setText(ygd)
Glide.with(getApplicationContext()).load(res?.body()!!.data.product_images.get(0).image).into(imagerate);
val buynumber = mView.findViewById<EditText>(R.id.editbuy)
val btnSubmit =
mView.findViewById(R.id.btnbuynow) as Button
Log.e("checkid",id.toString())
mBuild.setView(mView)
val dialog: AlertDialog = mBuild.create()
btnSubmit.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
val value: String = buynumber.getText().toString()
val finalValue = value.toInt()
if (value.isEmpty()) {
Toast.makeText(
applicationContext, "Data is missing",Toast.LENGTH_LONG
).show()
editbuy.error = "Email required"
editbuy.requestFocus()
}
val token: String =
SharedPrefManager.getInstance(
applicationContext
).user.access_token.toString()
RetrofitClient.instancecart.buynow(token,id,finalValue)
.enqueue(object : Callback<ResponseBaseCartAdd> {
override fun onFailure(call: Call<ResponseBaseCartAdd>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<ResponseBaseCartAdd>,
response: Response<ResponseBaseCartAdd>
) {
Log.e("hi",id)
var res = response
Log.e("checkres",res.toString())
Log.d("response check ", "" + response.body()?.status.toString())
if (res.isSuccessful) {
Toast.makeText(
applicationContext,
res.body()?.user_msg,
Toast.LENGTH_LONG
).show()
dialog.dismiss()
Log.d("kjsfgxhufb",response.body()?.user_msg.toString())
}
else{
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getString("message")+jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr",e.message)
}
}
}
})
}
})
dialog.show()
}
above code is crashing with an error in logcat:-- java.lang.NumberFormatException: For input string: ""
need help thanks :)

NumberFormatException is an Exception that might be thrown when you
try to convert a String into a number, where that number might be an
int , a float , or any other Java numeric type.
val finalValue = value.toInt() // value is empty. That's why problem
Your finalValue is Empty or null. You must check it.
isNotEmpty() is used to find if the String is not empty/String is
length 0 and not null.
DEMO
if (value.isNotEmpty()) {
val finalValue = value.toInt()
val token: String =SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
RetrofitClient.instancecart.buynow(token,id,finalValue)
.....your task.....
}
else
{
Toast.makeText(applicationContext, "Data is missing",Toast.LENGTH_LONG).show()
editbuy.error = "Email required"
editbuy.requestFocus()
}

Related

How to display Telugu data retrieved from API into Spinner using kotlin?

I need to display the Telugu texts of Districts retrieved from API into Spinner, but random characters are displayed instead. How do I convert these characters to Telugu readable texts?
Sample Codes:
class MainActivity : AppCompatActivity() {
lateinit var spDistrict: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
districtData = mutableListOf()
spDistrict = findViewById<Spinner>(R.id.district)
getDistrictData()
val jsonObject = JSONObject()
jsonObject.put("profile_pic", userImage.toString().replace("/storage/emulated/0/Pictures/",""))
jsonObject.put("district_id", districtData!![spDistrict.selectedItemPosition].id)
jsonObject.put("token", token)
Log.e("jsonObject", jsonObject.toString())
val url = Constant.BASE_URL + "register/"
Log.e("url", "---->$url")
val request = object : StringRequest(
Method.POST, url, Response.Listener { response ->
try {
val responseObj = JSONObject(response)
if (response.isNotEmpty()) {
next.hideProgress("నమోదు")
val status = responseObj.getString("status")
if (status == "success" && lang=="telugu") {
val message = responseObj.getString("response")
val token = responseObj.getString("token")
val prefs = SharedPrefs(this#TReg3)
prefs.token = (token)
if (userImage.isNotEmpty()) {
fileUpload()
} else {
showSuccessDialog(message)
dialog.dismiss()
}
} else {
next.hideProgress("నమోదు")
val message = responseObj.getString("response")
showCustomAlertDialog(message)
dialog.dismiss()
}
} else {
next.hideProgress("నమోదు")
showCustomAlertDialog("Something went wrong")
dialog.dismiss()
}
} catch (ex: Exception) {
next.hideProgress("నమోదు")
showCustomAlertDialog("Something went wrong")
dialog.dismiss()
}
},
Response.ErrorListener { error ->
next.hideProgress("ప్రవేశించండి")
val errorMessage = VolleyErrorParser.getVolleyErrorMessage(error)
showCustomAlertDialog(errorMessage)
dialog.dismiss()
}) {
override fun getHeaders(): MutableMap<String, String> {
val params = java.util.HashMap<String, String>()
params["Content-Type"] = "application/json"
return params
}
override fun getBody(): ByteArray {
return jsonObject.toString().toByteArray()
}
}
MySingleton.getInstance(this).addToRequestQueue(request)
}
}
private fun getDistrictData() {
val url = Constant.BASE_URL + "getDistricts/"
Log.e("districteUrl", url)
val request = StringRequest(Request.Method.GET, url, { response ->
try {
if (!response.isNullOrEmpty()) {
val jsonObject = JSONObject(response)
val status = jsonObject.getString("status")
if (status == "success") {
val data = jsonObject.getJSONArray("districts")
districtData = listOf(
*Gson().fromJson(
data.toString(),
Array<DistrictData>::class.java
)
)
if (districtData!!.isNotEmpty()) {
val categoryDataAdapter = ArrayAdapter<DistrictData>(
this,
android.R.layout.simple_list_item_1,
districtData!!)
categoryDataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1)
spDistrict.adapter = categoryDataAdapter
// getMandalData()
} else {
dialog.dismiss()
val response = jsonObject.getString("response")
Toast.makeText(this, response, Toast.LENGTH_SHORT).show()
}
} else {
dialog.dismiss()
val response = jsonObject.getString("response")
Toast.makeText(this, response, Toast.LENGTH_SHORT).show()
}
} else {
dialog.dismiss()
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show()
}
} catch (ex: Exception) {
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show()
dialog.dismiss()
ex.printStackTrace()
}
}, { error ->
dialog.dismiss()
val errorMessage = VolleyErrorParser.getVolleyErrorMessage(error)
Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show()
})
VolleySingleton.getInstance(this!!).addToRequestQueue(request)
}
}
How do I make my app automatically detetct the Telugu text? Do I have to use a flag value?

Why is the user details vanishes from the Firestore?

I am using Firebase PhoneAuth for user registration with my app. Users are verified successfully and started using the app without any issues. But, It happened to me a couple of times that user details vanished from Firestore database, not all users details have gone though. When I check the collection users in the Firestore, the document does exist for the user but some data was gone, in fact, it's overwritten the old data as if this is new user registration (However, the User UID under the Authentication is remain same). For example, the default value is user_type = "customer", as you can see in the fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential). Later I change this value accordingly to my need and when this issue happens the changes I made to this field and other fields are changed back to the default values.
Following is the code in my SignInWithPhone which will be called from the SplashScreen
class SigninWithPhoneActivity: BaseActivity() {
private lateinit var binding: ActivitySignInWithPhoneBinding
private lateinit var mAuth: FirebaseAuth
var code = ""
var number = ""
var phoneNumber = ""
var storedOtpID = ""
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignInWithPhoneBinding.inflate(layoutInflater)
setContentView(binding.root)
}
mAuth = FirebaseAuth.getInstance()
binding.btnGetOtp.setOnClickListener {
code = binding.etCountryCode.text.toString().trim()
number = binding.etMobileNumber.text.toString().trim()
phoneNumber = code + number
if (number.isNotEmpty()) {
binding.etMobileNumber.isEnabled = false
binding.flOtp.visibility = View.VISIBLE
binding.btnGetOtp.visibility = View.GONE
binding.btnSignIn.visibility = View.VISIBLE
sendVerificationCode(phoneNumber)
} else {
Toast.makeText(this, "Please enter a valid mobile number", Toast.LENGTH_LONG).show()
}
}
binding.btnSignIn.setOnClickListener {
val otp = binding.etOtp.text.toString().trim()
if (otp.isNotEmpty() || otp.length != 6) {
verifyVerificationCode(otp)
} else {
Toast.makeText(this, "Please enter the OTP received through SMS", Toast.LENGTH_LONG)
.show()
}
}
}
private val mCallBack: PhoneAuthProvider.OnVerificationStateChangedCallbacks =
object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
val code = credential.smsCode
if (code != null) {
binding.etOtp.setText(code)
binding.pbOtp.visibility = View.GONE
}
}
override fun onVerificationFailed(p0: FirebaseException) {
binding.etMobileNumber.isEnabled = true
binding.flOtp.visibility = View.GONE
binding.btnGetOtp.visibility = View.VISIBLE
binding.btnSignIn.visibility = View.GONE
Toast.makeText(this#SigninWithPhoneActivity, "Login Failed", Toast.LENGTH_LONG)
.show()
}
override fun onCodeSent(otpID: String, token: PhoneAuthProvider.ForceResendingToken) {
super.onCodeSent(otpID, token)
Toast.makeText(
this#SigninWithPhoneActivity,
"OTP is send to your number",
Toast.LENGTH_LONG
).show()
storedOtpID = otpID
resendToken = token
}
}
private fun sendVerificationCode(phoneNumber: String) {
binding.pbOtp.visibility = View.VISIBLE
Toast.makeText(this#SigninWithPhoneActivity, "Sending OTP", Toast.LENGTH_LONG).show()
val options = PhoneAuthOptions.newBuilder(mAuth!!)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(mCallBack)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
private fun verifyVerificationCode(code: String) {
Toast.makeText(
this#SigninWithPhoneActivity,
"Verifying credentials",
Toast.LENGTH_LONG
).show()
val credential = PhoneAuthProvider.getCredential(storedOtpID, code)
signInWithPhoneAuthCredential(credential)
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val firebaseUser: FirebaseUser = task.result!!.user!!
val userPreliminaryDetails = User(
firebaseUser.uid,
user_type = "customer",
mobile = binding.etMobileNumber.text.toString()
)
FirestoreClass().checkIfUserAlreadyExist(
this#SigninWithPhoneActivity,
firebaseUser.uid,
userPreliminaryDetails
)
} else {
showErrorSnackBar(task.exception!!.message.toString(), true)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
binding.etMobileNumber.isEnabled = true
binding.flOtp.visibility = View.GONE
binding.etOtp.text?.clear()
binding.btnGetOtp.visibility = View.VISIBLE
binding.btnGetOtp.text = "Resend OTP"
binding.btnSignIn.visibility = View.GONE
Toast.makeText(this, "OTP entered is wrong", Toast.LENGTH_LONG).show()
}
}
}
}
fun userRegistrationSuccess() {
finish()
startActivity(Intent(this, ServiceAreaActivity::class.java))
Toast.makeText(this, "Signed Up successful", Toast.LENGTH_LONG).show()
}
fun userSignInSuccess() {
finish()
startActivity(Intent(this, ServiceAreaActivity::class.java))
Toast.makeText(this, "Signed in successfully", Toast.LENGTH_LONG).show()
}
}
EDIT:
The following function is called to check if the user already exists and accordingly sign in or register a new user.
fun checkIfUserAlreadyExist(
activity: SigninWithPhoneActivity, userId: String, userDetails: User
) {
mFireStore.collection("users")
.whereEqualTo(Constants.USER_ID, userId)
.get()
.addOnSuccessListener { document ->
if (document.documents.size > 0) {
activity.userSignInSuccess()
} else {
FirestoreClass().registerUser(activity, userDetails)
}
}
.addOnFailureListener { e ->
}
}
private fun registerUser(activity: SigninWithPhoneActivity, userInfo: User) {
mFireStore.collection(Constants.USERS)
.document(userInfo.user_id)
.set(userInfo, SetOptions.merge())
.addOnSuccessListener {
activity.userRegistrationSuccess()
}
.addOnFailureListener { e ->
activity.hideProgressDialog()
}
}

user login is not working using retrofit and viewmodel

my login is not working ..im using retrofit and viewmodel ...actually scenerio is onclick of login shows the transition(loginpage to loginpage) but it is not moving to loginpage to homepage....
this method model.ResponseData.observeis not getting call
i dont know where im going wrong
need help thanks
Loginactivity:--
class LoginActivity : AppCompatActivity() {
lateinit var model: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
val button = findViewById<ImageView>(R.id.plusbutton)
val forgotpassword=findViewById<TextView>(R.id.forgotpassword)
button.setOnClickListener {
val i = Intent(applicationContext, RegisterActivity::class.java)
startActivity(i)
}
forgotpassword.setOnClickListener{
val i = Intent(applicationContext, ForgotPassword::class.java)
startActivity(i)
}
model = ViewModelProvider(this)[LoginViewModel::class.java]
model.ResponseData.observe(this, object : Observer<LoginResponse?> {
override fun onChanged(t: LoginResponse?) {
val intent = Intent(applicationContext, HomeActivity::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
finish()
}
})
loginbtn.setOnClickListener {
val email = loginuser.text.toString().trim()
val password = loginpassword.text.toString().trim()
if (email.isEmpty()) {
Toast.makeText(
applicationContext, "Data is missing", Toast.LENGTH_LONG
).show()
loginuser.error = "Email required"
loginuser.requestFocus()
return#setOnClickListener
} else if (password.isEmpty()) {
loginpassword.error = "Password required"
loginpassword.requestFocus()
return#setOnClickListener
}
else {
model.loadAccountData(email,password)
}
}
}}
viewmodel:--
class LoginViewModel(context: Application,private val savedStateHandle: SavedStateHandle) : AndroidViewModel(context) {
private var _aResponseData = MutableLiveData<LoginResponse?>()
val user: MutableLiveData<String> = savedStateHandle.getLiveData("user", "")
val password: MutableLiveData<String> = savedStateHandle.getLiveData("password", "")
val ResponseData: MutableLiveData<LoginResponse?>
get() {
if (_aResponseData == null) {
_aResponseData = MutableLiveData<LoginResponse?>()
loadAccountData(user.toString(), password.toString())
}
return _aResponseData
}
fun loadAccountData(email:String, password:String) {
RetrofitClient.instance.userLogin(email, password)
.enqueue(object : Callback<LoginResponse> {
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
Log.d("res", "" + t)
_aResponseData.value = null
}
override fun onResponse(
call: Call<LoginResponse>,
response: Response<LoginResponse>
) {
var res = response
if (res.body()?.status == 200) {
_aResponseData.value = response.body()
} else {
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
getApplication(),
jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Log.e("errorrr", e.message)
}
}
}
})
}
}
After discussion and debugging, looks like issue was not on observer but actually during parsing of response from API call via retrofit.
_aResponseData.value = response.body()
Here response.body() was not able to parse response as LoginResponse class object which was eventually causing issue further more on navigation.
Fixing issue on parsing helps O.P. through debugging on main concern.
Try this
if (res.body()?.status == 200) {
_aResponseData.postValue(response.body())
}

Store the rating bar value in alert dialog using shared prefernces

basically i have a button -->Onclick-->alert dialog is appearing ..in that alert dialog im having a ratingbar.on that rating bar im sending the rate value to server using retrofit which i have done succesfully.but what i have problem is storing that rate value using shared preference.im sharing my code following:--
ratebutton.setOnClickListener {
val mBuild: AlertDialog.Builder = AlertDialog.Builder(this#Product_details)
val mView: View = layoutInflater.inflate(R.layout.ratedialog, null)
val ratebar =mView.findViewById(R.id.ratingBaruser) as RatingBar
val titleimage=mView.findViewById<TextView>(R.id.titleimage) as TextView
val imagerate=mView.findViewById<ImageView>(R.id.imagerate) as ImageView
titleimage.setText(ygd)
Glide.with(getApplicationContext()).load(res?.body()!!.data.product_images.get(0).image).into(imagerate);
val wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val rating: Float = wmbPreference1.getFloat("numStars", 0f)
ratebar.setRating(rating)
ratebar.onRatingBarChangeListener =
OnRatingBarChangeListener { ratingBar, rating1, fromUser ->
val editor = wmbPreference1.edit();
editor.putFloat("numStars", rating);
editor.commit();
rateValue = rating1
Toast.makeText(this#Product_details, "" + rating1, Toast.LENGTH_SHORT).show()
}
val btnSubmit =
mView.findViewById(R.id.btnSubRating) as Button
btnSubmit.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
RetrofitClient.instancetable.setRating(id,rateValue)
.enqueue(object : Callback<Rate_Response> {
override fun onFailure(call: Call<Rate_Response>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<Rate_Response>,
response: Response<Rate_Response>
) {
var res = response
if (res.isSuccessful) {
Toast.makeText(
applicationContext,
res.body()?.user_msg,
Toast.LENGTH_LONG
).show()
}
else{
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getString("message")+jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr",e.message)
}
}
}
})
Toast.makeText(this#Product_details, "" + rateValue, Toast.LENGTH_SHORT).show()
}
})
mBuild.setView(mView)
val dialog: AlertDialog = mBuild.create()
dialog.show()
}
Above code output:--
when i again click that button i unable to see the previous rate value done by user
i need help thanks in advance

Blank fragment is being displayed

Expected action::
When user clicks on the "Add to favourites button" the book will be added to the local database and a toast will appear saying that the book has been added to the favourites . Here I have used Room Persistance library. Then on clicking the favourite fragment in the menu drawer, the favourites page displaying the favourite book should appear.
Error:
the toast appears when I click on the add to favourites button but
The favourite fragment page is blank.
What i have done:
The required part description activity code is as follows :#
val queue = Volley.newRequestQueue(this#DescriptionActivity)
val url = "http://13.235.250.119/v1/book/get_book/"
val jsonParams = JSONObject()
jsonParams.put("book_id", bookId)
if(ConnectionManager().checkConnectivity(this#DescriptionActivity)) {
val jsonRequest = object : JsonObjectRequest(
Request.Method.POST, url, jsonParams, Response.Listener {
try {
val success = it.getBoolean("success")
if (success) {
val bookJsonObject = it.getJSONObject("book_data")
progressLayout.visibility = View.GONE
val bookImageUrl = bookJsonObject.getString("image")
Picasso.get().load(bookJsonObject.getString("image"))
.error(R.drawable.default_book).into(imgBookImage)
txtBookName.text = bookJsonObject.getString("name")
txtBookAuthor.text = bookJsonObject.getString("author")
txtBookPrice.text = bookJsonObject.getString("price")
txtBookRating.text = bookJsonObject.getString("rating")
txtBookDesc.text = bookJsonObject.getString("description")
val bookEntity = BookEntity(
bookId?.toInt() as Int,
txtBookName.text.toString(),
txtBookAuthor.text.toString(),
txtBookPrice.text.toString(),
txtBookRating.text.toString(),
txtBookDesc.text.toString(),
bookImageUrl
)
val checkFav = DBAsyncTask(applicationContext,bookEntity,1).execute()
val isFav = checkFav.get()
if(isFav){
btnAddToFav.text = "remove from Favourites"
val favColor = ContextCompat.getColor(applicationContext,R.color.colorFavourite)
btnAddToFav.setBackgroundColor(favColor)
}else{
btnAddToFav.text = "add to favourites"
val nofav = ContextCompat.getColor(applicationContext, R.color.colorPrimary)
btnAddToFav.setBackgroundColor(nofav)
}
btnAddToFav.setOnClickListener {
if(!DBAsyncTask(applicationContext,bookEntity,1).execute().get()) {
val async = DBAsyncTask(applicationContext, bookEntity, 2).execute()
val result = async.get()
if (result) {
Toast.makeText(
this#DescriptionActivity,
"book added to favourites",
Toast.LENGTH_LONG
).show()
btnAddToFav.text = "remove from favourites"
val favColor = ContextCompat.getColor(
applicationContext,
R.color.colorFavourite
)
btnAddToFav.setBackgroundColor(favColor)
} else{
Toast.makeText(
this#DescriptionActivity,
"some error occurred",
Toast.LENGTH_LONG
).show()
}
}else{
val async = DBAsyncTask(applicationContext,bookEntity,3).execute()
val result = async.get()
if(result){
Toast.makeText(
this#DescriptionActivity,
"book removed from favourites",
Toast.LENGTH_LONG
).show()
btnAddToFav.text = "add to favourites"
val nofav = ContextCompat.getColor(applicationContext, R.color.colorPrimary)
btnAddToFav.setBackgroundColor(nofav)
}else{
Toast.makeText(
this#DescriptionActivity,
"some error occurred",
Toast.LENGTH_LONG
).show()
}
}
}
} else {
Toast.makeText(
this#DescriptionActivity as Context,
"some error has occurred",
Toast.LENGTH_SHORT
).show()
}
This is the asyncTask code:
class DBAsyncTask(context: Context,val bookEntity: BookEntity, val mode : Int) :
AsyncTask<Void,Void,Boolean>()
{
/*
mode 1: check db if book is in favourite or not
mode 2: save the book into db as favourite
mode 3: remove the favourite book
*/
val db = Room.databaseBuilder(context,BookDatabase::class.java, "book-db").build()
override fun doInBackground(vararg p0: Void?): Boolean {
when(mode){
1-> {
val book: BookEntity? = db.bookDao().getBookById(bookEntity.book_id.toString())
db.close()
return book != null
}
2->{
db.bookDao().insertBook(bookEntity)
db.close()
return true
}
3->{
db.bookDao().deleteBook(bookEntity)
db.close()
return true
}
}
return false
}
}
```

Categories

Resources