简体   繁体   中英

Activity to Fragment Communication: When I tried to update text view in fragment from activity am getting null pointer exception


I had an activity and fragment. In which I want to send values from activity to fragment. From activity am calling method in fragment which updates the Text view. But am unable to update the UI am getting null pointer exception.

First I was checking this link link in Case 2: I followed this code able to send values from activity to fragment it works fine. But when I cut this line inside fragment.sendData("Some Text") the button click and give pasted outside the button click its getting null pointer exception.

How fragment.sendData("Some Text") is working inside the button click and not on outside the button click?

I also tried the same concept added the codes and error lines. So can any one help me why am not update the text view in fragment >

Error:

com.example.fragments E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.fragments, PID: 3104
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragments/com.example.fragments.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.fragments.FragmentTwo.displayUI(FragmentTwo.kt:30)
        at com.example.fragments.MainActivity.loadDetailsView(MainActivity.kt:38)
        at com.example.fragments.MainActivity.onCreate(MainActivity.kt:32)
        at android.app.Activity.performCreate(Activity.java:7825)
        at android.app.Activity.performCreate(Activity.java:7814)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)

MainActivity

import android.os.Bundle
import android.util.LogAv
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var detailsView:FragmentTwo
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        loadDetailsView()
    }
    private fun loadDetailsView() {
        detailsView= FragmentTwo()
        supportFragmentManager.beginTransaction().replace(R.id.frameLayout,detailsView).commit()
        detailsView.displayUI("HELLO")
    }  
}

activity_main

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

    <FrameLayout
        android:layout_width="match_parent" android:id="@+id/frameLayout"
        android:layout_height="match_parent"></FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

FragmentTwo

package com.example.fragments

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.row_names.*

class FragmentTwo:Fragment() {
  

        fun displayUI(string: String)
        {
            txtName.setText(string)
        }
  
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view:View
        view=inflater.inflate(R.layout.fragment_two,container,false)
            return view
    }
}

fragment_two.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">

    <TextView
        android:layout_width="415dp"
        android:layout_height="200dp"
        android:text="HAI"
        android:id="@+id/txtName"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.201"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.09" />

</androidx.constraintlayout.widget.ConstraintLayout>

Var txtName is null. Do you set its ID in fragment_two.xml ?

You can not access fragment methods immediately after transaction replace method. You can pass data between them with the new api from AndroidX Fragment 1.3.0-beta01

on text change

Activity.supportFragmentManager.setFragmentResult("some_key", bundle_of_data)

and start listening it from fragment onCreate

Fragment.setFragmentResultListener()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM