Not Getting Edit Text Data - android

I am New to Android . I don't know how to get the data of EditText in Android .
Here is my Layout:
<?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:orientation="vertical"
tools:context=".MainActivity2">
<EditText
android:id="#+id/edOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/edSecond"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Here is my code :
val one=edOne.text.toString()
btnAdd.setOnClickListener{
val two=edOne.text.toString()
Log.e("Tag",one +" "+two)
}

one is calling from onCreate() method . and at the time of creation of you onCreate() you don't have any data in editText one .So you can't get any data from one if you have not added from xml .
So just move your one code into click listener.
val one=edOne.text.toString()
btnAdd.setOnClickListener{
val two=edOne.text.toString()
Log.e("Tag",one +" "+two)
}

You can access related View elements with findViewById and use them later.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
class MainActivity : AppCompatActivity() {
private lateinit var edOne : EditText
private lateinit var btnAdd : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
edOne = findViewById(R.id.edOne)
btnAdd = findViewById(R.id.btnAdd)
val one=edOne.text.toString()
btnAdd.setOnClickListener {
val two=edOne.text.toString()
Log.e("Tag",one +" "+two)
}
}
}

Related

Problems with webview

I'm creating an application that displays a webview and has a button that opens the Android settings. My problem is that when I add this button, the webview stops working and only show a white screen that doesn't charge. What am I doing wrong? I leave the code below:
PD: If I delete the code starting from "//init code" it works....
MainActivity.kt
package com.becas.apn_mexico
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.View
import com.becas.apn_mexico.base.BaseActivity
import com.becas.apn_mexico.databinding.ActivityMainBinding
import com.google.android.material.floatingactionbutton.FloatingActionButton
class MainActivity : BaseActivity<ActivityMainBinding>() {
companion object {
private const val URL_LINK_WEBSITE = "https://apn.tutorialez.net/index.php/landing-page/"
}
override fun setupViewBinding(): ActivityMainBinding {
return ActivityMainBinding.inflate(layoutInflater)
}
override fun setupViewModel() {
}
override fun setupUI(savedInstanceState: Bundle?) {
binding.mainWebview.loadUrlExt(URL_LINK_WEBSITE)
showAdBanner(binding.adsView.adsPhoneTabSpecialSmartBanner)
showAdInterstitial(getString(R.string.admob_interstitial))
}
// Init Code
private lateinit var fab: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fab = findViewById(R.id.abrir_configuracion)
// Configurando el setonclicklistener
fab.setOnClickListener(View.OnClickListener{
val i = Intent(Settings.ACTION_APN_SETTINGS)
startActivity(i) })
}
}
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.becas.apn_mexico.MainActivity">
<WebView
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/ads_view" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/abrir_configuracion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:layout_above="#id/ads_view"
android:clickable="true"
android:backgroundTint="#color/colorPrimary"
android:contentDescription="#string/open_config_apn"
app:srcCompat="#drawable/ic_baseline_settings_24" />
<include
android:id="#+id/ads_view"
layout="#layout/ads_phone_tab_special_smart_banner" />
</RelativeLayout>
I think your problem is that you are not using the viewbinding to inflate your view:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// You need to get here the binding and put it into the ContentView method
val view = binding.root
setContentView(view)
fab = findViewById(R.id.abrir_configuracion)
// Configurando el setonclicklistener
fab.setOnClickListener(View.OnClickListener{
val i = Intent(Settings.ACTION_APN_SETTINGS)
startActivity(i) })
}
Alternatively, the problem is in your layout. Can you remove the
<include
android:id="#+id/ads_view"
layout="#layout/ads_phone_tab_special_smart_banner" />
From your layout and let me know if you get the expected result?

Kotlin ListView not showing any text

I am currently trying to make a custom to-do list app. I have a ListView element set up and a text field with a buttons to add/remove elements from the list. However, when I add elements, no text shows up. I know that the fields add and remove correctly, the only problem is that there is no text. (image for reference)
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#color/white"
android:visibility="visible"
tools:context=".MainActivity">
...
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:background="#color/white"
android:choiceMode="multipleChoice"
android:divider="#color/black"
android:textColor="#color/black" />
</RelativeLayout>
And here is all the Kotlin code:
package com.example.to_do
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.SparseBooleanArray
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val itemlist = arrayListOf<String>()
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, itemlist)
val add = findViewById<Button>(R.id.add)
val editText = findViewById<EditText>(R.id.editText)
val listView = findViewById<ListView>(R.id.listView)
val delete = findViewById<Button>(R.id.delete)
listView.adapter = adapter
add.setOnClickListener {
val todoitem = editText.text.toString()
if (todoitem.isEmpty() == false) {
itemlist.add(editText.text.toString())
adapter.notifyDataSetChanged()
}
editText.text.clear()
}
delete.setOnClickListener {
val position: SparseBooleanArray = listView.checkedItemPositions
val count = listView.count
var item = count - 1
while (item >= 0) {
if (position.get(item)) {
adapter.remove(itemlist[item])
}
item--
}
position.clear()
adapter.notifyDataSetChanged()
}
}
}
Can anybody help?

Kotlin-Android First App Unresolved Reference TextView with Button

I'm new to android and kotlin development and I am having trouble with my first application.
I am looking to edit my TextView on button click but the compiler is complaining about an unresolved reference.
Here is my activity_main.xml file
<?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">
<Button
android:id="#+id/click_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onTap"
android:text="Click me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="64dp"
android:text="Not clicked..."
app:layout_constraintStart_toStartOf="#+id/click_me"
app:layout_constraintTop_toBottomOf="#+id/click_me" />
</androidx.constraintlayout.widget.ConstraintLayout>
and here is my MainActivity.kt file
package com.example.helloworld
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
//Method will be called on button click
fun onTap(view: View) {
textView.text = "Clicked"
}
}
}
you should define the textview as variable and then you could change it
val textView = findViewById(R.id.text_view_id)  
textView.setText("string").toString()  
val textViewValue = textView.text  
As other user already commented, you should use view binding.
On your app Gradle script.
android {
...
buildFeatures {
viewBinding = true
}
}
Then on your MainActivity
private lateinit var binding: ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.yourButtonID.setOnClickListener {buttonTtapped()}
}
fun buttonTtapped() {
binding.yourTextViewID.text = "Clicked"
}
}
Something like this
you need to apply this in your build.gradle file
plugins {
id 'kotlin-android-extensions'}
and press sync now
then back to your MainActivity it will suggest u to import that view
Kotlin has a feature Say goodbye to findViewById refered for Kotlin Android Extensions. You need to import the import kotlinx.android.synthetic.main.activity_main.* so that you directly use the ID name of the view directly.
To get this work you need to add this plugin in the module-level build.gradle file
apply plugin: 'kotlin-android-extensions'
Another approach by findViewById
class SampleActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onTap(view: View){
val myTextView = findViewById<TextView>(R.id.textView)
myTextView.text = "absc"
}
}

App crashes in Android Studio using Kotlin

I have started from the very basic level in Android and have created a simple app to display Happy Birthday. But the App keeps crashing in both the Emulator and the Actual hardware(SAMSUNG NOTE 8).
Need help on how can i resolve the error.
Here is xml Code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.example.android.happybirthday.MainActivity">
<TextView
android:id="#+id/sample_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_margin="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
MainActivity Code :
package com.example.android.happybirthday
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Example of a call to a native method
sample_text.text = stringFromJNI()
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
}
You forget to typecast your TextView :
Try with below code :
val sample_text : TextView = findViewById<TextView>(R.id.sample_text) as TextView
Full Code :
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sample_text : TextView = findViewById<TextView>(R.id.sample_text) as TextView
sample_text .text = "Happy Birthday"
}
}

How to replace a FrameLayout with a fragment with Kotlin on Android

I'm trying to develop an Android app with Kotlin, but I've hit a bit of a snag when trying to dynamically move fragments around. What I'm trying to do is replace a FrameLayout in an Activity's layout with a fragment. Currently whenever I try to run my app it just shows a white screen under the toolbar leading me to believe that the fragment is not being added to the FrameLayout the way I expected.
Here is my main Activity where I do the first transaction:
package net.ma.ttrobinson.kchan
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import com.androidquery.callback.AjaxStatus
import net.ma.ttrobinson.kchan.api.ChanThread
import net.ma.ttrobinson.kchan.api.Request
import org.jdeferred.DoneCallback
import org.jdeferred.FailCallback
import org.json.JSONArray
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content_frame, MainFragment())
.commit()
}
}
Here is the fragment I'm attempting to create. It simply inflates a view while adding a callback for when a button is pressed:
package net.ma.ttrobinson.kchan
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import com.androidquery.callback.AjaxStatus
import net.ma.ttrobinson.kchan.api.ChanThread
import net.ma.ttrobinson.kchan.api.Request
import org.jdeferred.DoneCallback
import org.jdeferred.FailCallback
/**
* Holds the main content
*/
class MainFragment : Fragment() {
companion object {
val TAG = "MainFragment"
}
val debugBoard = "g"
val debugThread = "48667796"
override fun onCreateView(inflater : LayoutInflater, parent : ViewGroup?, savedInstanceState : Bundle?) : View {
val v = inflater.inflate(R.layout.fragment_main, parent, false)
val boardText = v.findViewById(R.id.board_text) as EditText
val threadText = v.findViewById(R.id.thread_text) as EditText
val request = Request(getActivity())
boardText.setText(debugBoard)
threadText.setText(debugThread)
val button = v.findViewById(R.id.submit) as Button
button.setOnClickListener({ v ->
val board = boardText.getText().toString()
val thread = threadText.getText().toString().toInt()
val promise = request.getThread(board, thread)
promise.done({ thread ->
val fm = getActivity().getSupportFragmentManager()
fm.beginTransaction()
.replace(R.id.main_content_frame, ThreadFragment(thread), ThreadFragment.TAG)
.addToBackStack(null)
.commit()
}).fail({ result ->
Log.v(TAG, "Failed to get thread")
})
})
return v
}
}
Here's the layout that the main Activity uses with setContentView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And lastly here's the layout that the fragment is inflating:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/board_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/board_hint"/>
<EditText
android:id="#+id/thread_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:hint="#string/thread_hint"/>
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit"/>
</LinearLayout>
I feel like this is a fairly straightforward setup of a main Activity that has a FrameLayout that can be swapped out with other fragments. Does anyone know what I might be doing wrong?
In the meantime I suppose I'll try to make a simpler case to try to replicate the behaviour.
EDIT: Such a simple solution. I forgot to add android:orientation="vertical" in my LinearLayout. Here's the updated code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
The problem is that the Activity's LinearLayout should have orientation="vertical":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/main_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Just i want to pay your intention to extension function it's so useful.
Here i will share some steps to do that
Creat a kotlin file called util for example and add those function which allow to add and replace the fragment
util.kt
fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
supportFragmentManager.inTransaction { add(frameId, fragment) }
}
fun AppCompatActivity.replaceFragment(fragment: Fragment, frameId: Int) {
supportFragmentManager.inTransaction{replace(frameId, fragment)}
}
inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
beginTransaction().func().commit()
}
Create your fragment layout. I have call it father_fragment for example
fahter_fragment
<!-- You can put whatever you want here-->
In your Activity xml create a layout which will caontain the fragment:
activity_principal.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tharwa.tdm2_exo2.Principal">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
>
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
Now in youe activity you can easily create the fragment
Principal
class Principal : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_principal)
//Create and add the fragment
val fatherView=FatherPresentation()
addFragment(fatherView,R.id.container)
}
}
if you want to replace the fragment from your activity it's easy just do
replaceFragment(Fragment_you_want_to_replace_with(),id_of_of_your_frame_layout)

Categories

Resources