Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

android - When I try to use my layout id from my mainactivity in my secondactivity.kt page it returns as null and the app crashes

I'm trying to make a quiz app where on the homepage you click the + button and it takes you to a new page where you input the title of the quiz. Once you click the check button it takes you back to the homepage and the new quiz in the form of a button is created there. However, when I try to use the id for the layout from my mainactivity it returns as null and when the app crashes when I click the check button. Does anyone have any idea how I can fix this?

Second activity:

    package com.example.k_ari

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import com.google.android.material.floatingactionbutton.FloatingActionButton

class Page2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_page2)

        val button = Button(this@Page2)
        button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)

        val txtt = findViewById<EditText>(R.id.txt)
        val textmessage: String = txtt.text.toString()
        button.setText(textmessage)

        val message = "New quiz created"
        val toast1= Toast.makeText(applicationContext, message, Toast.LENGTH_LONG)
        toast1.setGravity(Gravity.CENTER, 0,0)
        
        val layout = findViewById<LinearLayout>(R.id.mainlayout)

        val btn = findViewById<FloatingActionButton>(R.id.floatingActionButton2)

        btn.setOnClickListener{

            layout.addView(button)

            toast1.show()

            val intent = Intent(this@Page2, MainActivity::class.java)
            startActivity(intent)
        }
    }
}

Second 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:id="@+id/secondlayout"
    android:orientation="vertical"
    tools:context=".Page2">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#99141414"
        android:backgroundTint="#180030"
        android:gravity="center_horizontal"
        android:padding="20dp"
        android:text="Enter the title:"
        android:textAlignment="center"
        android:textColor="#DADADA"
        android:textSize="35sp"
        android:textStyle="bold"
        android:translationX="50dp"
        android:translationY="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.433"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.112" />

    <EditText
        android:id="@+id/txt"
        android:layout_width="361dp"
        android:layout_height="67dp"
        android:autofillHints="title"
        android:background="#99141414"
        android:backgroundTint="#180030"
        android:hint="title"
        android:inputType="text"
        android:padding="10dp"
        android:textColor="#DADADA"
        android:textColorHint="#9ADCDCDC"
        android:textSize="28sp"
        android:translationX="25dp"
        android:translationY="170dp"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:contentDescription="@string/todo"
        android:focusable="true"
        android:translationX="300dp"
        android:translationY="400dp"
        app:backgroundTint="#180030"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.9"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</LinearLayout>

Main activity:

    package com.example.k_ari

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton

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

        val floatingActionButton = findViewById<FloatingActionButton>(R.id.btn)

        floatingActionButton.setOnClickListener{
            val intent = Intent(this, Page2::class.java)

            startActivity(intent)
        }
    }
}

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:id="@+id/mainlayout"
    android:orientation="vertical"
    android:layout_gravity="center"
    tools:context=".MainActivity">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="56dp"
        android:backgroundTint="#250A43"
        android:backgroundTintMode="add"
        android:clickable="true"
        android:contentDescription="@string/todo"
        android:tint="#250A43"
        android:translationX="280dp"
        android:translationY="580dp"
        app:backgroundTint="#250A43"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.56"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:rippleColor="#FFFFFF"
        app:srcCompat="@android:drawable/ic_input_add"
        android:focusable="true" />
</LinearLayout>

Logcat:

2020-12-23 15:32:03.599 1474-1474/com.example.k_ari E/Toast: setGravity() shouldn't be called on text toasts, the values won't be used 2020-12-23 15:32:05.482 1474-1474/com.example.k_ari E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.k_ari, PID: 1474 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference at com.example.k_ari.Page2$onCreate$1.onClick(Page2.kt:35) at android.view.View.performClick(View.java:8178) at android.view.View.performClickInternal(View.java:8147) at android.view.View.access$3700(View.java:888) at android.view.View$PerformClick.run(View.java:30233) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:246) at android.app.ActivityThread.main(ActivityThread.java:8414) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:596) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot access a View from the Activity that does not hold it.

to handle data between activities like this, you should read about ViewModel and/or SharedPreferences

https://developer.android.com/topic/libraries/architecture/viewmodel

https://developer.android.com/reference/android/content/SharedPreferences


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...