editText get text kotlin - android-edittext

How to get editText in kotlin and display with toast.
var editTextHello = findViewById(R.id.editTextHello)
I tried this but shows object
Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()

This is Kotlin, not java. You do not need to get the id of it. In kotlin, just write:
var editTextHello = editTextHello.text.toString()
use the beauty of kotlin ;-)
P.s: BTW, better to choose xml IDs like edx_hello and for the kotlin part, var editTextHello. Then you can differentiate between xml vars and kotlin vars.

You're missing a cast of the View you get from findViewById to EditText:
var editTextHello = findViewById(R.id.editTextHello) as EditText
Then, you want to display the text property of the EditText in your toast:
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
For the record, this is just the more idiomatic Kotlin equivalent to calling getText() on your EditText, like you'd do it in Java:
Toast.makeText(this, editTextHello.getText(), Toast.LENGTH_SHORT).show()

The voted answer is correct but it is not the best one for the Kotlin's world. If you're really interested in entering into this world, I'd recommend you to use extensions. From Kotlin you have kotlin-android-extensions and with it you can do this:
import kotlinx.android.synthetic.reference_to_your_view.editTextHello
and this:
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
please, forget about the getText()... use just this, it is more clean.
ps: read about extensions and you will see you can create your own extensions and do an even more clean usage of the Toast. Something like this:
fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_LONG) = Toast.makeText(this, text, duration).show()
and it being used like this through your classes:
showToast("uhuuu")
but this is beyond the scope we're talking about here.
from: https://kotlinlang.org/docs/tutorials/android-plugin.html

Use this instead it's working fine
val obj=findViewById<EditText>(R.id.editText)
Toast.makeText(this,obj.text, Toast.LENGTH_LONG).show()

use editTextHello.text
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()

Toast.makeText(this, editTextHello.text.toString(), Toast.LENGTH_SHORT).show()
If you make edittext as nullable then the line would be
Toast.makeText(this, editTextHello?.text.toString(), Toast.LENGTH_SHORT).show()

In Kotlin calling .text on your EditText is fine no need to do getText or toString
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
with button click
button?.setOnClickListener {
Toast.makeText(this,editText.text, Toast.LENGTH_LONG).show()
}
Even don't need findViewById

You're missing a cast of the View you get from findViewById to EditText.
But you need a "if" if the control exist then get the text:
val editText = findViewById(R.id.editText_main) as EditText
if (editText != null) {
val showString = editText.text.toString()
Toast.makeText(this, showString, Toast.LENGTH_SHORT).show()
}

Related

GTK4 Vala - show FileChooserDialog

I am playing around with Vala and GTK4.
FileChooserDialog is not working for me
using Gtk;
int main (string[] argv) {
// Create a new application
var app = new Gtk.Application ("com.example.GtkApplication",
GLib.ApplicationFlags.FLAGS_NONE);
app.activate.connect (() => {
// Create a new window
var window = new Gtk.ApplicationWindow (app);
window.title = "File chooser";
window.set_default_size (350, 70);
window.resizable = false;
// Create a new button
var file_choose_button = new Gtk.Button.with_label ("...");
file_choose_button.clicked.connect (() => {
var fileChooser = new FileChooserDialog(
"Select File",
window,
FileChooserAction.OPEN,
"Cancel",
ResponseType.CANCEL,
"Open",
ResponseType.ACCEPT,
null);
fileChooser.response.connect(()=> {
stdout.printf("File selectd!");
});
// WHAT TO DO IN ORDER TO SHOW FILE CHOOSER?
});
window.set_child (file_choose_button);
// Show
window.present ();
});
return app.run (argv);
}
I am missing some important piece of code, that will cause the FileChooserDialog to "appear".
In previous Versions of GTK there is "dialog.run" - which is missing in GTK4.
The C-Example on https://docs.gtk.org/gtk4/class.FileChooserDialog.html uses makro(?) "gtk_widget_show(xxx)" for which I was not able to find an representation in Vala.
Any help appreciated!
Best Regards
Emil
After some struggle the solution was found (and is pretty simple).
As stated in the Vala Documentaion Site - File Chooser Dialog
It inherits from couple of classes one of which is GTK.Window.
So it is as simple as calling the present() method.
Thus the missing command above is:
fileChooser.present();
One should not forget to use the close() method once file was selected or selection was canceled.
Important note:
"gtk_widget_show()" representation in Vala is GTK.Widget.show() BUT
I was not clever enough to find out how to prepare the parameter.
It expects pointer (GtkWidget*) and simply passing the "fileChooser" causes all kinds of compiler exceptions.
May be someone can throw more light on this (as I am using Vala to avoid the use of C - I am clearly not the expert in this area)

Return/break out of infinite foreach in kotlin

For class I have to make a program that calculates the birthday problem
Now I'm having trying to learn kotlin at the same time and I'm having trouble with a little snippet of code:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#outForeach
}
}
outForeach#
sum += checkSet.size
As you can see I'm trying to do this with an infinite sequence. Kotlin doesn't accept this as outForeach is an unresolved reference. But this doesn't work either:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#forEach
}
}
sum += checkSet.size
This will just start the forEach loop again. Is there a way to implement something as a forEachUntil or so?
p.s. I'm aware that this looks a lot like this question: 'return' doesn't jump out of forEach in Kotlin It's just that I don't really get the answers and I don't know if its applicable here. Also a way to implement forEachUntil seems for me to be far more elegant
Alternatives you may want to consider instead of first:
using a simple while without body:
while (checkSet.add(Random.nextInt(n))); // <- that semicolon is required! otherwise you execute what is coming next within the while
using run with a label:
run outForeach#{
generateSequence{ Random.nextInt(n)}.forEach {
if(!checkSet.add(it)) {
return#outForeach
}
}
}
maybe also takeWhile might be helpful. In this specific case however it is surely not (as it would check against the checkSet and leave us with a sequence that isn't consumed... but if the condition would be different, it may make sense to consider something like take, takeWhile, takeLast, etc.):
generateSequence { Random.nextInt(n) }
.takeWhile(checkSet::add) // as said: for this specific condition it doesn't make sense...
.forEach { /* do nothing except consume the sequence */ } // the same values you added to the set would be available in this step of course
I think I found the solution myself:
val checkSet = mutableSetOf<Int>()
generateSequence{ Random.nextInt(n)}.first { !checkSet.add(it) }
sum += checkSet.size
Basically use the function first() and keep returning false until you want to get out of the loop. And just drop the return of the function first()

How to replace DomRepeatModel.item?

I have the following code snippet that listen on button click event for item on a list created by dom-repeat (Polymer 1.0.0-rc.17). According to polymer.dart change.log, DomRepeatModel.item is now deprecated, although it will properly use the as attribute for now. The [] operator has been added in its place. Anyone knows how to apply it to the code to get the same result?
#reflectable
handlePurchase(event, [_]) {
print('Purchase item');
var model = new DomRepeatModel.fromEvent(event);
ShopItem item = model.item;
print(item.name);
print(item.price);
}
Found the answer, it is simply model['item'].

How do you pass statements through an addEventListener?

Iv been trying to pass arguments through an addEventListener event in actionscript such as...
target.addEventListener("pComp", rakeSoil(target));
but i get errors.
Iv tried to google but no luck :/
Thanks for replying if you do :)
The target is already passed as part of the event, either event.currentTarget or event.target will be what you want.
If you want something else passed, create a custom event. Add the property to the custom event.
Try adding an additional method as your event listener:
target.addEventListener ("pComp", targetListener);
...
private function targetListener (event:Event):void {
rakeSoil (event.currentTarget);
}
How this is what you want:
{
var target:EventDispatcher = ...;
Function rakeSoil = function (e:Event):void
{
// handle target
}
target.addEventListener("pComp", rakeSoil);
}
rakeSoil is a first class function(or closure), when event is dispatched, it will be invoked, and you can access 'target' in it.
EDIT:
Have a look at Closure (computer science)
I have always found anonymous functions to be more trouble than they are worth. I would simply follow the standard event handler code layout. It's more formal and takes a little more effort up front, but there is no ambiguity and it is far more readable when you return to it a year from now (reduces head-scratching duration):
// Target extends EventDispatcher
private var target:Target;
public function listenToTarget();
{
target = new Target();
target.addEventListener("pComp", pCompHandler);
}
private function pCompHandler(event:Event):void
{
target.rakeSoil();
}
Although, now that I look at it more closely, why are you having this object do something that Target should be capable of handling internally on its own?

Very basic AChartEngine XY

I've been trying for hours to get something as simple as displaying a line chart based on 2 dots that I supply manually and all I get is a crash. I've tried to understand how everything works based on the demo code but it's too complex. I'm not even concerned about writing nice code with onResume() etc, I just want something to display the first time I open the activity. Once I know how to do that I'll be able to adapt and learn what I need. Here's the code I came up with:
public class StatsActivity extends Activity {
private XYMultipleSeriesDataset StatsDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer StatsRenderer = new XYMultipleSeriesRenderer();
private XYSeries StatsCurrentSeries;
private GraphicalView StatsChartView;
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.stats);
LinearLayout layout = (LinearLayout) findViewById(R.id.Statschart);
StatsRenderer.setAxesColor(Color.YELLOW);
String seriesTitle = "Rank";
XYSeries series = new XYSeries(seriesTitle);
series.add(5, 7); //1st series I want to add
StatsDataset.addSeries(series);
series.add(9, 1); //the 2nd one
StatsDataset.addSeries(series);
StatsCurrentSeries = series;
System.out.println(series);
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.RED);
StatsRenderer.addSeriesRenderer(renderer);
StatsChartView = ChartFactory.getLineChartView(this, StatsDataset,StatsRenderer);
layout.addView(StatsChartView);
}
}
I've been reading the docs to determine what each function does but in the end I still can't get anything to display.
Thanks!
The big thing that I struggled with is that you need a renderer for each XYSeries. You have two series here, but just one renderer - I just create/add renderers when I input data. Also, Android is mostly pass-by-reference, so you've passed the same data set in twice (i.e. your second update to the data will be mirrored "in" the MultipleSeriesDataset).

Resources