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
Related
hi i am new in android and kotlin and i have a chat app that will work with sms and want save state of all chat for next run
i did use recyclerView and GroupieViewHolder for show chats , i see some post here but all was with java but i am using kotlin for this app
so if you can please help me and If possible, state the easiest way in the simplest possible way
app screenshot:
my smsActivity.kt:
class smsActivity : AppCompatActivity() {
private val messageAdapter = GroupAdapter<GroupieViewHolder>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sms)
val recyclerView = findViewById<RecyclerView>(R.id.listmessage)
val button = findViewById<Button>(R.id.button)
val editmessage = findViewById<EditText>(R.id.editText)
val sharedPeref = getSharedPreferences("setNumber", MODE_PRIVATE)
val number = sharedPeref.getString("number", null)
recyclerView.adapter = messageAdapter
populateData()
receiveAutoResponse()
button.setOnClickListener {
val message = Message(text = editmessage.text.toString(), sendBy = "me")
val smssend = editmessage.text.toString()
val sendMessageItem = SendMessageItem(message)
messageAdapter.add(sendMessageItem)
editmessage.text.clear()
receiveAutoResponse()
recyclerView.scrollToPosition(messageAdapter.getItemCount() - 1);
try {
val smsManager: SmsManager = SmsManager.getDefault()
smsManager.sendTextMessage(number, null, smssend, null, null)
Toast.makeText(
applicationContext,
"بخاری 3 =دریافت گزارش ✅ دریافت گزارش چندین ثانیه زمان می برد ، لطفا برای ارسال دستور بعدی کمی صبر کنید",
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(
applicationContext,
"لطفا ابتدا شماره سیستم را وارد کنید !",
Toast.LENGTH_SHORT
).show()
val intent = Intent(this, setnumberActivity::class.java)
this.startActivity(intent)
}
}
}
fun ScrollView.scrollToBottom() {
val lastChild = getChildAt(childCount - 1)
val bottom = lastChild.bottom + paddingBottom
val delta = bottom - (scrollY + height)
smoothScrollBy(0, delta)
}
private fun populateData() {
val data = listOf<Message>()
data.forEach {
if (it.sendBy == "me") {
messageAdapter.add(SendMessageItem(it))
} else {
messageAdapter.add(ReceiveMessageItem(it))
}
}
}
private fun receiveAutoResponse() {
GlobalScope.launch(Dispatchers.Main) {
delay(1000)
val sharedPeref = getSharedPreferences("setNumber", MODE_PRIVATE)
val nums = "+98" + sharedPeref.getString("number", null)
val cursor: Cursor? = getContentResolver().query(
Uri.parse("content://sms"),
null,
"address='$nums'",
null,
null
)
cursor?.moveToFirst()
val messageSend = cursor?.getString(12)
val receive = Message(text = "$messageSend", sendBy = "me")
val receiveItem = ReceiveMessageItem(receive)
messageAdapter.add(receiveItem)
val recyclerView = findViewById<RecyclerView>(R.id.listmessage)
recyclerView.scrollToPosition(messageAdapter.getItemCount() - 1);
}
}
}
class SendMessageItem(private val message: Message) : BindableItem<ItemMessageSendBinding>() {
override fun getLayout(): Int {
return R.layout.item_message_send
}
override fun bind(viewBinding: ItemMessageSendBinding, position: Int) {
viewBinding.message = message
}
}
class ReceiveMessageItem(private val message: Message) : BindableItem<ItemMessageReceiveBinding>() {
override fun getLayout(): Int {
return R.layout.item_message_receive
}
override fun bind(viewBinding: ItemMessageReceiveBinding, position: Int) {
viewBinding.message = message
}
}
If you want ensure that Activity re-creation doesn't destroy your content, you can refer to this answer
If you want to connect the data to your local Storage, I suggest you using Room
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?
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()
}
}
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())
}
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()
}