I am trying to display an image selected from the gallery in a image view using ACTION_GET_CONTENT, but it is not working for some reason.
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">
<ImageView
android:id="#+id/imgViewTakePhoto"
android:layout_width="270dp"
android:layout_height="400dp"
app:layout_constraintBottom_toTopOf="#+id/btnTakePhoto"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnTakePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Image"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.754" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt:
package com.example.fundamentals
import android.app.Activity
import android.content.Intent
import androidx.appcompat.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)
btnTakePhoto.setOnClickListener {
Intent(Intent.ACTION_GET_CONTENT).also {
it.type = "image/*"
startActivityForResult(it,0)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == Activity.RESULT_OK && requestCode == 0){
val uri = data?.data
imgViewTakePhoto.setImageURI(uri)
}
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fundamentals">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am able to select the image from gallery but it is not being displayed in the image view i.e. imgViewTakePhoto .
I tried searching for answers here, some people said for Android 11 or higher, I have to add an external query to my manifest file but that did not worked either.
This was the query:
<queries>
<intent>
<action android:name="android.intent.action.GET_CONTENT" />
<data android:mimeType="image/*"/>
</intent>
</queries>
I don't think the version of Android is a problem here because I tried it again on Android 9, and it didn't work.
startActivityForResult has been deprecated in favour of newer and modern registerForActivityResult and ActivityResultContracts.
Therefore what you should rather be doing is firstly creating an ActivityResultLauncher like following :
private val getImage = registerForActivityResult(ActivityResultContracts.OpenDocument()) {
it?.let {
imgViewTakePhoto.setImageURI(it)
}
}
and then calling it inside your buttons on click like this :
btnTakePhoto.setOnClickListener {
getImage.launch(arrayOf("image/*"))
}
Note that registerForActivityResult is supposed to be initialised before your activity comes into context due to the actual callback registering process which is why it should be directly instantiated as a variable before onCreate is called. If that is not the case then launching the result launcher would throw some state related exception.
Following is the final code for your MainActivity:
class MainActivity : AppCompatActivity() {
private val getImage = registerForActivityResult(ActivityResultContracts.OpenDocument()) {
it?.let {
imgViewTakePhoto.setImageURI(it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnTakePhoto.setOnClickListener {
getImage.launch(arrayOf("image/*"))
}
}
}
Related
I'm working on a kotlin app that simply display a pop-up when buttons are pressed, but for some reason whenever i run the app all i get is a blank white screen. I've tried so many solutions online all to no avail.
Here's my Main Activity code:
import android.app.AlertDialog
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.popup.R
import com.example.popup.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private var activityMainBinding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.lay_custom_dialog)
title = "POP UP"
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// add the following three lines
activityMainBinding?.btnShowDefaultDialog?.setOnClickListener {
showDefaultDialog()
}
}
override fun onDestroy() {
activityMainBinding = null
super.onDestroy()
}
private fun showDefaultDialog() {
val alertDialog = AlertDialog.Builder(this)
alertDialog.apply {
setIcon(R.drawable.ic_hello)
setTitle("Hello")
setMessage("I just wanted to greet you. I hope you are doing great!")
setPositiveButton("Positive") { _, _ ->
toast("clicked positive button")
}
setNegativeButton("Negative") { _, _ ->
toast("clicked negative button")
}
setNeutralButton("Neutral") { _, _ ->
toast("clicked neutral button")
}
}.create().show()
}
private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
And here's the activity_main.xml file(the button views are displayed on the view pager, but not on the device when run)
\<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"\>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnShowDefaultDialog"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/show_dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.912" />
<Button
android:id="#+id/btnShowCustomDialog"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/show_custom_dialog"
app:layout_constraintBottom_toTopOf="#id/btnShowDefaultDialog"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.238"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.977" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here's the Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Popup"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
In onCreate() you call
setContentView(R.layout.lay_custom_dialog)
however, you say that the layout file for your Activity is called activity_main.xml. You should be doing this:
setContentView(R.layout.activity_main)
I am new to android application development and I am trying to create a voice assistant in Kotlin. When I try to use my microphone it seems that my SpeechRecognizer doesn't work. I followed the directions of this video, but when I test my app on emulator it seems that SpeechRecognizer isn't avaiable. I also tried this issue on github, but it didn't help me.
The result is always the same. I always get the text string I wrote in case the SpeechRecognizer.isRecognitionAvailable is not available.
Here is what i have tried to do:
Add all permition to my application from android settings
Enable the microphone from emulator settings
Here is my scrips:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.firstkotlinproject">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.speech.RecognitionService"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.FirstKotlinProject"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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"
android:background="#525252">
<TextView
android:id="#+id/textView_to_change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFA500"
android:textSize="24sp"
android:text="Hello"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_to_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_to_change"
android:textColor="#FFA500"
android:backgroundTint="#000"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity
package com.example.firstkotlinproject
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
private val requestCodeDefoult = 102
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button_to_click.setOnClickListener {
askSpeechInput()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == requestCodeDefoult && resultCode == Activity.RESULT_OK) {
val result :ArrayList<String>? = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
textView_to_change.text = result?.get(0).toString()
}
}
private fun buttonPressed() :Boolean {
var result = false
if (button_to_click.isPressed) {
result = true
}
return result
}
private fun askSpeechInput() {
if (!SpeechRecognizer.isRecognitionAvailable(this)) {
Toast.makeText(this, "Speech recognition is not avaiable!", Toast.LENGTH_SHORT).show()
} else if (!buttonPressed()) {
Toast.makeText(this, "Press the button to speak", Toast.LENGTH_SHORT).show()
} else {
val i = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ITALIAN)
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something...")
startActivity(i)
}
}
}
**Hello everyone, I'm new to programming. When I press the button, nothing happens, I can't find the error. Please see. On assignment, I need to create a message listener (Receiver) and send text data to it by clicking on a button. Show the received data in Toast. .xml file:
**
<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/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/btn_send_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
.kt file:
package kg.tutorialapp.homework_47
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val myAction = "kg.tutorialapp.action.MESSAGE"
private val alarmMessage = "Hello world!"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener { sendMessage() }
}
private fun sendMessage() {
val intent = Intent()
intent.action = myAction
intent.putExtra("kg.tutorialapp.broadcast.MESSAGE", alarmMessage)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
sendBroadcast(intent)
}
}
receiver file:
class Receiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Toast.makeText(context, "Новое сообщение: " + intent.getStringExtra("kg.tutorialapp.broadcast.MESSAGE"), Toast.LENGTH_LONG).show()
}
}
> manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="kg.tutorialapp.homework_47">
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Homework_47"
tools:ignore="AllowBackup">
<receiver
android:name=".Receiver"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedReceiver">
<intent-filter>
<action android:name="kg.tutorialapp.action.MESSAGE"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try removing android:permission="TODO" from your reciever's manifest declaration.
Refer here
I made a simple telephone app for android, I was do Permission internet in Android Manifest file on android studio, I use this method for make my app can be used for calling android.Manifest.permission.CALL_PHONE.
but when I run my code nothing happens
this is the first class :
class MainActivity : AppCompatActivity() {
val mobno: String = "1234567890"
val REQUEST_PHONE_CALL = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val call = findViewById<Button>(R.id.phone_call)
call.setOnClickListener {
if (ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.CALL_PHONE
) != PackageManager.PERMISSION_GRANTED
) {
}
}
}
private fun makecall() {
val intent = Intent(Intent.ACTION_CALL, Uri.fromParts("tel", mobno, null))
startActivity(intent)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_PHONE_CALL) {
makecall()
}
}
}
this is my 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:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/phone_call"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:text="Place Call" />
</LinearLayout>
this is my manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.telephoneappkotlin">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
in my graddle I don't use any Library implementation.
Add this in your manifest
<uses-permission android:name="android.permission.CALL_PHONE" />
My app works absolutely fine on the emulator. but when i get it to a real phone (tried on multiple: one plus 7t pro running android 10, Samsung M20 running android 10), the second activity doesnt launch at all.
I tried a simple app that just launches a second activity & nothing happens even in this. Im out of ideas on what to do!
Here is my main activity:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun btnClick(view: View){
intent.setClass(this,ViewExpenseList::class.java)
intent.putExtra("Text",findViewById<TextView>(R.id.helloWorld).text.toString())
startActivityForResult(intent,1)
}
}
activity 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">
<TextView
android:id="#+id/helloWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="159dp"
android:layout_marginTop="21dp"
android:layout_marginEnd="164dp"
android:layout_marginBottom="286dp"
android:onClick="btnClick"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/helloWorld" />
</androidx.constraintlayout.widget.ConstraintLayout>
My second activity:
package com.anand.expensetracker
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class ViewExpenseList : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_expense_list)
findViewById<TextView>(R.id.textView).text=intent.getStringExtra("Text") +"asdfghj"
}
}
My android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anand.expensetracker"
android:versionCode="1"
android:versionName="#string/versionName">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".ViewExpenseList"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
try change
intent.setClass(this,ViewExpenseList::class.java)
to
val intent = Intent(this, ViewExpenseList::class.java)
Do it like this below
fun btnClick(view: View){
//Get text from view
val myText = helloWorld.text.toString()
//Launch ViewExpenseList Activity
val intent = Intent(this,ViewExpenseList::class.java)
intent.putExtra("Text",myText)
startActivity(intent)
}