I want to add a spinning top to the navigation drawer.I want it to look like this:
I couldn't find how and where to add.I always get this error when I try to find id
my spinner layout
<Spinner
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/qualitySpinner"
android:layout_marginLeft="50dp"
android:entries="#array/mQuality"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and my items
<item
android:id="#+id/right_menu_spinner"
android:icon="#drawable/icon_default"
android:title="Quality"
app:actionLayout="#layout/spinner_layout"/>
and my fragment code
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val array = arrayOf("deneme","deneme")
val denemeSp : Spinner = view.findViewById(R.id.qualitySpinner)
denemeSp.adapter = ArrayAdapter(view.context,android.R.layout.simple_spinner_item,array)
denemeSp.setOnItemSelectedListener(this)
}
but when it works it gives the following error:
2020-06-07 23:12:41.292 6872-6872/com.enesseval.moviedeneme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.enesseval.moviedeneme, PID: 6872
java.lang.IllegalStateException: view.findViewById(R.id.qualitySpinner) must not be null
at com.enesseval.moviedeneme.view.MoviesFragment.onViewCreated(MoviesFragment.kt:57)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2722)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1188)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
at android.app.Activity.performStart(Activity.java:7825)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
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)
2020-06-07 23:12:41.308 6872-6872/com.enesseval.moviedeneme I/Process: Sending signal. PID: 6872 SIG: 9
Your menu item should be something like (I edited the stock android studio Navigation project template for illustative purposes) :
<item
android:id="#+id/right_menu_spinner"
android:icon="#drawable/icon_default"
android:title="Quality"
app:actionViewClass="androidx.appcompat.widget.AppCompatSpinner"/>
And access in your Activity, not fragment :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setup code ...
// Access Navigation header and menu
val navView: NavigationView = findViewById(R.id.nav_view)
(navView.menu.findItem(R.id.right_menu_spinner).actionView as Spinner).run {
adapter = ArrayAdapter(this#MainActivity, android.R.layout.simple_list_item_1, arrayOf("High", "Medium", "Low"))
}
}
}
Result :
Add you Spinner in XML:
<RelativeLayout
android:id="#+id/tilLanguage"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="35dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="35dp"
android:layout_weight=".28"
app:layout_constraintTop_toBottomOf="#+id/tvAlmostThere"
android:background="#drawable/spinner_background"
android:orientation="horizontal">
<Spinner
android:id="#+id/etLanguage"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginStart="5dp"
android:background="#android:color/transparent"
android:gravity="center"
android:spinnerMode="dropdown"
android:focusable="true"
android:textColorHint="#color/textColorPrimary"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:src="#drawable/dropdown" />
</RelativeLayout>
Add Strings for Values:
<item>Select Language:</item>
<item>English</item>
<item>French</item>
</string-array>
Then Add it in your Navigation Drawer:
Language = (Spinner) root.findViewById(R.id.etLanguage);
ArrayAdapter<CharSequence> status_adapter = ArrayAdapter.createFromResource(getActivity(), R.array.language_arrays, R.layout._spinner_item);
language_adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
Language .setAdapter(status_adapter);```
Related
so i want to intent from settings activity into edit profile activity, but when i clicked the edit profile button in settings activity, suddenly my application is force closed. for the information, i have profile fragment attached to main activity. on profile fragment, it has button that intent to settings activity. but, in settings activity it also has button that intent to edit profile activity. the problem is i can't intent from the settings activity to edit profile activity.
here's the SettingsActivity.kt
class SettingsActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var settingsBinding: ActivitySettingsBinding
private var refUsers : DatabaseReference? = null
private var firebaseUser : FirebaseUser? = null
companion object{
fun getLaunchService (from: Context) = Intent(from, SettingsActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsBinding = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(settingsBinding.root)
supportActionBar?.hide()
settingsBinding.cvSettingsLogOut.setOnClickListener(this)
settingsBinding.btnEditProfile.setOnClickListener(this)
userInfo()
}
private fun userInfo(){
firebaseUser = FirebaseAuth.getInstance().currentUser
refUsers = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser!!.uid)
refUsers!!.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
override fun onDataChange(snapshot: DataSnapshot) {
for (p0 in snapshot.children){
val userName = snapshot.child("userName").value.toString()
val email = snapshot.child("email").value.toString()
val profileImage = snapshot.child("profile_image").value.toString()
settingsBinding.tvProfileUsername.text = userName
settingsBinding.tvProfileEmail.text = email
Glide.with(this#SettingsActivity).load(profileImage).into(settingsBinding.ivProfileSettings)
}
}
})
}
override fun onClick(v: View) {
when(v.id){
R.id.btnEditProfile -> startActivity(EditProfileActivity.getLaunchService(this))
R.id.cvSettingsLogOut -> logOut()
}
}
private fun logOut() {
/* Create a new instance of the AlertDialog class. */
var alertDialog: AlertDialog? = null
val builder = AlertDialog.Builder(this)
/* Inflate the layout file for the dialog box. */
val view = DialogConfirmLogoutBinding.inflate(layoutInflater)
/* Set the view of the dialog box. */
builder.setView(view.root)
view.btnConfirmCancel.setOnClickListener {
alertDialog?.dismiss()
}
view.btnConfirmYes.setOnClickListener {
alertDialog?.dismiss()
FirebaseAuth.getInstance().signOut()
val intent = Intent(this, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
/* Showing the dialog box. */
alertDialog = builder.create()
alertDialog.show()
}
}
my EditProfileAcitivity.kt
class EditProfileActivity : AppCompatActivity() {
private lateinit var editProfileBinding: ActivityEditProfileBinding
companion object{
fun getLaunchService (from: Context) = Intent(from, EditProfileActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
editProfileBinding = ActivityEditProfileBinding.inflate(layoutInflater)
setContentView(editProfileBinding.root)
supportActionBar?.hide()
}
}
here's the layout for EditProfile 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"
tools:context=".activity.EditProfileActivity">
<ImageView
android:id="#+id/ivBackEditProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_20dp"
android:src="#drawable/ic_back"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_20dp"
android:fontFamily="#font/poppins_medium"
android:text="#string/edit_profile"
android:textColor="#color/black"
android:textSize="#dimen/_18sp"
app:layout_constraintBottom_toBottomOf="#+id/ivBackEditProfile"
app:layout_constraintStart_toEndOf="#+id/ivBackEditProfile"
app:layout_constraintTop_toTopOf="#+id/ivBackEditProfile" />
<LinearLayout
android:id="#+id/llAddEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_20dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/ivBackEditProfile">
<ImageView
android:id="#+id/ivAddBgEditProfile"
android:layout_width="match_parent"
android:layout_height="#dimen/_150dp"
android:scaleType="fitXY"
android:src="#drawable/bg_addbgeditprofile">
</ImageView>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/ivAddProfilePhoto"
android:layout_width="#dimen/_100dp"
android:layout_height="#dimen/_100dp"
android:layout_marginStart="#dimen/_20dp"
android:scaleType="fitCenter"
android:src="#drawable/bg_addprofilephtoeditpro" />
</LinearLayout>
<EditText
android:id="#+id/etNameEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="#dimen/_25dp"
android:background="#drawable/bg_et_editprofile"
android:hint="Name"
android:layout_marginTop="#dimen/_20dp"
android:inputType="textPersonName"
android:maxLines="1"
android:maxLength="15"
android:padding="#dimen/_15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/llAddEditProfile" />
<EditText
android:id="#+id/etBioEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_et_editprofile"
android:hint="Bio"
android:layout_marginHorizontal="#dimen/_25dp"
android:maxLines="3"
android:inputType="textMultiLine"
android:layout_marginTop="#dimen/_20dp"
android:maxLength="100"
android:padding="#dimen/_15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/etNameEditProfile" />
<EditText
android:id="#+id/etLinkEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_et_editprofile"
android:hint="Link"
android:layout_marginHorizontal="#dimen/_25dp"
android:maxLines="1"
android:inputType="textUri"
android:layout_marginTop="#dimen/_20dp"
android:maxLength="15"
android:padding="#dimen/_15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/etBioEditProfile" />
<Button
android:id="#+id/btnSaveEditProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="#dimen/_25dp"
android:layout_marginEnd="#dimen/_25dp"
android:background="#drawable/bg_btnaddpost"
android:fontFamily="#font/poppins_semibold"
android:paddingHorizontal="#dimen/_50dp"
android:text="Save"
android:textAllCaps="false"
android:textSize="#dimen/_18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
this is the log error that i got cuz of sudden force close on my app while intent to editprofile activity. if u know what's goin on with my code, pls help me. Thanks.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.isjieman.ocion, PID: 5334
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.isjieman.ocion/com.isjieman.ocion.activity.EditProfileActivity}: android.view.InflateException: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Error inflating class <unknown>
Caused by: android.view.InflateException: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Error inflating class <unknown>
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:852)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1124)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at com.isjieman.ocion.databinding.ActivityEditProfileBinding.inflate(ActivityEditProfileBinding.java:80)
at com.isjieman.ocion.databinding.ActivityEditProfileBinding.inflate(ActivityEditProfileBinding.java:74)
at com.isjieman.ocion.activity.EditProfileActivity.onCreate(EditProfileActivity.kt:20)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalArgumentException: ScaleType FIT_CENTER not supported.
at de.hdodenhof.circleimageview.CircleImageView.setScaleType(CircleImageView.java:134)
at android.widget.ImageView.<init>(ImageView.java:223)
at android.widget.ImageView.<init>(ImageView.java:190)
at de.hdodenhof.circleimageview.CircleImageView.<init>(CircleImageView.java:98)
at de.hdodenhof.circleimageview.CircleImageView.<init>(CircleImageView.java:94)
... 29 more
You are getting because you have set android:scaleType="fitCenter" in below code and CircleImageView not supporting fitCenter
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/ivAddProfilePhoto"
android:layout_width="#dimen/_100dp"
android:layout_height="#dimen/_100dp"
android:layout_marginStart="#dimen/_20dp"
android:scaleType="fitCenter"
android:src="#drawable/bg_addprofilephtoeditpro" />
kindly read limitation of library first
https://github.com/hdodenhof/CircleImageView#limitations
I have a recycler view and a XML file for the recycler view. I have used the recycler views inside the fragment layout. I want to access the textview id from the fragment activity for using fragment transactions.
var titleTextView = view.findViewById<TextView>(R.id.tvTitle)
val subjectFragment = SubjectFragment()
println(titleTextView.text)
the above code provides a null pointer exception
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.samachar, PID: 7038
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at com.example.samachar.NewsFragment.onViewCreated(NewsFragment.kt:86)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 7038 SIG: 9
I want to use the fragment manager to use the transactions and switch layouts
// var fragment = parentFragmentManager?.beginTransaction()
// fragment?.replace(R.id.newsFrameLayout, subjectFragment)
// fragment?.commit()
but I cannot seem to access the textview id from the fragment class.
<?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/newsItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingHorizontal="16dp"
android:paddingVertical="12dp">
<TextView
android:id="#+id/tvTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/title_eg"
android:textColor="#color/purple_200"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvDescription"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/description_eg"
android:textSize="12sp"
android:textColor="#color/black"
android:maxLines="2"
android:justificationMode="inter_word"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvTitle" />
<TextView
android:id="#+id/tvCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/teal_700"
android:padding="2dp"
android:text="#string/category_eg"
android:textColor="#color/white"
android:textSize="10sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvDescription" />
<TextView
android:id="#+id/tvPublishedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub_date_eg"
android:textSize="10sp"
app:layout_constraintBottom_toBottomOf="#+id/tvCategory"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvDescription" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the xml layout used in the recycler view of the app
EDIT***
Solved it by using the onClickListener on textview in the adapter class onBindViewHolder function and used activity context for calling the supportFragmentManager.
You should have some item click listner in your adapter class this way:
interface ItemClickListener {
fun onClick(dataYouWantInFragment:String) // or of any type
}
Then you should ask for the interface implementation of your fragment in your adapter class like below:
class YourRVAdapter(private val listener:ItemClickListener) {
override fun onBindViewHolder(holder:YourViewHolder,position:Int) {
holder.bindData(dataForPosition(position),listener)
}
class YourViewHolder(private val view:View) : RecyclerView.ViewHolder(view) {
private val tvTitle = view.findViewById<TextView>(R.id.tvTitle)
fun bindData(data:String,listener:ItemClickListener) {
tvTitle.text = data
view.setOnClickListener {
listener.onClick(tvTitle.text.toString())// pass the data you want in fragment
}
}
}
// If you used binding,
class YourViewHolder(private val binding:YourBinding) : RecyclerView.ViewHolder(binding.root) {
fun bindData(data:String,listener:ItemClickListener) {
binding.tvTitle.text = data
binding.root.setOnClickListener {
listener.onClick(tvTitle.text.toString())// pass the data you want in fragment
}
}
}
}
in your fragment class, you should implement that listener interface like below:
class YourFragmentClass() : ItemClickListener {
override fun onCreateView(...) {
..
recyclerView.adapter = YourRVAdapter(this)
..
}
override fun onClick(dataYouWant:String) {
// use this data for your fragment transaction
childFragmentManager.beginTransaction().add/replace()....commit()
}
}
Now, you should be able to get the onClick() callback in your fragment class with you desired data when you click on a recycler view item.
When you use a recyclerview there isn't a unique tvtitle id available. For each item in the recyclerview there is a tvtitle.
Although you can aceess each of them from the recyclerview adapter.
If you want to access any item of recyclerview then you need to create a event at onBindViewHolder .
Use interface or lambda funtion for getting every view inside activity or fragment.
if you want views when click event happen then implement clickListener.
I`m just started learning Kotlin, and i have a problem with one of the buttons.
In MainActivity i have a button, that shows a popup with EditText and Button. In that popup user enters a city, and variable CITY changes according to user input after pressing a button.
In function cityChange im trying to replace my variable CITY with a text that user enters in EditText named editText. But when user taps on button, my program crashes with a NullPointerException. Can someone explain, or show how to fix that problem?
Exception log
FATAL EXCEPTION: main
Process: com.example.weatherapp, PID: 16567
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:7192)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7192)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: kotlin.KotlinNullPointerException
at com.example.weatherapp.MainActivity.cityChange(MainActivity.kt:48)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7192)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
I/Process: Sending signal. PID: 16567 SIG: 9
MainActivity.kt
class MainActivity : AppCompatActivity() {
var CITY: String = "kyiv, ua"
val API: String = "7c45088f48678b739d4d8409a2d9d03e"
private var btn: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val menuActivity = findViewById<Button>(R.id.activityButton)
menuActivity.setOnClickListener(){
val Intent = Intent(this, MenuActivity::class.java)
startActivity(Intent)
}
var dialog = CustomDialogFragment()
val clkBtn = findViewById<Button>(R.id.cityChange)
clkBtn.setOnClickListener {
dialog.show(supportFragmentManager, "customDialog")
}
}
fun cityChange(view: View){
btn = findViewById(R.id.changingButton)
btn!!.setOnClickListener{
CITY = editText.text.toString()
}
}
change_city.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="200dp"
android:background="#color/colorPrimaryDark"
android:padding="5dp"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City Change"
android:textStyle="bold"
android:textColor="#color/white"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:gravity="center"
android:inputType="textPersonName"
android:text="" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="225dp"
android:orientation="vertical">
<Button
android:onClick="cityChange"
android:id="#+id/changingButton"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_gravity="bottom"
android:background="#color/bluelight"
android:text="Submit" />
</LinearLayout>
</LinearLayout>
Just simply do this
// Variable declaration
private var btn: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val menuActivity = findViewById<Button>(R.id.activityButton)
menuActivity.setOnClickListener(){
val Intent = Intent(this, MenuActivity::class.java)
startActivity(Intent)
}
var dialog = CustomDialogFragment()
btn= findViewById<Button>(R.id.changingButton)
clkBtn.setOnClickListener {
dialog.show(supportFragmentManager, "customDialog")
}
}
Or Else You have to Change
This
val clkBtn = findViewById<Button>(R.id.cityChange)
To
val clkBtn = findViewById<Button>(R.id.changingButton)
Hope this will helpful to you.
wrong ID
from this
val clkBtn = findViewById<Button>(R.id.cityChange)
to
val clkBtn = findViewById<Button>(R.id.changingButton)
in your XML the button id is "changingButton" not "cityChange"
and don't use onClick and setOnClickListener together, just choose one
I am new to kotlin in android.
I followed this "https://codelabs.developers.google.com/codelabs/camerax-getting-started/#9" tutorial but got following error.
the app is built successfully however, app stops and the message on my phone says "app keeps stopping".
I also followed the tutorial in here https://developer.android.com/training/camera
but no luck, it starts but do not capture any image. All i wanna do is to get frame from realtime video stream and work on frames. Any help.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 28612
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to android.view.TextureView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to android.view.TextureView
at com.example.myapplication.MainActivity.onCreate(MainActivity.kt:40)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
My xml is
<?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">
<TextView
android:id="#+id/view_finder"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<ImageButton
android:id="#+id/capture_button"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_margin="24dp"
app:srcCompat="#android:drawable/ic_menu_camera"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
and my main is
// This is an arbitrary number we are using to keep track of the permission
// request. Where an app has multiple context for requesting permission,
// this can help differentiate the different contexts.
private const val REQUEST_CODE_PERMISSIONS = 10
// This is an array of all the permission specified in the manifest.
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Add this at the end of onCreate function
viewFinder = findViewById(R.id.view_finder)
// Request camera permissions
if (allPermissionsGranted()) {
viewFinder.post { startCamera() }
} else {
ActivityCompat.requestPermissions(
this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}
// Every time the provided texture view changes, recompute layout
viewFinder.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
updateTransform()
}
}
// Add this after onCreate
private val executor = Executors.newSingleThreadExecutor()
private lateinit var viewFinder: TextureView
private fun startCamera() {
...
}
.....
}
}
Your view_finder view in the layout of MainActivity is AppCompatTextView and you are trying to assign it into a TextureView here:
viewFinder = findViewById(R.id.view_finder)
Change one of them to match the other.
<?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">
<TextureView //changed from textView to TextureView
android:id="#+id/view_finder"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/capture_button"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_margin="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#android:drawable/ic_menu_camera" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am a beginner at programming. I have an error message when I start my app and do not know what to do with the code. Can someone help me please.
Here is my code:
Activity :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val items = ArrayList<String>()
items.add("Test1")
items.add("Test2")
items.add("Test3")
listview1.adapter = Adapter1(this, items)
val transaction1 = supportFragmentManager.beginTransaction()
fragment1Button1.setOnClickListener{
transaction1.replace(R.id.fragment1Platz,Fragment1())
transaction1.commit()
}
}
}
Fragment :
class Fragment1 : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_fragment1, container, false)
}
}
Adapter:
class Adapter1 (context : Context, items : ArrayList<String>) : BaseAdapter() {
private val context: Context = context
private val items: ArrayList<String> = items
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val listeneintrag = LayoutInflater.from(context).inflate(R.layout.adapter1_layout,parent, false)
listeneintrag.findViewById<TextView>(R.id.adapter_textfeld1).text = items.get(position)
return listeneintrag
}
override fun getItem(position: Int): String {
return items.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return items.size
}
}
Error stacktrace:
2020-02-01 13:37:17.972 10729-10729/? E/AndroidRuntime: FATAL
EXCEPTION: main Process: strauss2002.yannick.fragmentetest, PID: 10729
java.lang.RuntimeException: Unable to start activity
ComponentInfo{strauss2002.yannick.fragmentetest/strauss2002.yannick.fragmentetest.MainActivity}:
java.lang.IllegalStateException: listview1 must not be null at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106) at
android.os.Looper.loop(Looper.java:164) at
android.app.ActivityThread.main(ActivityThread.java:6494) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused
by: java.lang.IllegalStateException: listview1 must not be null at
strauss2002.yannick.fragmentetest.MainActivity.onCreate(MainActivity.kt:29)
at android.app.Activity.performCreate(Activity.java:7009) at
android.app.Activity.performCreate(Activity.java:7000) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106) at
android.os.Looper.loop(Looper.java:164) at
android.app.ActivityThread.main(ActivityThread.java:6494) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here is my updated Main Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listview1=findViewById<ListView>(R.id.listview1)
val items = ArrayList<String>()
items.add("Test1")
items.add("Test2")
items.add("Test3")
listview1.adapter = Adapter1(this, items)
val transaction1 = supportFragmentManager.beginTransaction()
fragment1Button1.setOnClickListener{
transaction1.replace(R.id.fragment1Platz,Fragment1())
transaction1.commit()
}
}
}
And here is the new error message:
2020-02-02 11:15:15.935 12764-12764/strauss2002.yannick.fragmentetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: straus
s2002.yannick.fragmentetest, PID: 12764
java.lang.RuntimeException: Unable to start activity ComponentInfo{strauss2002.yannick.fragmentetest/strauss2002.yannick.fragmentetest.MainActivity}: java.lang.IllegalStateException: listview1 must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalStateException: listview1 must not be null
at strauss2002.yannick.fragmentetest.MainActivity.onCreate(MainActivity.kt:28)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here is the xml of the 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:id="#+id/fragment1Platz"
android:layout_width="410dp"
android:layout_height="495dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
</FrameLayout>
<Button
android:id="#+id/fragment1Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="Öffne Fragment 1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.529"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the xml of the fragment_fragment1:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview1"
android:layout_width="match_parent"
android:layout_height="322dp"/>
</FrameLayout>
Here is the xml of the adapter1_layout:
<?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/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/adapter_textfeld1"
android:layout_width="137dp"
android:layout_height="53dp"
android:layout_marginTop="128dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Because you didn't call findViewById for listview1.
Add listview1=findViewById(R.id.yourListViewIdInXml); just after setContentView method of oncreate
Or if you are using kotlin synthetic then make sure that listview1 resides in activity_main.xml file
Update
The problem persists because you are calling findViewById on an id(listview1) which is not available in activity_main.xml. Note that in case of activities, when you call findViewById it searches id in the layout file which is passed in setContentView method, that is activity_main.xml in your case. So when you called findViewById<ListView>(R.id.listview1) it searches listview1 in activity_main.xml, but as we know that there is no view available in activity_main.xml which has id=listview1, so findViewById simply returns null and that's why you are getting this error. So to get rid of this exception change:
val listview1=findViewById<ListView>(R.id.listview1)
to this:
val listview1=findViewById<ListView>(R.id.kontaktliste)
I had the same issue. I resolved just putting the setContentView(activity_layout) in the onResume method.
I don't know why this error hasn't occurred in other activities with a listView
The reason you are getting Null Exception is that you are trying to access listView1 before the fragment view is completely created which means listView1 doesn't exist yet.
So you have to move that part of the code you have in your MainActivity to the onCreateView method of your fragment like so:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_fragment1, container, false)
val items = ArrayList<String>()
items.add("Test1")
items.add("Test2")
items.add("Test3")
//THIS IS HOW YOU REFERENCE YOU VIEWS IN A FRAGMENT IN KOTLIN
rootView.listview1.adapter = Adapter1(this, items)
return rootView
}
And pay attention that in a fragment, you have to reference the views through the inflated rootView for your fragment.