Я новичок в Android Studio, Kotlin и XML. Вчера весь мой код работал нормально. Сегодня один из моих сценариев сломан. Я искал в Интернете ответы, но ни один из них не соответствовал моей ситуации.
Проблема: при каждом запуске приложения я получаю ошибку NullPointerException из кода
productTextView.append("Product: ${it.name}\nOwner: ${it.owner}\nYear Purchased: ${it.yearPurchased}\nPrice: ${it.price}\n\n")
Все идентификатор совпадает, и он работает в других частях приложения.
Вот мой Kotlin код:
package com.example.myapplicationtutorialseries
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener {
startActivity(Intent(this, AddProductActivity::class.java))
}
val preferences = getSharedPreferences("database", Context.MODE_PRIVATE)
val savedName = preferences.getString("savedProductName", "This Value Doesn't Exist.")
//d("Will", "Saved message is: $savedName")
//lastSavedProduct.text = savedName
val products = listOf(
Product("Google Home Mini", "Will", 2019, 69.99),
Product("Galaxy A40", "Will", 2019, 139.50),
Product("Monitor", "Will", 2020, 160.00),
Product("Amazon Fire", "Will", 2019, 25.00)
)
var totalCost = 0.0
products.forEach{
productTextView.append("Product: ${it.name}\nOwner: ${it.owner}\nYear Purchased: ${it.yearPurchased}\nPrice: ${it.price}\n\n")
totalCost += it.price
}
//lastSavedProduct.text = "Total Cost: $totalCost"
}
}
Вот мой 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:id="@+id/ConstraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:id="@+id/productTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:verticalScrollbarPosition="defaultPosition"
android:visibility="visible"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>