How to make a share button in android - Kotlin

Viewed 6675

How can I make a working share button so it's possible to share certain quotes
(It's share's the text from the textview over)

I found the following code online:

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

share_text_1_btn.setOnClickListener {
            val t1 = share_text_1_t.text.toString()
            val shareIntent = Intent()
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.type="text/plain"
            shareIntent.putExtra(Intent.EXTRA_TEXT, t1)
            startActivity(Intent.createChooser(shareIntent,"Share via"))
        }
}

But when I make the setOnClickListener active the app is crashing when I open the fragment
And nothing is red

This are all of my imports:

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import android.view.Menu
import android.widget.Toast
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_blogs.*
import kotlinx.android.synthetic.main.fragment_share.*

import com.example.blogesther.ui.home.HomeFragment
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

This is my xml code:

<?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">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/share_title_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:text="@string/share_title"
                android:textSize="50sp"
                android:textFontWeight="100"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/share_text_1_t"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="25dp"
                android:text="@string/share_text_1"
                app:layout_constraintEnd_toStartOf="@+id/share_text_1_btn"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/share_title_text" />

            <TextView
                android:id="@+id/share_text_2_t"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:text="@string/share_text_2"
                app:layout_constraintEnd_toStartOf="@+id/share_text_2_btn"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/share_text_1_t" />

            <TextView
                android:id="@+id/share_text_3_t"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:text="@string/share_text_3"
                app:layout_constraintEnd_toStartOf="@+id/share_text_3_btn"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/share_text_2_t" />

            <TextView
                android:id="@+id/share_text_4_t"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:text="@string/share_text_4"
                app:layout_constraintEnd_toStartOf="@+id/share_text_4_btn"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/share_text_3_t" />

            <TextView
                android:id="@+id/share_text_5_t"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:text="@string/share_text_5"
                app:layout_constraintEnd_toStartOf="@+id/share_text_5_btn"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/share_text_4_t" />

            <TextView
                android:id="@+id/share_text_6_t"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:text="@string/share_text_6"
                app:layout_constraintEnd_toStartOf="@+id/share_text_6_btn"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/share_text_5_t" />

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/share_text_1_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="50dp"
                android:clickable="true"
                android:scaleX="1"
                android:scaleY="1"
                app:layout_constraintBottom_toBottomOf="@+id/share_text_1_t"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/share_text_1_t"
                app:srcCompat="@drawable/ic_share_white_50dp" />

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/share_text_2_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="50dp"
                android:clickable="true"
                android:scaleX="1"
                android:scaleY="1"
                app:layout_constraintBottom_toBottomOf="@+id/share_text_2_t"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/share_text_2_t"
                app:srcCompat="@drawable/ic_share_white_50dp" />

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/share_text_3_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="50dp"
                android:clickable="true"
                android:scaleX="1"
                android:scaleY="1"
                app:layout_constraintBottom_toBottomOf="@+id/share_text_3_t"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/share_text_3_t"
                app:srcCompat="@drawable/ic_share_white_50dp" />

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/share_text_4_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="50dp"
                android:clickable="true"
                android:scaleX="1"
                android:scaleY="1"
                app:layout_constraintBottom_toBottomOf="@+id/share_text_4_t"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/share_text_4_t"
                app:srcCompat="@drawable/ic_share_white_50dp" />

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/share_text_5_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="50dp"
                android:clickable="true"
                android:scaleX="1"
                android:scaleY="1"
                app:layout_constraintBottom_toBottomOf="@+id/share_text_5_t"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/share_text_5_t"
                app:srcCompat="@drawable/ic_share_white_50dp" />

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/share_text_6_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="50dp"
                android:clickable="true"
                android:scaleX="1"
                android:scaleY="1"
                app:layout_constraintBottom_toBottomOf="@+id/share_text_6_t"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/share_text_6_t"
                app:srcCompat="@drawable/ic_share_white_50dp" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

This is the logcat:

2020-03-17 12:29:03.153 28028-28028/com.example.blogesther E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.blogesther, PID: 28028
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.blogesther/com.example.blogesther.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7063)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.blogesther.MainActivity.onCreate(MainActivity.kt:50)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3101)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7063) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965) 
2 Answers

Try this:

val share_text_1_btn = findViewById<com.google.android.material.floatingactionbutton.FloatingActionButton>(R.id.share_text_1_btn)
share_text_1_btn.setOnClickListener { 
            val intent= Intent()
            intent.action=Intent.ACTION_SEND
            intent.putExtra(Intent.EXTRA_TEXT,"Hey Check out this Great app:")
            intent.type="text/plain"
            startActivity(Intent.createChooser(intent,"Share To:"))
}

Docs About Implicit intent with more than one app to recieve

Also you can do it by using Xml onClick Attribute, just add this to the button and auto generate the function in the error dropdown (alt+enter)

android:onClick="shareIntent"

Then just copy the contents of the click listener to the generated function. Quick and easy solution avoiding most of all the null pointer exceptions you may get.

private lateinit var share_text_1_btn : FloatingActionButton

share_text_1_btn = findViewById(R.id.share_text_1_btn)

share_text_1_btn.setOnClickListener { view ->
            val sendIntent = Intent()
                                sendIntent.action = Intent.ACTION_SEND
                                sendIntent.putExtra(
                                    Intent.EXTRA_TEXT,
                                    "Hey Check out this Great app:"
                                )
                                sendIntent.type = "text/plain"
                                startActivity(sendIntent)
        }
Related