I am new to kotlin. Here I am implementing login screen to my application, and the implementation of class using kotlin as below with xml file, but when I am clicking on button or textview onclick is not responding. please help me to resolve this.
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.*
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
class login : AppCompatActivity(), View.OnClickListener {
#BindView(R.id.title) var title: TextView? = null
#BindView (R.id.email) var email : TextView? = null
#BindView (R.id.password) var pass : TextView? = null
#BindView (R.id.tv_fp) var fp : TextView? = null
#BindView (R.id.tv_register) var register : TextView? = null
#BindView (R.id.btn_login ) var login : Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
ButterKnife.bind(this)
// change to register!!.setOnClickListener(this) to make sure your view is injected
register?.setOnClickListener(this)
login?.setOnClickListener(this)
}
// v--- change the parameter type View? to View, it is never be null
override fun onClick(p0: View?) {
// v--- remove it
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
// v--- remove the redundant safe-call ?.
if(p0?.id == R.id.tv_register){
Log.e("login", "i")
var intent = Intent(this#login, signin:: class.java)
startActivity(intent)
}
if(p0?.id == R.id.btn_login){
Toast.makeText(this, "Login Button clicked", Toast.LENGTH_SHORT)
}
}
}
and layout file of this class is as below, i used constrainedLayout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">
<android.support.design.widget.TextInputEditText
android:id="#+id/email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Email id"
android:textCursorDrawable="#drawable/cursor_color"
android:backgroundTint="#color/skyBlue"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="100dp"
app:layout_constraintHorizontal_bias="0.0"
android:inputType="textEmailAddress"/>
<android.support.design.widget.TextInputEditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Password"
android:textCursorDrawable="#drawable/cursor_color"
android:id="#+id/password"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/email"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
android:inputType="textPassword"/>
<Button
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="36dp"
android:background="#color/yellow"
android:textStyle="bold"
app:layout_constraintTop_toBottomOf="#+id/password"
android:layout_marginStart="4dp" />
<TextView
android:id="#+id/tv_fp"
android:layout_width="171dp"
android:layout_height="22dp"
android:text="FORGOT PASSWORD?"
android:background="?attr/selectableItemBackground"
tools:layout_editor_absoluteY="301dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/tv_register"
android:layout_marginTop="6dp"
android:layout_marginBottom="7dp"
app:layout_constraintBottom_toTopOf="#+id/btn_login" />
<TextView
android:id="#+id/tv_register"
android:layout_width="156dp"
android:layout_height="18dp"
android:layout_marginStart="8dp"
android:text="Register"
android:background="?attr/selectableItemBackground"
android:gravity="right"
app:layout_constraintStart_toEndOf="#+id/tv_fp"
app:layout_constraintTop_toTopOf="#+id/button"
android:layout_marginTop="58dp"
app:layout_constraintBottom_toBottomOf="#+id/btn_login"
/>
</android.support.constraint.ConstraintLayout>
Related
To be as clear as possible, I'm going to show the problem with a gif.
As you can see, the text is overlapping in my emulator and I don't know how to solve it, I don't know what I'm doing wrong.
It should be displayed correctly without overlapping. What I'm doing is subscribing to changes in both LiveData and StateFlow. When I press the button, I make it change the value, but instead of changing, it seems to return both values at once (Default and Hello). Could it be that the view is not refreshing? Or could it be a problem with my emulator?
Anyway, I'll leave all the code here in case you can figure it out.
FlowsFragment.kt
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.rr.stateflow_livedata_flow_sharedflow.databinding.FragmentFlowsBinding
import kotlinx.coroutines.flow.collectLatest
class FlowsFragment : Fragment(R.layout.fragment_flows) {
private lateinit var binding: FragmentFlowsBinding
private val viewModel: FlowsViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentFlowsBinding.bind(view)
binding.btnLiveData.setOnClickListener {
viewModel.triggerLiveData()
}
binding.btnStateFlow.setOnClickListener {
viewModel.triggerStateFlow()
}
subscribeToObservables()
}
private fun subscribeToObservables() {
viewModel.liveData.observe(viewLifecycleOwner) {
binding.tvLiveData.text = it
}
lifecycleScope.launchWhenStarted {
viewModel.stateFlow.collectLatest {
binding.tvStateFlow.text = it
}
}
}
}
FlowsViewModel.kt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.*
class FlowsViewModel : ViewModel() {
private val _liveData = MutableLiveData("Default LiveData")
val liveData: LiveData<String> = _liveData
private val _stateFlow = MutableStateFlow("Default StateFlow")
val stateFlow: StateFlow<String> = _stateFlow.asStateFlow()
fun triggerLiveData() {
_liveData.value = "Hello LiveData!"
}
fun triggerStateFlow() {
_stateFlow.value = "Hello StateFlow!"
}
}
fragment_flows.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FlowsFragment">
<TextView
android:id="#+id/tvLiveData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:fontFamily="sans-serif-condensed"
android:text="Hello World!"
android:textColor="#color/black"
android:textSize="34sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnLiveData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="LIVEDATA"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvLiveData" />
<TextView
android:id="#+id/tvStateFlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:fontFamily="sans-serif-condensed"
android:text="Hello World!"
android:textColor="#color/black"
android:textSize="34sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLiveData" />
<Button
android:id="#+id/btnStateFlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="STATEFLOW"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvStateFlow" />
<TextView
android:id="#+id/tvFlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:fontFamily="sans-serif-condensed"
android:text="Hello World!"
android:textColor="#color/black"
android:textSize="34sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnStateFlow" />
<Button
android:id="#+id/btnFlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="FLOW"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvFlow" />
<TextView
android:id="#+id/tvSharedFlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:fontFamily="sans-serif-condensed"
android:text="Hello World!"
android:textColor="#color/black"
android:textSize="34sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnFlow" />
<Button
android:id="#+id/btnSharedFlow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="SHAREDFLOW"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvSharedFlow" />
</androidx.constraintlayout.widget.ConstraintLayout>
I hope that the text doesn't overlap and returns the latest value of LiveData and StateFlow.
Edit with more info: The application displays the view directly from the fragment, MainActivity only has a fragment container that I show below.
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.add
import androidx.fragment.app.commit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.commit {
setReorderingAllowed(true)
add<FlowsFragment>(R.id.mainActivityFragmentContainer)
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/mainActivityFragmentContainer"
android:name="com.rr.stateflow_livedata_flow_sharedflow.FlowsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_flows" />
</androidx.constraintlayout.widget.ConstraintLayout>
EDIT This is not the solution, it's a bad way to solve the problem.
I just have to add this line of code in fragment_flows.xml.
android:background="#color/white"
Just by setting the background of the fragment to white, the text is no longer duplicated and overlapping.
Does anyone know why this happens? Why does what is drawn on the screen stick to the background if there is no background in the fragment layout?
I have a recyclerview with adapter (to show external strings)and I'm trying to click a button "copy" so that it copies the strings in view to the clipboard.
CardLayout.xml Button to use as copy button is android:id="#+id/copyactivity"
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="0dp"
app:cardElevation="0dp"
app:cardMaxElevation="3dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
tools:context="ui.CardLayout">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/idActivityName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="14dp"
android:layout_marginRight="10dp"
android:text="#string/placeholdertasktitle"
android:textColor="#color/black"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/idActivityDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/idActivityName"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="30dp"
android:drawablePadding="2dp"
android:text="#string/let_s_get_started_creating_a_photo_album_for_you_so_you_can_share_with_the_kids_in_the_near_future"
android:textColor="#color/black"
android:textSize="15sp"
tools:ignore="UnknownId" />
<View
android:id="#+id/divider"
android:layout_width="380dp"
android:layout_height="2dp"
android:layout_below="#id/idActivityDescription"
android:layout_alignStart="#id/idActivityName"
android:layout_centerHorizontal="false"
android:layout_centerVertical="false"
android:background="#EDEDED" />
<Button
android:id="#+id/saves"
style="#style/cardbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/divider"
android:layout_alignStart="#id/idActivityName"
android:background="#drawable/cardbutton"
android:contentDescription="#string/saves"
android:stateListAnimator="#null"
android:text="Save"
android:textAlignment="textStart"
android:textColor="#595959"
android:textSize="12sp"
app:icon="#drawable/ic_saves_blank"
app:iconGravity="textStart"
app:iconTint="#595959" />
<Button
android:id="#+id/calendar"
style="#style/cardbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/divider"
android:layout_marginStart="35dp"
android:layout_marginEnd="35dp"
android:layout_toStartOf="#+id/copyactivity"
android:layout_toEndOf="#id/saves"
android:background="#drawable/cardbutton"
android:contentDescription="#string/saves"
android:stateListAnimator="#null"
android:text="#string/calendar"
android:textAlignment="textStart"
android:textColor="#595959"
android:textSize="12sp"
app:icon="#drawable/ic_calendar"
app:iconGravity="textStart"
app:iconTint="#595959" />
<Button
android:id="#+id/copyactivity"
style="#style/cardbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/divider"
android:layout_alignEnd="#id/divider"
android:background="#drawable/cardbutton"
android:contentDescription="#string/saves"
android:stateListAnimator="#null"
android:text="#string/copy"
android:textAlignment="textStart"
android:textColor="#595959"
android:textSize="12sp"
app:icon="#drawable/ic_copytext"
app:iconGravity="textStart"
app:iconTint="#595959" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
And this is my TaskAdapter.kt
package com.example.what2do_v6.Adapter
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.RecyclerView
import com.example.what2do_v6.Model.TaskResponse
import com.example.what2do_v6.R
import com.example.what2do_v6.Repository.TaskRepository
import com.example.what2do_v6.databinding.CardLayoutBinding
import com.example.what2do_v6.ui.CardLayout
import android.content.Context as ContentContext
class TaskAdapter: RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = CardLayoutBinding.inflate(layoutInflater, parent, false)
return TaskViewHolder(binding)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
holder.bind(TaskRepository.list[position])
}
override fun getItemCount(): Int {
return TaskRepository.list.size
}
class TaskViewHolder(private val binding: CardLayoutBinding) : RecyclerView.ViewHolder(binding.root){
var bCopyText: Button? = null
fun bind(task: TaskResponse) {
binding.idActivityName.text = task.title
binding.idActivityDescription.text = task.description
bCopyText = findViewById<View>(R.id.copyactivity) as Button
val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
bCopyText!!.setOnClickListener {
val clipData = ClipData.newPlainText("", task.description,)
clipboardManager.setPrimaryClip(clipData)
Toast.makeText(RecyclerView, "message...", Toast.LENGTH_SHORT).show()
}
}
private fun getSystemService(clipboardService: String): Any {
}
}
}
There are two lines in my code that are throwing up problems:
bCopyText = findViewById<View>(R.id.copyactivity) as Button
and
Toast.makeText(RecyclerView, "message...", Toast.LENGTH_SHORT).show()
I've tried different variances of the two above lines and research many articles on StackOverflow but with no winner, can anyone help?
Managed to get this working utilising help from Gobu:
class TaskViewHolder(private val binding: CardLayoutBinding) : RecyclerView.ViewHolder(binding.root){
fun bind(task: TaskResponse) {
binding.idActivityName.text = task.title
binding.idActivityDescription.text = task.description
binding.copyactivity
binding.copyactivity.setOnClickListener {
val clipboardManager = itemView.context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText("", task.title +"\n\n" + task.description)
clipboardManager.setPrimaryClip(clipData)
Toast.makeText(itemView.context, "Activity copied to clipboard", Toast.LENGTH_SHORT).show()
}
}
First of all, if you're using ViewBinding, why would you declare a variable for your button? Just get it from the binding.
Second, it's giving you an error, because you're making sure (!!) that the button you declare isn't null, but most likely it is, because you're trying to get the ID of a view you don't have.
Third, RecyclerView is not a context, if you are using ViewBinding, you get the context from binding.root.context
I am pretty much a beginner in app development. I am creating a GPA calculator. I was able to create a button that would create a new EditText view for each time it was tapped. but I don't know how can get the values from those EditTexts separately so I can use them to calculate GPA. I looked up every similar question here and on the internet in general, but none of them helped me. Here is my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/layout_list"
android:layout_width="match_parent"
android:layout_height="500dp"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:drawableRight="#drawable/ic_baseline_add_24"
android:text="Add"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</LinearLayout>
<Button
android:id="#+id/calculate_button"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="Calculate"
app:layout_constraintLeft_toLeftOf="#id/layout_list"
app:layout_constraintTop_toBottomOf="#id/layout_list" />
<TextView
android:id="#+id/result"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="13dp"
android:hint="GPA:0.0"
android:textSize="20dp"
app:layout_constraintStart_toEndOf="#id/calculate_button"
app:layout_constraintTop_toBottomOf="#id/layout_list"
tools:text="GPA:0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
new_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/gpa_points"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/custom_input"
android:hint=" GPA point"
android:inputType="number"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/credit_points"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/custom_input"
android:hint=" ETCS"
android:inputType="number"
app:layout_constraintStart_toEndOf="#+id/gpa_points"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/close"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="18dp"
android:background="#drawable/ic_baseline_close_24"
app:layout_constraintLeft_toRightOf="#id/credit_points"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.example.gpacalculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
class MainActivity : AppCompatActivity() {
private var layout: LinearLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
layout = findViewById(R.id.layout_list)
val addButton: Button = findViewById(R.id.add_button)
addButton.setOnClickListener { addView() }
val calculateButton: Button = findViewById(R.id.calculate_button)
calculateButton.setOnClickListener { calculate() }
}
private fun addView() {
val gpaView: View = layoutInflater.inflate(R.layout.new_layout, null, false)
layout?.addView(gpaView)
}
i added this function to my code
fun calculate(){
var total = 0.0
var etcs = 0.0
layout.children.forEach { newLayout ->
// Find the gpa_points EditText in the child layout
val gpaPointsEditText = newLayout.findViewById<EditText>(R.id.gpa_points) as? EditText
val creditsEditText = newLayout.findViewById<EditText>(R.id.credit_points) as? EditText
// Parse the text to be able to perform calculations
val gpaPoints = gpaPointsEditText?.text.toString().toDouble()
val credits = creditsEditText?.text.toString().toDouble()
total+=gpaPoints*credits
etcs+=credits
}
var gpa = total/etcs
val result:TextView = findViewById(R.id.result)
result.text=gpa.toString()
}
but it gives me an error like this
java.lang.NumberFormatException: For input string: "null"
atsun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.example.gpacalculator.MainActivity.calculate(MainActivity.kt:46)
at com.example.gpacalculator.MainActivity.onCreate$lambda1(MainActivity.kt:27)
at com.example.gpacalculator.MainActivity.$r8$lambda$1xRU0rpJNKxzUpdKrPz49s5lowk(Unknown Source:0)
at com.example.gpacalculator.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
You can iterate on the child views of layout, and retrieve the GPA.
// Get a decimal format for the current locale
private val decimalFormat = DecimalFormat.getInstance()
// Iterate on the children of layout
layout.children.forEach { newLayout ->
// Find the gpa_points EditText in the child layout
val gpaPointsEditText = newLayout.findViewById<EditText>(R.id.gpa_points) as EditText
// Parse the text to be able to perform calculations
val gpaPointsStr = gpaPointsEditText.text.toString()
val gpaPoints = decimalFormat.parse(str)
}
To learn more about layouts :
https://developer.android.com/guide/topics/ui/declaring-layout
im new on android
i try create my custom arrayadapter.
I want to access the layout variables from tmpview, but I can't do that. The man in the video I watched was doing the same and he could reach
how can i reach this variables ?
I also added "kotlin-android-extensions" to the plugins section
package com.example.burclar
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import java.security.AccessControlContext
import java.util.zip.Inflater
class myArrayAdapter(var gelencontext: Context, resource: Int,var burcAdlar: ArrayList<String>, var burcTarihler: ArrayList<String>, var burcResimler: ArrayList<Int>): ArrayAdapter<String>(gelencontext, resource){
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var tmpview = convertView
if(tmpview == null){
tmpview = LayoutInflater.from(gelencontext).inflate(R.layout.my_list_view_element,null)
}
tmpview.burcMiniYazi = burcAdlar[position] //there is a problem "unresolved reference"
tmpview.burcMiniResim = burcResimler[position] //there is a problem "unresolved reference"
tmpview.burcMiniTarih = burcTarihler[position] //there is a problem "unresolved reference"
return tmpview!!
}
}
my_list_view_element.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/burcMiniYazi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:text="TextView"
android:textSize="14sp"
app:layout_constraintStart_toEndOf="#+id/burcMiniResim"
app:layout_constraintTop_toTopOf="#+id/burcMiniResim" />
<ImageView
android:id="#+id/burcMiniResim"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
<TextView
android:id="#+id/burcMiniTarih"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="#+id/burcMiniResim"
app:layout_constraintStart_toEndOf="#+id/burcMiniResim" />
<View
android:id="#+id/divider2"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_marginTop="24dp"
android:background="?android:attr/listDivider"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/burcMiniResim" />
</android.support.constraint.ConstraintLayout>
thanks
enter image description here
I'm trying to make a quiz app where on the homepage you click the + button and it takes you to a new page where you input the title of the quiz. Once you click the check button it takes you back to the homepage and the new quiz in the form of a button is created there. However, when I try to use the id for the layout from my mainactivity it returns as null and when the app crashes when I click the check button. Does anyone have any idea how I can fix this?
Second activity:
package com.example.k_ari
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import com.google.android.material.floatingactionbutton.FloatingActionButton
class Page2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_page2)
val button = Button(this#Page2)
button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val txtt = findViewById<EditText>(R.id.txt)
val textmessage: String = txtt.text.toString()
button.setText(textmessage)
val message = "New quiz created"
val toast1= Toast.makeText(applicationContext, message, Toast.LENGTH_LONG)
toast1.setGravity(Gravity.CENTER, 0,0)
val layout = findViewById<LinearLayout>(R.id.mainlayout)
val btn = findViewById<FloatingActionButton>(R.id.floatingActionButton2)
btn.setOnClickListener{
layout.addView(button)
toast1.show()
val intent = Intent(this#Page2, MainActivity::class.java)
startActivity(intent)
}
}
}
Second activity xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/secondlayout"
android:orientation="vertical"
tools:context=".Page2">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#99141414"
android:backgroundTint="#180030"
android:gravity="center_horizontal"
android:padding="20dp"
android:text="Enter the title:"
android:textAlignment="center"
android:textColor="#DADADA"
android:textSize="35sp"
android:textStyle="bold"
android:translationX="50dp"
android:translationY="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.433"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.112" />
<EditText
android:id="#+id/txt"
android:layout_width="361dp"
android:layout_height="67dp"
android:autofillHints="title"
android:background="#99141414"
android:backgroundTint="#180030"
android:hint="title"
android:inputType="text"
android:padding="10dp"
android:textColor="#DADADA"
android:textColorHint="#9ADCDCDC"
android:textSize="28sp"
android:translationX="25dp"
android:translationY="170dp"
app:layout_constraintBottom_toTopOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="#string/todo"
android:focusable="true"
android:translationX="300dp"
android:translationY="400dp"
app:backgroundTint="#180030"
app:layout_constraintBottom_toTopOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.9"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
Main activity:
package com.example.k_ari
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val floatingActionButton = findViewById<FloatingActionButton>(R.id.btn)
floatingActionButton.setOnClickListener{
val intent = Intent(this, Page2::class.java)
startActivity(intent)
}
}
}
Main activity xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainlayout"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:backgroundTint="#250A43"
android:backgroundTintMode="add"
android:clickable="true"
android:contentDescription="#string/todo"
android:tint="#250A43"
android:translationX="280dp"
android:translationY="580dp"
app:backgroundTint="#250A43"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.56"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:rippleColor="#FFFFFF"
app:srcCompat="#android:drawable/ic_input_add"
android:focusable="true" />
</LinearLayout>
Logcat:
2020-12-23 15:32:03.599 1474-1474/com.example.k_ari E/Toast: setGravity() shouldn't be called on text toasts, the values won't be used
2020-12-23 15:32:05.482 1474-1474/com.example.k_ari E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.k_ari, PID: 1474
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
at com.example.k_ari.Page2$onCreate$1.onClick(Page2.kt:35)
at android.view.View.performClick(View.java:8178)
at android.view.View.performClickInternal(View.java:8147)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30233)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8414)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:596)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
You cannot access a View from the Activity that does not hold it.
to handle data between activities like this, you should read about ViewModel and/or SharedPreferences
https://developer.android.com/topic/libraries/architecture/viewmodel
https://developer.android.com/reference/android/content/SharedPreferences