In the raw directory I have files named rhode1.mp3 to rhode49.mp3.
I need to randomly play one of these files so I'm randomly generating a number and attaching it to R.raw.rhode to use as URI (uri1 in the code below), but it crashes the app. When I replace uri1 with R.raw.rhode1 for example it works and the audio file plays.
I tried writing R.raw.rhode$note1.mp3 and it still didn't work. Also tried:
("R.raw.rhode" + note1.toString() + ".mp3")
And:
("R.raw.rhode" + note1.toString())
override fun onCreate (savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var mediaplayer: MediaPlayer? = null
val letsgo = findViewById<Button>(R.id.start)
val think = findViewById<SeekBar>(R.id.think)
val extime = findViewById<SeekBar>(R.id.extime)
val rpt = findViewById<SeekBar>(R.id.rpt)
val rtime = findViewById<SeekBar>(R.id.rtime)
var note1: Int
var uri1: Uri
letsgo.setOnClickListener {
note1 = Random.nextInt(49) + 1
uri1 = Uri.parse("R.raw.rhode" + note1.toString())
mediaplayer = MediaPlayer.create(applicationContext, uri1)
mediaplayer!!.start()
}
}
R.resourceType.resourceName is a valid symbol from the point of the programming language. But it is, obviously, not an URL/URI.
Here is a sample of how to construct a resource URI: https://stackoverflow.com/a/7979084/3050249
Related
I am trying to solve this issue but i didn#t find enything until now. So my Image View its a string and i am trying to call it with Glide.with and many more but unfortunately no success until now. It should be a simple Line of code but i am not finding it.
class ImageInformation : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_information)
val image = intent.getParcelableExtra<ImageModel>("image")
if (image != null){
val downloadUrl: TextView = findViewById(R.id.downloadUrla)
val previewUrl : ImageView = findViewById(R.id.previewUrls)
val id: TextView = findViewById(R.id.idsa)
val filename: TextView = findViewById(R.id.fileNamea)
val filesize: TextView = findViewById(R.id.filesizea)
val contentType: TextView = findViewById(R.id.contentTypea)
val createdBy: TextView = findViewById(R.id.createdBya)
val createdTimestamp: TextView = findViewById(R.id.createdTimestampa)
val creationSource: TextView = findViewById(R.id.creationSourcea)
val domainIdentityType: TextView = findViewById(R.id.domainIdentityTypea)
val domainIdentityValue: TextView = findViewById(R.id.domainIdentityValuea)
val tags: TextView = findViewById(R.id.tagsa)
val description: TextView = findViewById(R.id.descriptiona)
downloadUrl.text = image.downloadUrl
TO DO, Preview URL
//previewUrl.setImageResource(image.previewUrl)//Required Int not a String.
//Glide.with(this).load( previewUrl).into(previewUrl)
//Glide.with(Activity()).load(previewUrl).centerInside().into(previewUrl)
//previewUrl.setImageResource(image.previewUrl)
//Glide.with(Activity()).load(previewUrl).into(image.previewUrl)
//Glide.with(this).load(previewUrl).centerInside().into(image.previewUrl)
//previewUrl.setImageResource(image.previewUrl)
//Nothing from the above lines doesn#t work.
id.text = image.id
filename.text = image.fileName
filesize.text = image.filesize.toString()
contentType.text = image.contentType
createdBy.text = image.createdBy
createdTimestamp.text = image.createdTimestamp
creationSource.text = image.creationSource
domainIdentityType.text = image.domainIdentityType
domainIdentityValue.text = image.domainIdentityValue
tags.text = image.tags.toString()
description.text = image.description
}
}
}
Try this:
Glide.with(context)
.load(image.downloadUrl) // here we are telling Glide what it needs to load
.into(previewUrl) // here we are telling Glide where to load it into (your imageView)
I must say your naming of you ImageView (previewUrl) does make it very hard to read, it might be better to rename it to something like previewImageView.
I tried to make password generator ( only string ) using Kotlin for-loop
when I run the code it's shows me outputs like this
OHDPETGDIKPCIQPHBHKWSQKXB
PJQBCSNRWDSHJJXFISDMBVAGT
XSEVXCONRMXQGHXDADQFNLJYK
its too long password so I tried to use some Kotlin functions (Size,Length) and didn't work with me maybe I just don't know the right way to do it , example I just want Password length size is from 5 to 15 chars
please forget the numbers variable and x variable
Kotlin Code:
class passwordMaker {
private val password = ('a'..'Z') + ('A'..'Z')
private val numbers = arrayOf(1,3,4,5,2,0,4,6,7,'#','#','_','/')
fun passwordMaker(){
var x = numbers
var xy = password.subList(0,25)
for (i in xy){
print(xy.random())
xy.size-3
print((x.random()))
x.size-4
}
}
}
class passwordMaker {
fun getRandomPassword(a: Int): String {
val characterSet =( 'a'..'Z') + ('A'..'Z')
var random = Random(System.nanoTime())
var password = StringBuilder()
for (i in 0 until a){
val psMaker = random.nextInt(characterSet.size)
password.append(characterSet[psMaker])
}
return password.toString()
}
}
I wrote a simple temperature converter app, everything is working fine except when user leaves EditText blank/null but selects one of the radio buttons, The App crashes.
Here is the Kotlin Code:
class MainActivity : AppCompatActivity() {
lateinit var etTemp: EditText
lateinit var radioGroup: RadioGroup
lateinit var btnConverter :Button
lateinit var tempConverted: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Zeeshan's Temperature Converter"
etTemp = findViewById(R.id.etTemp)
radioGroup = findViewById(R.id.radioGroup)
btnConverter = findViewById(R.id.btnConverter)
tempConverted = findViewById(R.id.tempConverted)
btnConverter.setOnClickListener {
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this#MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
}
}
}
You should check if etTemp.text.ToString() == "" (that is empty string) if it is, then do not try to convert it into int. The problem appears when you try to convert "null" value to int.
Inside the listener add a check for for EditText to check whether it is empty or not,
btnConverter.setOnClickListener {
// Add the validation check here ... like this -> if(etTemp.length() > 0){
val id = radioGroup.checkedRadioButtonId
val radioButton = findViewById<RadioButton>(id)
if (radioButton == findViewById(R.id.radioC)){
val temp =etTemp.text.toString().toInt()
val result = temp * 9/5 + 32
tempConverted.setText(result.toString())
}
else if (radioButton == findViewById(R.id.radioF)){
val tempy =etTemp.text.toString().toInt()
val resulty = (tempy - 32) / 1.8
tempConverted.setText(resulty.toString())
}
else{
Toast.makeText(this#MainActivity, "Select one conversion scale", Toast.LENGTH_SHORT).show()
}
// Close the check here -> }
else{
// Prompt the user to put some text in the field - this is called form validation before processing
// Toast.makeText(.....).show
}
}
check if the user has entered some input or not, one way is like below (Kotlin):
if(!etTemp.text.isNullOrEmpty())
{
temp =etTemp.text.toString().toInt()
}
I'm learning myself some android programming (beginning level) and following a tutorial. I'm getting an error when I run/build the project. Expecting member declaration. I've checked the code for typos and syntax errors. I've googled this, but I'm just not sure what it means or what to look for to fix it.
Are other classes used in the project automatically seen by the MainActivity class?
Code in part:
MainActivity.kt:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
val friendlyDestroyer = Destroyer("Invincible")
val friendlyCarrier = Carrier("Indomitable")
val enemyDestroyer = Destroyer("Grey Death")
val enemyCarrier = Carrier("Big Grey Death")
val friendlyShipyard = ShipYard()
friendlyDestroyer.takeDamage(enemyDestroyer.shootShell())
friendlyDestroyer.takeDamage(enemyCarrier.launchAerialAttack())
// Fight back
enemyCarrier.takeDamage(friendlyCarrier.launchAerialAttack())
enemyCarrier.takeDamage(friendlyDestroyer.shootShell())
...
Any line that has an instance to a class with a function call shows the red squiggly line and the error.
In the line: friendlyDestroyer.takeDamage(enemyDestroyer.shootShell()), it shows the expecting member declaration error at just about every part of the line.
This happens on every instance of a class making a call to a class.
I'm not seeing any errors for the other classes/files.
Destroyer.kt:
package com.johndcowan.basicclasses
class Destroyer(name: String) {
// what is the name of the ship
var name: String = ""
private set
// what type of ship is it
// alwys a destroyer
val type = "Destroyer"
// how much the ship can take before sinking
private var hullIntegrity = 200
// how many shots left in the arsenal
var ammo = 1
// cannot be directly set externally
private set
// no external access whatsoever
private var shotPower = 60
// has the ship been sunk
private var sunk = false
// this code runs as the instance is being initialized
init {
// so we can use the name parameter
this.name = "$type $name"
}
fun takeDamage(damageTaken: Int) {
if (!sunk) {
hullIntegrity -= damageTaken
println("$name hull integrity = $hullIntegrity")
if (hullIntegrity <= 0){
println("Destroyer $name has been sunk")
sunk = true
}
} else {
// Already sunk
println("Error Ship does not exist")
}
}
fun shootShell():Int {
// let the calling code know how much damage to do
return if (ammo > 0) {
ammo--
shotPower
}else{
0
}
}
...
What am I missing or not seeing?
Thanks for any tips.
I have a myNode: scalafx.scene.Node that I'd like to turn into a bitmap so that I can save it to disk, compare it to other bitmaps, etc. I think the correct code to turn it into a scalafx.scene.image.WritableImage is
val writableImg = new Scene { root = new Group(myNode) }.snapshot(null)
and then I should be able to turn that into a java.awt.image.RenderedImage with
val renderedImg = SwingFXUtils.fromFXImage(writableImg, null)
The problem, as you've probably realized, is that I have to run the code to get wrImg on the ScalaFX thread. There's a question here that explains how to return a value, but I'm not having any luck translating that to Scala. I tried this:
lazy val writableImg: WritableImage = {
val wrImg = new FutureTask(new Callable[WritableImage]() {
override def call(): WritableImage = {
new Scene { root = new Group(myNode) }.snapshot(null)
}
})
Platform.runLater(wrImg)
wrImg.get()
}
but the code just hangs and never completes. Can anyone provide an idiomatic Scala version and/or tell me why the code never returns?
If you just want to save the image to disk you can simply do it on the same thread avoiding complication passing the image around. Something like this will work:
Platform.runLater {
val node = new Circle {
centerX = 200
centerY = 200
radius = 50
stroke = Color.BROWN
strokeWidth = 2
fill = Color.DARKKHAKI
}
val jfxImage = node.snapshot(new SnapshotParameters(), null)
val bufferedImage = SwingFXUtils.fromFXImage(jfxImage, null)
val file = new File("./snapshot.png")
println("Writing snapshot to: " + file.getAbsolutePath)
javax.imageio.ImageIO.write(bufferedImage, "png", file)
()
}
The empty () to have closure returning Unit, so ScalaFX Platform.runLater is happy.
Update:
If you want to have a value from Platform.runLater the approach you suggested in your question should be in general fine. However, you want to make sure that you do not block the FX Application Thread. If you call Platform.runLater on FX Application Thread you will lock out, so you may want to have something like this
def makeSnapshot() = myNode.snapshot(new SnapshotParameters(), null)
val writableImg = if (Platform.isFxApplicationThread) {
makeSnapshot()
} else {
val futureTask = new FutureTask(new Callable[WritableImage]() {
override def call(): WritableImage = makeSnapshot()
})
Platform.runLater(futureTask)
futureTask.get()
}