fragment.show(fragmentManager,"confirmDelete") error - android-studio

Please help me, I'm new to kotlin programming. Since this morning i have this problem and I can't solve it. I don't understand the error, ... This is this line of code: fragment.show (fragmentManager, "confirmDelete")
enter image description here
MainActivity.kt
import android.app.PendingIntent.getActivity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.graphics.Typeface
import androidx.core.app.ComponentActivity
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.util.Log
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val user = User("ACHAKA", "Eric", 26)
val button1 = findViewById<View>(R.id.button1)
button1.setOnClickListener {
println("Start 2nd activity")
val intent = Intent(this, GreenActivity::class.java)
intent.putExtra("user", user)
startActivity(intent)
}
findViewById<View>(R.id.button2).setOnClickListener{
val fragment = ConfirmDeleteDialogFragment()
fragment.listener = object: ConfirmDeleteDialogFragment.ConfirmDeleteListener {
override fun onDialogPositiveClick() {
Log.i("MainActivity", "onDialogPositiveClick()")
}
override fun onDialogNegativeClick() {
Log.i("MainActivity", "onDialogNegativeClick()")
}
}
fragment.show(fragmentManager,"confirmDelete")
}
}
}
ConfirmDeleteDialogFragment.kt
import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.DialogFragment
class ConfirmDeleteDialogFragment: DialogFragment() {
interface ConfirmDeleteListener {
fun onDialogPositiveClick()
fun onDialogNegativeClick()
}
val TAG = ConfirmDeleteDialogFragment::class.java.simpleName
var listener: ConfirmDeleteListener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
builder.setMessage("Supprimer tout le contenu du téléphone ?")
.setPositiveButton("Oh oui !", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, id: Int) {
Log.i(TAG, "Youpi ! on va tout casser")
listener?.onDialogPositiveClick()
}
})
.setNegativeButton("Euh... Non", DialogInterface.OnClickListener { dialog, id ->
Log.i(TAG, "Bon ben ce sera pour la prochaine fois")
dialog.dismiss()
listener?.onDialogNegativeClick()
})
return builder.create()
}
}
Logcat (error)
:55:54.868 25808-25808/aea.com E/Zygote: v2
2019-12-23 00:55:54.883 25808-25808/aea.com E/Zygote: accessInfo : 0
2019-12-23 00:55:57.485 25808-25808/aea.com E/AndroidRuntime: FATAL EXCEPTION: main
Process: aea.com, PID: 25808
java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.fragment.app.FragmentTransaction androidx.fragment.app.FragmentManager.beginTransaction()' on a null object reference
at androidx.fragment.app.DialogFragment.show(DialogFragment.java:142)
at aea.com.MainActivity$onCreate$2.onClick(MainActivity.kt:42)
at android.view.View.performClick(View.java:6207)
at android.view.View$PerformClick.run(View.java:23639)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

fragmentManager is deprecated:
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*
* #deprecated Use {#link android.support.v4.app.FragmentActivity#getSupportFragmentManager()}
*/
#Deprecated
public FragmentManager getFragmentManager() {
return mFragments.getFragmentManager();
}
So you must use supportFragmentManager instead of fragmentManager.
It will not be compiled if you use fragmentManager (as marked red line, it seems on your screenshot too).

Thank you supportFragmentManager solved my problem well. :)
fragment.show(supportFragmentManager ,"confirmDelete")

Related

How do I fix Unresolved reference: dp?

Hello I have tried to find some help with this I'm using the correct import statement import androidx.compose.ui.Modifier but I get the error message e: /Users/lebo/AndroidStudioProjects/BasicsCodelab/app/src/main/java/com/example/basicscodelab/MainActivity.kt: (36, 68): Unresolved reference: dp
My code looks like this but when I add padding it stops working
package com.example.basicscodelab
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.basicscodelab.ui.theme.BasicsCodelabTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BasicsCodelabTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
#Composable
fun Greeting(name: String) {
Surface(color = MaterialTheme.colorScheme.primary){
Text(text = "Hello $name!", modifier = Modifier.padding(24.dp))
}
}
#Preview(showBackground = true)
#Composable
fun DefaultPreview() {
BasicsCodelabTheme {
Greeting("Android")
}
}
I tried updating my grade version and jetpack compose in the source gradle file and in the app gradle file and nothing has helped. I've been stuck for hours
Import dp like this
import androidx.compose.ui.unit.dp

Background color change automatically in fragment in Android studio?

I have added the blue-alliance spectrum color picker to my simple note app. Now, I can change the background color using the color picker. And the card color also changes according to the selected color. Right now, the problem is whenever I click on the note to edit and click save, then the color of the Material card change automatically to white, and then if I again click on that note to edit right now it automatically set the color as white. Right now, how can I solve this?
EditNoteFragment.kt
package com.example.noteapp.ui.Fragments
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.ViewCompat
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.Navigation
import androidx.navigation.fragment.navArgs
import com.example.noteapp.R
import com.example.noteapp.ViewModel.NotesViewModel
import com.example.noteapp.databinding.BottomsheetlayoutBinding
import com.example.noteapp.databinding.FragmentEditnotesFragmemtBinding
import com.example.noteapp.model.Notes
import com.example.noteapp.ui.Adapter.NotesAdapter
import com.example.noteapp.utils.hideKeyboard
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.transition.MaterialContainerTransform
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.absoluteValue
class EditnotesFragmemt : Fragment() {
val oldNotes by navArgs<EditnotesFragmemtArgs>()
lateinit var binding : FragmentEditnotesFragmemtBinding
val viewModel : NotesViewModel by viewModels()
private var color = -1
private lateinit var result : String
private val job = CoroutineScope(Dispatchers.Main)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentEditnotesFragmemtBinding.inflate(layoutInflater,container,false)
binding.editingedittextnote.setText(oldNotes.data.notes)
binding.editingedittexttitle.setText(oldNotes.data.title)
binding.editFragmentxmlid.setBackgroundColor(oldNotes.data.color)
val animation = MaterialContainerTransform().apply {
drawingViewId = R.id.createFragment
scrimColor = Color.TRANSPARENT
duration = 300L
}
sharedElementEnterTransition=animation
sharedElementReturnTransition=animation
binding.backbutton.setOnClickListener {
requireView().hideKeyboard()
Navigation.findNavController(it).popBackStack()
}
binding.fabcolorpick.setOnClickListener {
val bottomSheetDialog = BottomSheetDialog(
requireContext(),
R.style.BottomSheetDialogTheme
)
val bottomSheetView : View = layoutInflater.inflate(
R.layout.bottomsheetlayout,
null,
)
val bottomSheetBinding = BottomsheetlayoutBinding.bind(bottomSheetView)
bottomSheetBinding.apply {
colorpicker.apply {
setSelectedColor(color)
setOnColorSelectedListener {
value->
color = value
binding.apply {
editFragmentxmlid.setBackgroundColor(color)
toolbarfragmentnotecontent.setBackgroundColor(color)
bottombar.setBackgroundColor(color)
activity?.window?.statusBarColor = color
}
bottomSheetBinding.bottomSheetparent.setCardBackgroundColor(color)
}
}
bottomSheetparent.setCardBackgroundColor(color)
}
bottomSheetView.post{
bottomSheetDialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
}
bottomSheetDialog.setContentView(bottomSheetBinding.root)
bottomSheetDialog.show();
}
binding.btneditdonenotes.setOnClickListener {
updateNotes(it)
}
try {
binding.editingedittextnote.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus)
{
binding.bottombar.visibility = View.VISIBLE
binding.editingedittextnote.setStylesBar(binding.styleBar)
}else{
binding.bottombar.visibility = View.GONE
}
}
}catch (e: Throwable) {
Log.d("TAG", e.stackTraceToString())
}
return binding.root
}
private fun updateNotes(it: View?) {
val title = binding.editingedittexttitle.text.toString()
val notes = binding.editingedittextnote.text.toString()
val data = Notes(
oldNotes.data.id,
title = title,
notes = notes,
color= color,
)
result = "Note Saved"
setFragmentResult(
"key",
bundleOf("bundleKey" to result)
)
viewModel.updateNotes(data)
Toast.makeText(context, "Edit Note Successfully", Toast.LENGTH_SHORT).show()
Navigation.findNavController(it!!).navigate(R.id.action_editnotesFragmemt_to_homeFragment)
}
}
enter image description here
enter image description here
enter image description here
enter image description here

Android Studio Kotlin app "keeps stopping" when I run it

I am just trying to set up a spinner configured as a dropdown menu, but I can't even test my app to see if it works because every time I run it, it immediately crashes. I know that my issue is related to a null object reference at line 21 in my MainActivity.kt file. Here is the problem code:
val spinner: Spinner = findViewById<Spinner>(R.id.locations)
The id of the spinner is locations, so I'm not sure why this is coming back as a null value.
Here is also the full code for the file:
import android.app.Activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Spinner
import android.widget.ArrayAdapter
import android.widget.AdapterView
private var userLocation: Any = ""
private var userDestination: Any = ""
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
val spinner: Spinner = findViewById<Spinner>(R.id.locations)
val locationsAdapter: ArrayAdapter<CharSequence> = ArrayAdapter.createFromResource(
this,
R.array.rooms,
android.R.layout.simple_spinner_item
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
}
}
class SpinnerActivity : Activity(), AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id:Long) {
userLocation = parent.getItemAtPosition(pos)
val spinner: Spinner = findViewById(R.id.locations)
spinner.onItemSelectedListener = this
}
override fun onNothingSelected(parent: AdapterView<*>) = Unit
}
Declare spinner global for MainActivity:
private lateinit var spinner: Spinner
On the method onCreate initialise the spinner and set its adapter, I would recommend you to set the array adapter as follows:
spinner = findViewById<Spinner>(R.id.locations)
spinner.adapter = ArrayAdapter(this, R.layout.drop_down_generic_item, resources.getStringArray(R.array.rooms))
I don't really understand the SpinnerActivity you showed in the question, sorry. But in MainActivity you can set the spinner.onItemSelectedLister() as follows:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, position: Int, p3: Long) {
val selectedRoom = adapterView?.getItemAtPosition(position)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
I don't want to confuse you, but have a look at a TextInputLayout with an AutoCompleteTextView, just as a hint. :D

How to add onClickListener on images in recyclerView?

I am trying to attach onclick listener on images in this code, using Glide framework but I'm not able to find a solution for that. Can someone help with this?
Images are showing in emulator already.
Thanks in advance
package com.example.andoridlifecycle.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.andoridlifecycle.R
import kotlinx.android.synthetic.main.item_custom_row.view.*
class ItemAdapter(private val context: Context, private val urls: ArrayList<String>) :
RecyclerView.Adapter<ItemAdapter.ViewHolder>() {
/**
* Inflates the custom view which is designed in xml layout file
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(context).inflate(
R.layout.item_custom_row,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Array with urls
val url = urls[position]
Glide.with(context)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.placeholder)
.into(holder.imageView)
}
// Gets the number of items in the list
override fun getItemCount(): Int {
return urls.size
}
// A ViewHolder describes an item view and metadata about its place within the RecyclerView.
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val imageView: ImageView = view.iv_image
}
}
I'm Java Developer so I cannot code with Kotlin but I'll show you how to set OnClickListener on your imageView. For using OnclickListener on imageView no need for Glide Library.
Just add the below lines in your onBindViewHolder
holder.imageView.setOnClickListener(view -> {
Toast.makeText(context, "this is number: "+position+" Image Selected", Toast.LENGTH_SHORT).show();
// or your code for imageView
});
Your new code looks like the below:-
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Array with urls
val url = urls[position]
//code for onClick on image
holder.imageView.setOnClickListener(view -> {
Toast.makeText(context, "this is number: "+position+" Image Selected", Toast.LENGTH_SHORT).show();
// or your code for imageView
});
Glide.with(context)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.placeholder)
.into(holder.imageView)
}
Make sure to change JAVA to Kotlin in my code. If you any problem is causing, Let me know

Why get request http dont working in Kotlin?

Hi guys i have problem with getting http request if i write "http://10.0.1.42:8080/state"(this is my ip) on emulator chrome this working, but if i want getting http request aplication close. Can someone help me?
import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
import java.util.*
class kmnActivity : AppCompatActivity() {
val EXTRA_TEXT = "com.example.application.example.EXTRA_TEXT"
var uuid = UUID.randomUUID().toString()
var response = "nothing"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kmn)
val textView = findViewById<TextView>(R.id.textView3)
val kamenButton = findViewById<ImageButton>(R.id.kamen)
val papierButton = findViewById<ImageButton>(R.id.papier)
val nozniceButton = findViewById<ImageButton>(R.id.noznice)
kamenButton.setOnClickListener {
get_state()
textView.setText(response)
// openRollActivity()
}
papierButton.setOnClickListener {
openRollActivity()
}
nozniceButton.setOnClickListener {
openRollActivity()
}
}
fun get_state(){
val client = HttpClient()
runBlocking {
response = client.get<String>("http://10.0.1.42:8080/state") //Here not working
}
client.close()
}
fun openRollActivity() {
val intent = Intent(this#kmnActivity, rollActivity::class.java)
intent.putExtra("id", uuid)
startActivity(intent)
}
}
Or if somebody have better way, He can said me. Thanks for your help.
android:usesCleartextTraffic="true"
Add this code AndroidManifest.xml file
could refer to this https://medium.com/#son.rommer/fix-cleartext-traffic-error-in-android-9-pie-2f4e9e2235e6 u will get the clear idea over it
another possible fix will be
instead of HTTP can use https

Resources