How to pass Image selected in ImageView to another Activity in Android using Kotlin ?
This is the way to select the Image inside the ImageView using internal Storage and I need to pass the image to another activity
fun Loadimage()
{
var intent = Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent,ImageCode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode==ImageCode && data!=null && resultCode== Activity.RESULT_OK)
{
val selectedImage = data.data
val filepath = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(selectedImage,filepath,null,null,null)
cursor.moveToFirst()
val Index = cursor.getColumnIndex(filepath[0])
val Picture = cursor.getString(Index)
cursor.close()
imageView.setImageBitmap(BitmapFactory.decodeFile(Picture))
}
}
You can pass Picture variable to next activity using Intents like below
val intent = Intent(this, NextActivity::class.java)
intent.putExtra("picture", Picture)
startActivity(intent)
Then in NextActivity, in onCreate method, you can get picture using
val Picture = getIntent().getStringExtra("picture")
In the NextActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val postImage = findViewById<ImageView>(R.id.post_image)
myPic = postImage
}
companion object {
lateinit var myPic: ImageView()
}
And in the first Activity:
NextActivity.myPic = Picture
Related
hello I am making note app I have tried other answers to questions like this and it didn't work for me. also I have tried Registering a callback for an Activity Result it was two complicated I didn't get it. when I add item to the recyclerview but when i click that added item it is giving me Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
the point is send data back from secondActivity and update the Recyclerview TextView
this is my code for mainactivity
override fun update(position: Int) {
val note = notes[position]
val intent = Intent(this, Data::class.java)
intent.putExtra(Data.INTENT_PARCELABLE, note)
startActivityForResult(intent, REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode === REQUEST_CODE) {
if (resultCode === Activity.RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
val x: String? = data?.getStringExtra("keyName")
val y: String? = data?.getStringExtra("keyName")
// set text view with string
val tit = findViewById<TextView>(R.id.tit)
val desc= findViewById<TextView>(R.id.desc)
tit.text = x
desc.text = y
}
}
}}
second activity
class Data : AppCompatActivity() {
private lateinit var binding: ActivityDataBinding
companion object {
const val INTENT_PARCELABLE = "object_intent"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDataBinding.inflate(layoutInflater)
setContentView(binding.root)
title = "Edit Note"
val name = intent.getSerializableExtra(INTENT_PARCELABLE) as Notes
binding.tit.setText(name.title)
binding.desc.setText(name.description)
// get the text from the EditText
val a = binding.tit.text.toString()
val b = binding.desc.text.toString()
// put the String to pass back into an Intent and close this activity
val data = Intent()
data.putExtra("keyName", a)
data.putExtra("keyName", b)
setResult(Activity.RESULT_OK, data)
finish()
}
}
Complete beginner, trying this on kotlin. I am trying to capture a photo and save it and then load it on room database. I also need tag the photo and load it according to that. But there is an error like "Caused by: java.lang.NullPointerException: findViewById(R.id.metin) must not be null". How I can solve it? Thanks in advance.
class MainActivity : AppCompatActivity() {
private val cameraRequest = 1888
lateinit var imageView: ImageView
lateinit var textbox : EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var dao_object = ImageDatabase.getInstance(application).MyDao()
textbox = findViewById(R.id.metin)
setContentView(R.layout.activity_main)
if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED
)
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
cameraRequest
)
imageView = findViewById(R.id.imageView)
// var textbox: EditText = findViewById(R.id.text)
val photoButton: Button = findViewById(R.id.capture_button)
photoButton.setOnClickListener {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, cameraRequest)
}
val saveButton: Button= findViewById(R.id.save_button)
saveButton.setOnClickListener{
val takenPhoto: ByteArray = DbBitmapUtility.getBytes(imageView.drawingCache)
dao_object.insertImage(MyDatabase(takenPhoto, textbox.text.toString()))
}
val loadButton: Button= findViewById(R.id.load_button)
loadButton.setOnClickListener {
var displayPhoto: ByteArray = dao_object.getImageByTag(textbox.text.toString())
imageView.setImageBitmap(DbBitmapUtility.getImage(displayPhoto))
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == cameraRequest) {
val photo: Bitmap = data?.extras?.get("data") as Bitmap
imageView.setImageBitmap(photo)
}
}
object DbBitmapUtility {
// convert from bitmap to byte array
fun getBytes(bitmap: Bitmap): ByteArray {
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream)
return stream.toByteArray()
}
// convert from byte array to bitmap
fun getImage(image: ByteArray): Bitmap {
return BitmapFactory.decodeByteArray(image, 0, image.size)
}
}
}
Change the arrangement of the code. Rather than doing the following
textbox = findViewById(R.id.metin)
setContentView(R.layout.activity_main)
do:
setContentView(R.layout.activity_main)
textbox = findViewById(R.id.metin)
setContentView must first be called before you can attempt any manipulation on the activity's view.
You can't use findViewById before you've called setContentView(). There is no View to search in for your view yet at that point.
My application checks whether the new selected image is the same as the previous one so that I don't need to update the cloud data, but newBitmap.sameAs(oldBitmap) always return false even though I pick the same photo.
Piece of my code:
private lateinit var oldBitmap: Bitmap
private lateinit var newBitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_profile)
myProfilePictureUrl = intent.getStringExtra("myProfilePictureUrl")!!
if (myProfilePictureUrl.isNotEmpty()) {
Picasso.get().load(myProfilePictureUrl).into(my_profile_imageView)
}
oldBitmap = (my_profile_imageView.drawable as BitmapDrawable).bitmap //for later comparison
my_profile_imageView.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, RESULT_CODE_PICK_IMAGE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RESULT_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
val inputStream = contentResolver.openInputStream(data!!.data!!)
val bitmap = BitmapFactory.decodeStream(inputStream)
newBitmap = bitmap //for comparison
my_profile_imageView.setImageBitmap(bitmap)
}
}
And when the user click on the "save" button on the action bar will it first check whether they are the same photo:
private fun updateProfile(nickname: String) {
if (this::newBitmap.isInitialized && !newBitmap.sameAs(oldBitmap)) { //here
//upload task code
}
}
THE PROBLEM IS:
!newBitmap.sameAs(oldBitmap) always return false even they are the same photo, may be the problem of PICASSO? Or the way I used to compare is not right. Any help would be appreciated.
I am using image picker inside recyclerview
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvAnimalType.text = items[position].name
holder.image.setOnClickListener{
requestPermissions(it.context as Activity , arrayOf(WRITE_EXTERNAL_STORAGE),1)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
(it.context as Activity).startActivityForResult(intent, 1)
}
}
In Main Activity
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1 -> {/*file front*/
if (resultCode == Activity.RESULT_OK && data != null) {
val selectedImageUri = data.data as Uri
val selectedImageBitmap: Bitmap =
MediaStore.Images.Media.getBitmap(this.contentResolver, selectedImageUri)
}
}
}
}
My question is how to load the selected image in recylerview imageview ?
Try like the following
Pass item position as request_code.
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvAnimalType.text = items[position].name
// here you can get image as bitmap using filepath and set in to your image view
val filepath = items[position].filePath
val bitmapImage = ...........[get bitmap from filepath]
holder.image.setImageBitmap(bitmapImage)
holder.image.setOnClickListener{
requestPermissions(it.context as Activity , arrayOf(WRITE_EXTERNAL_STORAGE),1)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
(it.context as Activity).startActivityForResult(intent, position) // pass position as request code
}
}
And In activity do like the following
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data != null) {
val selectedImageUri = data.data as Uri
val selectedImageBitmap: Bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, selectedImageUri)
// here you can get image file path using URI
val filePathFromURI = ......[get image path using URI]
// then save it to your list data like
items[requestCode].filePath = filePathFromURI // here items is your data set which passed in adapter from your activity you should replace it with yours.
// now you have to notify your adapter that your data set is changed
adapter.notifyDataSetChanged() // replace adapter with yours.
}
}
}
And one important thing you should have a property named filePath in your data class.
I am trying to receive the user-changed value of an Edit Text, and set that value to the first activities Text View. To do this I am employing the functions onBackPressed() and onActivityResult() as shown below. However, it apperast that no data is being sent back to the first activity when then back button is being pressed
Second Activity (sending data back):
class MetaDataActivity : AppCompatActivity() {
val name by lazy {findViewById<EditText>(R.id.editTextName)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_meta_data)
val food = intent.getParcelableExtra("Food") as Food
name.setText(food.name)
}
override fun onBackPressed() {
val intent = Intent()
intent.putExtra("New Name", name.toString())
setResult(Activity.RESULT_OK, intent)
super.onBackPressed()
}
}
First activity (receiving user-changed data):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val food1: ImageButton = findViewById(R.id.imageButtonFood1)
val name1: TextView = findViewById(R.id.textViewName1)
val date1: TextView = findViewById(R.id.textViewDate1)
val pizza = Food(
"Pizza", "www.test.com", "Italy, Tomato",
"1/1/2018", "pizza#mail.com", 5)
date1.text = pizza.date
food1.setOnClickListener()
{
val intent = Intent(this, MetaDataActivity::class.java)
intent.putExtra("Food", pizza)
startActivityForResult(intent, 1)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
val newName = data?.getStringExtra("New Name")
textViewName1.text = newName
}
}
}
Where I'm trying to be able to edit textViewName1's value from the second activity.
I believe I my parameters for the functions are correct, just cannot determine why it is not receiving the user-changed name value?
Thankyou