0

i m new to kotlin and i am trying to send bitmap. like i in recyclerview card i add an image and after that i have to edit the card so for that how can i send the bitmap there can anyone please help me in this. Thanks in advance.

here is my code:

MainActivity.kt:-

package com.example.itemgetset

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {

    lateinit var activity: Activity
    val userList = ArrayList<ProductInfoGetSet>()
    private lateinit var btnProductAdd: Button
    lateinit var llEmptyView: LinearLayout
    lateinit var llMain: LinearLayout
    lateinit var recyclerView: RecyclerView
    private lateinit var llFab: LinearLayout
    private lateinit var linearLayoutManager: LinearLayoutManager
    private lateinit var gridLayoutManager: GridLayoutManager
    private lateinit var adapter: CustomAdapter

    companion object {
        var handler: Handler = Handler()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        activity = this
        initView()
        onClicks()
        setUpData()

        handler = @SuppressLint("HandlerLeak")
        object : Handler() {
            override fun handleMessage(msg: Message) {
                if (msg.what == 111) {
                    val temp: Temp = msg.obj as Temp

                    if (temp.id == "") {
                        userList.add(
                            ProductInfoGetSet(
                                (userList.size + 1).toString(),
                                temp.image,
                                temp.name,
                                temp.quantity,
                                temp.price,
                                temp.total
                            )
                        )
                        adapter = CustomAdapter(activity, userList)
                        recyclerView.adapter = adapter
                    } else {
                        for (i in userList.indices) {
                            if (userList[i].id == temp.id) {
                                userList[i].id = temp.id
                                userList[i].image = temp.image
                                userList[i].name = temp.name
                                userList[i].quantity = temp.quantity
                                userList[i].price = temp.price
                                userList[i].total = temp.total
                            }
                        }
                        adapter.notifyDataSetChanged()
                    }
                }
                if (userList.size > 0) {
                    llEmptyView.visibility = View.GONE
                    llMain.visibility = View.VISIBLE
                } else {
                    llEmptyView.visibility = View.VISIBLE
                    llMain.visibility = View.GONE
                }
            }
        }
    }




    private fun changeLayoutManager() {
        if (recyclerView.layoutManager == linearLayoutManager) {
            recyclerView.layoutManager = gridLayoutManager
        } else {
            recyclerView.layoutManager = linearLayoutManager
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) Toast.makeText(applicationContext, "Phone Rotated", Toast.LENGTH_SHORT).show()
    }

    private fun initView() {
        btnProductAdd = findViewById(R.id.btn_product_add)
        llFab = findViewById(R.id.ll_fab)
        llEmptyView = findViewById(R.id.llEmptyView)
        llMain = findViewById(R.id.llMain)
        recyclerView = findViewById(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        gridLayoutManager = GridLayoutManager(this, 2)
    }

    private fun onClicks() {
        btnProductAdd.setOnClickListener {
            val intent = Intent(this@MainActivity, AddDetails::class.java)
            intent.putExtra("isFor", "Add")
            startActivity(intent)
        }
        llFab.setOnClickListener {
            val intent = Intent(this@MainActivity, AddDetails::class.java)
            intent.putExtra("isFor", "Add")
            startActivity(intent)
        }
    }

    private fun setUpData() {
        if (userList.size > 0) {
            llEmptyView.visibility = View.GONE
            llMain.visibility = View.VISIBLE
        } else {
            llEmptyView.visibility = View.VISIBLE
            llMain.visibility = View.GONE
        }
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.menu_view) {
            if (userList.size > 0) {
                changeLayoutManager()
            }
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}

CustomeAdapter.kt: -

   package com.example.itemgetset

import android.R.attr.bitmap
import android.app.Activity
import android.app.AlertDialog
import android.content.ContentValues.TAG
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import java.io.ByteArrayOutputStream


@Suppress("UNREACHABLE_CODE")
class CustomAdapter(
    private var activity: Activity,
    private val userList: ArrayList<ProductInfoGetSet>,
) :
    RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val itemview =
            LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
        return ViewHolder(itemview)
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val productInfoGetSet: ProductInfoGetSet = userList[position]

        holder.txtId.text = productInfoGetSet.id
        holder.txtName.text = productInfoGetSet.name
        holder.txtQuantity.text = productInfoGetSet.quantity
        holder.txtPrice.text = productInfoGetSet.price
        holder.txtTotal.text = productInfoGetSet.total
        holder.imgList.setImageBitmap(productInfoGetSet.image)

        val id = userList[position].id
        Log.e(TAG, "List item ID: $id")

        holder.buttonViewOption.setOnClickListener {

            val popup = PopupMenu(activity, holder.buttonViewOption)
            popup.inflate(R.menu.pop_menu)
            popup.setOnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.edit -> {


                        val intent = Intent(activity, AddDetails::class.java)
                        intent.putExtra("isFor", "Update")
                        val bStream = ByteArrayOutputStream()
                        productInfoGetSet.image?.compress(CompressFormat.PNG, 100, bStream)
                        val byteArray = bStream.toByteArray()
                        intent.putExtra("imagebitmap", byteArray)
                        intent.putExtra("id", productInfoGetSet.id)
                        intent.putExtra("name", productInfoGetSet.name)
                        intent.putExtra("quantity", productInfoGetSet.quantity)
                        intent.putExtra("price", productInfoGetSet.price)
                        intent.putExtra("total", productInfoGetSet.total)
                        activity.startActivity(intent)
                    }

                    R.id.delete -> {
                        val builder = AlertDialog.Builder(activity)
                        builder.setTitle("Delete")
                        builder.setMessage("Do you want to delete the item?")
                        builder.setPositiveButton("Yes") { _, _ ->
                            userList.removeAt(position)
                            notifyItemRemoved(position)
                            val snack = Snackbar
                                .make(
                                    holder.linearly,
                                    "Item was removed from the list.",
                                    Snackbar.LENGTH_SHORT
                                )
                            snack.show()
                        }
                        builder.setNegativeButton("No") { _, _ ->
                        }
                        val dialog: AlertDialog = builder.create()
                        dialog.show()
                    }
                }
                false
            }
            popup.show()
        }
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getItemCount(): Int {
        return userList.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val txtName = itemView.findViewById(R.id.txt_name) as TextView
        val txtId = itemView.findViewById(R.id.txt_id) as TextView
        var imgList = itemView.findViewById(R.id.img_list) as ImageView
        val txtQuantity = itemView.findViewById(R.id.txt_quantity) as TextView
        val txtPrice = itemView.findViewById(R.id.txt_price) as TextView
        val txtTotal = itemView.findViewById(R.id.txt_result1) as TextView
        val linearly: LinearLayout = itemView.findViewById(R.id.linearlayout)
        val buttonViewOption = itemView.findViewById<View>(R.id.txt_Options) as TextView
    }
}

AddDetails:-

    package com.example.itemgetset

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


@Suppress("DEPRECATION")
class AddDetails : AppCompatActivity() {

    private lateinit var btnSubmit: Button
    private lateinit var edtName: EditText
    private lateinit var img_add: ImageView
    private var edtQuantity: EditText? = null
    private var edtPrice: EditText? = null
    private var txtResult: TextView? = null
    private var txtTotal: TextView? = null
    private var bitmap: Bitmap? = null

    companion object {
        private const val IMAGE_PICK_CODE = 1000
        private const val PERMISSION_CODE = 1001
    }

    @SuppressLint("SetTextI18n", "ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_item)
        supportActionBar?.hide()
        findViewById()
        onclick()

        edtPrice?.addTextChangedListener(priceWatcher)
        edtQuantity?.addTextChangedListener(textWatcher)

        if (intent.getStringExtra("isFor").equals("Update")) {
            val byteArray = intent.getByteArrayExtra("imagebitmap")
            bitmap = byteArray?.size?.let { BitmapFactory.decodeByteArray(byteArray, 0, it) }
            img_add.setImageBitmap(bitmap)
            edtName.setText(intent.getStringExtra("name"))
            edtQuantity?.setText(intent.getStringExtra("quantity"))
            edtPrice?.setText(intent.getStringExtra("price"))
        }
    }

    private fun findViewById() {
        btnSubmit = findViewById(R.id.btn_submit)
        txtResult = findViewById(R.id.txt_result)
        txtTotal = findViewById(R.id.txt_final)
        edtName = findViewById(R.id.edt_name)
        edtQuantity = findViewById(R.id.edt_quantity)
        edtPrice = findViewById(R.id.edt_price)
        img_add = findViewById(R.id.img_add)
    }

    @SuppressLint("ResourceType")
    private fun onclick() {
        btnSubmit.setOnClickListener {
            when {
                edtName.text.trim().isEmpty() -> {
                    edtName.error = "Please Enter Product Name"
                    Toast.makeText(
                        applicationContext,
                        "Please Enter Product Name",
                        Toast.LENGTH_SHORT
                    )
                        .show()
                }
                edtQuantity?.text?.trim()?.isEmpty()!! -> {
                    edtQuantity?.error = "Please Enter Product Quantity"
                    Toast.makeText(
                        applicationContext,
                        "Please Enter Product Quantity",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                edtPrice?.text?.trim()?.isEmpty()!! -> {
                    edtPrice?.error = "Please Enter Product Price"
                    Toast.makeText(
                        applicationContext,
                        "Please Enter Product Price",
                        Toast.LENGTH_SHORT
                    )
                        .show()
                }
                else -> {
                    Toast.makeText(
                        applicationContext,
                        "Product Added Successfully ",
                        Toast.LENGTH_SHORT
                    ).show()

                    val temp = Temp()
                    temp.image = bitmap
                    temp.name = edtName.text.toString()
                    temp.quantity = edtQuantity?.text.toString()
                    temp.price = edtPrice?.text.toString()
                    temp.total = txtResult?.text.toString()

                    if (intent.getStringExtra("isFor").equals("Update")) {
                        temp.id = intent.getStringExtra("id").toString()
                    }
                    val message: Message = Message.obtain()
                    message.what = 111
                    message.obj = temp
                    MainActivity.handler.sendMessage(message)
                    finish()
                }
            }
        }
        img_add.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) ==
                    PackageManager.PERMISSION_DENIED
                ) {
                    val permissions = arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    requestPermissions(permissions, PERMISSION_CODE)
                } else {
                    pickImageFromGallery()
                }
            } else {
                pickImageFromGallery()
            }
        }
    }

    private val priceWatcher = object : TextWatcher {

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
            val num1: String = edtPrice?.text.toString()
            val mnum1 = num1.toIntOrNull()

            val num2: String = edtQuantity?.text.toString()
            val mnum2 = num2.toIntOrNull()

            val res = mnum2?.let { mnum1?.times(it) }
            Log.e("<><> res1", res.toString())
            txtResult?.text = res.toString()
        }
    }
    private val textWatcher = object : TextWatcher {

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

        override fun afterTextChanged(s: Editable?) {
            val num1: String = edtPrice?.text.toString()
            val mnum1 = num1.toIntOrNull()

            val num2: String = edtQuantity?.text.toString()
            val mnum2 = num2.toIntOrNull()

            val res = mnum2?.let { mnum1?.times(it) }
            Log.e("<><> res1", res.toString())
            txtResult?.text = res.toString()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        when (requestCode) {
            PERMISSION_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED
                ) {
                    pickImageFromGallery()
                } else {
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

    }

    private fun pickImageFromGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        startActivityForResult(intent, IMAGE_PICK_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK && data != null) {
            img_add.setImageURI(data.data)
            val pickedImage: Uri? = data.data

            val filePath = arrayOf(MediaStore.Images.Media.DATA)
            val cursor: Cursor? =
                pickedImage?.let { contentResolver.query(it, filePath, null, null, null) }
            cursor?.moveToFirst()
            val imagePath: String = cursor!!.getString(cursor.getColumnIndex(filePath[0]))
            val options = BitmapFactory.Options()
            options.inPreferredConfig = Bitmap.Config.ARGB_8888
            bitmap = BitmapFactory.decodeFile(imagePath, options)

            cursor.close()
        }
    }
}

Logcat: -

2020-09-14 19:46:21.834 26263-26263/? E/mple.itemgetse: Unknown bits set in runtime_flags: 0x28000
2020-09-14 19:46:43.406 26263-26263/com.example.itemgetset E/<><> res1: null
2020-09-14 19:46:43.754 26263-26263/com.example.itemgetset E/<><> res1: null
2020-09-14 19:46:45.992 26263-26263/com.example.itemgetset E/<><> res1: 32
2020-09-14 19:46:47.908 26263-26263/com.example.itemgetset E/<><> res1: null
2020-09-14 19:46:48.491 26263-26263/com.example.itemgetset E/<><> res1: 64
2020-09-14 19:46:51.002 26263-26263/com.example.itemgetset E/ContentValues: List item ID: 1
2020-09-14 19:46:54.533 26263-26263/com.example.itemgetset E/ContentValues: List item ID: 1
2020-09-14 19:46:55.167 26263-26263/com.example.itemgetset E/ContentValues: List item ID: 1
2020-09-14 19:47:02.993 26263-26263/com.example.itemgetset E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!  (parcel size = 16777976)
2020-09-14 19:47:02.995 26263-26263/com.example.itemgetset E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.itemgetset, PID: 26263
    java.lang.RuntimeException: Failure from system
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1904)
        at android.app.Activity.startActivityForResult(Activity.java:5215)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
        at android.app.Activity.startActivityForResult(Activity.java:5173)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
        at android.app.Activity.startActivity(Activity.java:5544)
        at android.app.Activity.startActivity(Activity.java:5512)
        at com.example.itemgetset.CustomAdapter$onBindViewHolder$1$1.onMenuItemClick(CustomAdapter.kt:69)
        at android.widget.PopupMenu$1.onMenuItemSelected(PopupMenu.java:108)
        at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:787)
        at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:151)
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:934)
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:924)
        at com.android.internal.view.menu.MenuPopup.onItemClick(MenuPopup.java:128)
        at android.widget.AdapterView.performItemClick(AdapterView.java:330)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1257)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3265)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7707)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: android.os.TransactionTooLargeException: data parcel size 16777976 bytes
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:557)
        at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3887)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1898)
        at android.app.Activity.startActivityForResult(Activity.java:5215) 
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676) 
        at android.app.Activity.startActivityForResult(Activity.java:5173) 
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663) 
        at android.app.Activity.startActivity(Activity.java:5544) 
        at android.app.Activity.startActivity(Activity.java:5512) 
        at com.example.itemgetset.CustomAdapter$onBindViewHolder$1$1.onMenuItemClick(CustomAdapter.kt:69) 
        at android.widget.PopupMenu$1.onMenuItemSelected(PopupMenu.java:108) 
        at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:787) 
        at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:151) 
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:934) 
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:924) 
        at com.android.internal.view.menu.MenuPopup.onItemClick(MenuPopup.java:128) 
        at android.widget.AdapterView.performItemClick(AdapterView.java:330) 
        at android.widget.AbsListView.performItemClick(AbsListView.java:1257) 
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3265) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7707) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

From Customadpate to adddetails i have to send the bitmap.

Jay3421
  • 3
  • 5
  • Possible duplicate of: https://stackoverflow.com/questions/11010386/passing-android-bitmap-data-within-activity-using-intent-in-android – Amirhosein Sep 14 '20 at 13:42
  • Save the bitmap in a file in the 1st Activity, pass the Uri via Bundle to the 2nd Activity, load the bitmap from the file using the Uri passed in the 2nd Activity. – Onik Sep 14 '20 at 13:55
  • @Onik can u please give some explanation with code. – Jay3421 Sep 14 '20 at 14:00
  • i got an error in intent in the last line startactivity in that i get an error. – Jay3421 Sep 14 '20 at 14:18

1 Answers1

0

In onActivityResult you receive the picked image Uri, this can then be passed from one activity to the next by converting the Uri to a string then attaching it to the intent with .putExtra(), as seen below:

val intent = Intent(this, Activity::class.java)
    intent.putExtra("Uri", imageUri)
    startActivity(intent)

The information can then be received in the next activity by:

if (intent.getStringExtra("Uri") != null){
        val uri = intent.getStringExtra("Uri")
    }

The Uri will be in string form so all you have to do is convert it back to Uri form.

To convert bitmap to Uri , use the code below:

public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);

}

  • i already sent the bitmap from where it was generate and now i have to sent the bitmap from the second activity to third one. how to convert it into uri in that activity – Jay3421 Sep 15 '20 at 05:07