I start doing a simple android app for practice to calculate the age with Kotlin programming language, the error came from the line 34, can someone help me with this and fix it to know where is my wrong because I am just very beginner
package com.calcult.age.agecalcult
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var my_age_number = ageText.text!!
var my_month_number = ageText2.text!!
var my_day_number = ageText3.text!!
var calcult_age_button = doIT
calcult_age_button.setOnClickListener {
if(my_age_number.isEmpty()){
Toast.makeText(this,"ادخل سنه ميلادك !",Toast.LENGTH_LONG).show()
}else if (my_age_number.length < 4 || my_age_number.length > 4){
Toast.makeText(this,"ادخل سنه ميلاديه صالحه الأستعمال !",Toast.LENGTH_LONG).show()
}else if (my_age_number.length == 4){
fun getAge(){
val get_the_year = Calendar.getInstance().get(Calendar.YEAR);
val calculat_the_age = my_age_number - get_the_year
}
}
}
}
}
my_age_number is a String value, so you should try
var calculat_the_age: Int? = null
try {
calculat_the_age = my_age_number.toInt() - Calendar.getInstance().get(Calendar.YEAR)
} catch (ex: NumberFormatException) {
// my_age_number not a number
}
hope this helps!
Related
when i build smaple project , app has been crashed
when i see logcat , i see this:
90-30676/io.agora.agora_android_uikit E/agora.io: jni_generator_helper.h: (line 131): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
what do i do ?
My code:
package io.agora.agora_android_uikit
import android.Manifest
import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import io.agora.agorauikit_android.AgoraButton
import io.agora.agorauikit_android.AgoraConnectionData
import io.agora.agorauikit_android.AgoraSettings
import io.agora.agorauikit_android.AgoraVideoViewer
import io.agora.agorauikit_android.requestPermission
import io.agora.rtc2.Constants
private const val PERMISSION_REQ_ID = 22
private val REQUESTED_PERMISSIONS = arrayOf<String>(
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
#ExperimentalUnsignedTypes
class MainActivity : AppCompatActivity() {
var agView: AgoraVideoViewer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
try {
agView = AgoraVideoViewer(
this, AgoraConnectionData("*******"),
)
} catch (e: Exception) {
println("Could not initialise AgoraVideoViewer. Check your App ID is valid. ${e.message}")
return
}
val set = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
this.addContentView(agView, set)
if (AgoraVideoViewer.requestPermission(this)) {
agView!!.join("test", role = Constants.CLIENT_ROLE_BROADCASTER)
} else {
val joinButton = Button(this)
// this#MainActivity.runOnUiThread(java.lang.Runnable {
runOnUiThread {
Runnable { joinButton.text = "Allow Camera and Microphone, then click here" }
}
// })
joinButton.setOnClickListener {
if (AgoraVideoViewer.requestPermission(this)) {
// (joinButton.parent as ViewGroup).removeView(joinButton)
agView!!.join("test", role = Constants.CLIENT_ROLE_BROADCASTER)
}
}
// joinButton.setBackgroundColor(Color.GREEN)
// joinButton.setTextColor(Color.RED)
this.addContentView(
joinButton,
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 300)
)
}
}
i want to solve my issue
Please wrap with function and make annotations there instead of mentioning in the main content view and wrap using UI thread.And refer sample github agora sdk github for reference - https://github.com/AgoraIO-Community/VideoUIKit-Android
Super new to kotlin. My code seems to be bugging out at this line:
else if (userInput == randomNumber){
message = "Horray! You got it!\n Play again?"
}
Seems like a quick fix but I'm not sure...When I input according to the hint, it doesn't register the correct answer at all. It's stuck on "higher/lower" and gives no option for the game to end. I'll attach the entire thing if it helps:
Thanks so much in advance.
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import android.view.inputmethod.InputMethodManager
import android.view.View
import android.widget.Toast
import kotlin.random.Random
import kotlin.random.Random.Default.nextInt
class MainActivity : AppCompatActivity() {
private var userAttempts = 0
private val UPPER_BOUND = 100
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun buttonClick(view: View){
val userInput = numberGuess.text.toString().toInt()
userAttempts ++;
val randomNumber = generateRandomNumber();
var message = ""
if (userInput < randomNumber) {
message = "Higher!"
}
else if (userInput > randomNumber) {
message = "Lower!"
}
else if (userInput == randomNumber){
message = "Horray! You got it!\n Play again?"
}
hint.text = message
attempts.text = "attempts: " + userAttempts
numberGuess.text.clear()
}
private fun generateRandomNumber(): Int {
return Random.nextInt(UPPER_BOUND)
}
}
i'm making an app on AndroidStudio and I need to verify credentials when they log in to the app. The app works with an API and to verifiy credentials i created this function in the database to check someones email and password:
(postgresql)
create or replace function login (emailf text, passwordf text)
returns boolean
language plpgsql
as
$$
declare pp text;
begin
pp = (select pass_w from utilizador where utilizador.email = emailf);
if (pp = passwordf) then return true;
else return false;
end if; end
$$
I'm parsing the data through this CheckLoginas function:
var bola: Boolean? = null
fun CheckLoginas(c: Context?, email: String, pass: String): Boolean? {
var mQueue: RequestQueue
mQueue = Volley.newRequestQueue(c);
var url = "https://myurl.com" + "/utilizador/login/" + email + "/" + pass
val request = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener {
response ->try {
var jsonArray = JSONArray()
jsonArray = response.getJSONArray(0)
for (i in 0 until jsonArray.length())
{
val jsonObject : JSONObject? = jsonArray.getJSONObject(i)
//val user = jsonArray.getJSONObject(i)
//val bool = jsonObject.getBoolean("login")
val boo : Boolean = jsonObject!!.getBoolean("login")
println("im inside CheckLoginas boo $boo\n\n")
bola = boo
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, Response.ErrorListener { error -> error.printStackTrace() })
mQueue?.add(request)
return bola
}
'bola' variable is a global variable because I needed to return a boolean from the function so I can know if the credentials check (or not) in another activity.
The Problem:
To login when the credentials are correct, I have to press twice in the login button. If the email and password are correct, the first time I press it gives me the "Wrong credentials" error and in the second time it logs in. I already tried to do it with a while(), I checked it step by step and it seems fine, nothing seems to work to fix this error... The function works, the API too, and the app itself kinda works too, it just has this bug of clicking twice on the button... This is the activity code:
package com.example.crowdzero
import CheckLoginas
import Database
import android.content.Intent
import android.os.Bundle
import android.view.View.OnFocusChangeListener
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.textfield.TextInputLayout
import java.lang.Thread.sleep
class Login : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val log_in_btn_log_in = findViewById<Button>(R.id.log_in_btn_log_in)
val log_in_btn_registar = findViewById<Button>(R.id.log_in_btn_registar)
log_in_btn_log_in.setOnClickListener {
verificacao()
}
log_in_btn_registar.setOnClickListener {
val intent = Intent(this, Registo::class.java)
startActivity(intent)
}
}
private fun verificacao() {
val log_in_input_text_email = findViewById<TextInputLayout>(R.id.log_in_input_text_email)
val log_in_input_text_password = findViewById<TextInputLayout>(R.id.log_in_input_text_password)
val string_email = log_in_input_text_email?.getEditText()?.getText().toString()?.trim()
val string_password = log_in_input_text_password?.getEditText()?.getText().toString()?.trim()
if (string_email.isNullOrEmpty())
{
log_in_input_text_email.setError(" ")
}
else if (string_password.isNullOrEmpty())
{
log_in_input_text_password.setError(" ")
}
else
{
val email = log_in_input_text_email.editText?.text.toString()
val password = log_in_input_text_password.editText?.text.toString()
//var baca = CheckLoginas(this,email,password)
println(email)
println(password)
var baca: Boolean? = null
baca = CheckLoginas(this, email, password)
//baca = CheckLoginas(this,email,password)
if (baca == false) {
//Toast.makeText(this, "Esta conta não está registada", Toast.LENGTH_SHORT).show();
println("Im inside if in login baca $baca")
} else if (baca == true) {
Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
val intent = Intent(this, Home::class.java)
startActivity(intent)
finish()
}
}
}
}
When I test this with an actual email and password from the database, baca variable stays false when it should be true, since CheckLoginas boo var is true. This is what is causing the problem.
image that shows it
I'm fairly new to the Database-API-App thing, so please forgive me if its a trivial thing
You are calling baca = CheckLoginas(this, email, password)
baca will not update immedietly, the next line if (baca == false) will be executed before you API response arrives, so after you got some response baca becomes true. This is why you need to click twice.
SOLVED:
I pretty much inserted the CheckLoginas function inside the login.kt file. It works now! It looks like this now:
package com.example.crowdzero
import Database
import android.content.Intent
import android.os.Bundle
import android.view.View.OnFocusChangeListener
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.textfield.TextInputLayout
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.lang.Thread.sleep
class Login : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val log_in_btn_log_in = findViewById<Button>(R.id.log_in_btn_log_in)
val log_in_btn_registar = findViewById<Button>(R.id.log_in_btn_registar)
log_in_btn_log_in.setOnClickListener {
verificacao()
}
log_in_btn_registar.setOnClickListener {
val intent = Intent(this, Registo::class.java)
startActivity(intent)
}
}
private fun verificacao() {
val log_in_input_text_email = findViewById<TextInputLayout>(R.id.log_in_input_text_email)
val log_in_input_text_password = findViewById<TextInputLayout>(R.id.log_in_input_text_password)
val string_email = log_in_input_text_email?.getEditText()?.getText().toString()?.trim()
val string_password = log_in_input_text_password?.getEditText()?.getText().toString()?.trim()
if (string_email.isNullOrEmpty())
{
log_in_input_text_email.setError(" ")
}
else if (string_password.isNullOrEmpty())
{
log_in_input_text_password.setError(" ")
}
else
{
val email = log_in_input_text_email.editText?.text.toString()
val password = log_in_input_text_password.editText?.text.toString()
var mQueue: RequestQueue
mQueue = Volley.newRequestQueue(this);
var url = "https://myurl.com" + "/utilizador/login/" + email + "/" + password
val request = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener {
response ->try {
var jsonArray = JSONArray()
jsonArray = response.getJSONArray(0)
for (i in 0 until jsonArray.length())
{
val jsonObject : JSONObject? = jsonArray.getJSONObject(i)
//val user = jsonArray.getJSONObject(i)
//val bool = jsonObject.getBoolean("login")
val boo : Boolean = jsonObject!!.getBoolean("login")
println("im inside CheckLoginas boo $boo\n\n")
if (boo == false) {
Toast.makeText(this, "Esta conta não está registada", Toast.LENGTH_SHORT).show();
} else if (boo == true) {
Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
val intent = Intent(this, Home::class.java)
startActivity(intent)
finish()
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, Response.ErrorListener { error -> error.printStackTrace() })
mQueue?.add(request)
}
}
}
kotlin code for android app
This is the code for reading the data from the firebase firestore database.. but unable to get data from firestore database where is the falt in the code
these two Error show in logcat:
2021-05-09 02:12:26.315 19481-19481/? E/raunak.alison_: Unknown bits set in runtime_flags: 0x8000
2021-05-09 02:12:26.828 19481-19481/com.raunak.alison_4 E/libc: Access denied finding property "ro.vendor.df.effect.conflict"
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.auth.User
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.comment_list_view.*
import java.util.*
class home : AppCompatActivity() {
var selectCategery = Funny
lateinit var commentAdopter: CommentAdopter
val comment_detail = arrayListOf<data_constructer>()
val commentClollectionRef = FirebaseFirestore.getInstance().collection(Reference_data)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
commentAdopter = CommentAdopter(comment_detail)
recycler_list_view.adapter = commentAdopter
val layoutManager = LinearLayoutManager(this)
recycler_list_view.layoutManager = layoutManager
commentClollectionRef.get()
.addOnSuccessListener { snapshot ->
for (document in snapshot.documents) {
val data = document.data
val name = data!![USERNAME] as String
val timestamp = data[TIMESTAMP] as Date
val comment = data[COMMENT] as String
val numLikes = data[NUM_LIKES] as Long
val numComments = data[NUM_COMMENTS] as Long
val documentId = document.id
val newThoughts = data_constructer(
name,
timestamp,
comment,
numLikes.toInt(),
numComments.toInt(),
documentId
)
comment_detail.add(newThoughts)
}
commentAdopter.notifyDataSetChanged()
}.addOnFailureListener { exception ->
Log.e("Exception", "Could not add post:$exception")
}
}
fun mainFunnyClicked(view: View) {
if (selectCategery == Funny) {
main_funnyBtn.isChecked = true
return
}
main_seriousBtn.isChecked = false
main_crazyBtn.isChecked = false
main_populerBtn.isChecked = false
selectCategery = Funny
}
fun mainSeriousClicked(view: View?) {
if (selectCategery == SERIOUS) {
main_seriousBtn.isChecked = true
return
}
main_funnyBtn.isChecked = false
main_crazyBtn.isChecked = false
main_populerBtn.isChecked = false
selectCategery = SERIOUS
}
fun mainCrazyClicked(view: View?) {
if (selectCategery == CRAZY) {
main_crazyBtn.isChecked = true
return
}
main_seriousBtn.isChecked = false
main_funnyBtn.isChecked = false
main_populerBtn.isChecked = false
selectCategery = Funny
}
fun mainPopulerClicked(view: View?) {
if (selectCategery == POPULAR) {
main_populerBtn.isChecked = true
return
}
main_seriousBtn.isChecked = false
main_funnyBtn.isChecked = false
main_crazyBtn.isChecked = false
selectCategery = Funny
}
}
when i comment down the code below: application run fine..
commentClollectionRef.get()
.addOnSuccessListener { snapshot ->
for (document in snapshot.documents) {
val data = document.data
val name = data!![USERNAME] as String
val timestamp = data[TIMESTAMP] as Date
val comment = data[COMMENT] as String
val numLikes = data[NUM_LIKES] as Long
val numComments = data[NUM_COMMENTS] as Long
val documentId = document.id
val newThoughts = data_constructer(
name,
timestamp,
comment,
numLikes.toInt(),
numComments.toInt(),
documentId
)
comment_detail.add(newThoughts)
}
commentAdopter.notifyDataSetChanged()
}.addOnFailureListener { exception ->
Log.e("Exception", "Could not add post:$exception")
}
how can i read the data from the firestore database give me the simple
code example for kotlin if i want to upload and read the data ... as
well as images on firebase.. help me out
I am able to tun my test but it fails. The problem is, mocked method is still returning wrong data. This is my method that I want to test it:
fun getTextByLanguage(list: List<TitleModel>) : String {
val deviceLanguage = Locale.getDefault().language
var default = ""
for (item in list) {
if (item.culture.contains(deviceLanguage, true)) return item.value
if (item.culture.contains("en", true)) default = item.value
}
return default
}
And this is how I am testing the method:
import junit.framework.TestCase.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.api.mockito.PowerMockito.*
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.Locale
#RunWith(PowerMockRunner::class)
#PrepareForTest(Locale::class)
class AppConfigUtilityByPowerMockTest {
#Test
fun `getTextByLanguage, test en`() {
mockStatic(Locale::class.java)
val mockedLocal = mock(Locale::class.java)
`when`(Locale.getDefault()).thenReturn(mockedLocal)
`when`(mockedLocal.language).thenReturn("en")
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list)
assertEquals("Home", actual)
}
#Test
fun `getTextByLanguage, test fr`() {
mockStatic(Locale::class.java)
val mockedLocal = mock(Locale::class.java)
`when`(Locale.getDefault()).thenReturn(mockedLocal)
`when`(mockedLocal.language).thenReturn("fr")
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list)
assertEquals("HomeFr", actual)
}
}
The first test cases without problem but the second one fails. This is the out put:
junit.framework.ComparisonFailure: expected:<Home[Fr]> but was:<Home[]>
Expected :HomeFr
Actual :Home
One way to answer the question is to get rid of Local class from the method and do stuff in Kotlin way. So, what I did is to change my original method like this:
fun getTextByLanguage(list: List<TitleModel>, deviceLanguage: String = getDeviceLanguage()) : String {
var default = ""
for (item in list) {
if (item.culture.contains(deviceLanguage, true)) return item.value
if (item.culture.contains("en", true)) default = item.value
}
return default
}
fun getDeviceLanguage(): String {
return Locale.getDefault().language
}
Now my test class looks like this:
import junit.framework.TestCase.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.Locale
#RunWith(PowerMockRunner::class)
#PrepareForTest(Locale::class)
class AppConfigUtilityByPowerMockTest {
#Test
fun `getTextByLanguage, test en`() {
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list, "en")
assertEquals("Home", actual)
}
#Test
fun `getTextByLanguage, test fr`() {
val list = listOf(TitleModel("en-ca", "Home"), TitleModel("fr-ca", "HomeFr"))
val actual = getTextByLanguage(list, "fr")
assertEquals("HomeFr", actual)
}
}
Although my test passes, I am still willing to see your recommendation and down to accept your answer to my question.