Why does navigation composable call twice? - android-jetpack-navigation

Why does navigation composable call twice? If I set a breakpoint on the Text I will get two stops when the app runs. Thank you for your answers.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
var i: Int = 0
NavHost(navController = navController, startDestination = "s1") {
composable("s1") {
i++
Text("$i")
}
}
}
}
}

Related

how to handle imepadding when textfield is at bottom of view in jetpack compose?

When the basictextfield is at bottom of view and is focused, the basictextfield is moving to the center of screen. How can I stop that? If I remove imePadding(), only half of textfield is visible.
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
var a by remember {
mutableStateOf("")
}
Box(
modifier = Modifier
.fillMaxSize()
.imePadding()
) {
BasicTextField(
value = a, onValueChange = { a = it }, modifier = Modifier.align(
Alignment.BottomCenter
)
)
}
}
}
}

how to solve this startActivityForResult

how to solve this kind of problem starActivityForResult please any budy guide me to solve this
startActivityForResult is deprecated following is new the way. Here is a full source code example
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var tvResult:TextView
private lateinit var btnNext:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvResult = findViewById(R.id.tv_result)
btnNext = findViewById(R.id.btn_next)
btnNext.setOnClickListener {
openActivityForResult(Intent(this,SampleActivity::class.java))
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val mIntent: Intent? = result.data
val mDataString = mIntent?.getStringExtra("result_data")
tvResult.text = mDataString
}
}
private fun openActivityForResult(mIntent: Intent) {
resultLauncher.launch(mIntent)
}
}
SampleActivity
class SampleActivity : AppCompatActivity() {
private lateinit var btnDone: Button
private val sampleData = "Sample Activity Result Data"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
btnDone = findViewById(R.id.btn_done)
btnDone.setOnClickListener{
returnForResult()
}
}
private fun returnForResult(){
val replyIntent = Intent()
replyIntent.putExtra(
"result_data",
sampleData
)
setResult(Activity.RESULT_OK, replyIntent)
finish()
}
}
startActivityForResult is deprecated, meaning that it will no longer be supported going forward. That is why Android Studio is showing you the lines through the code. Instead, review this Stackoverflow post on alternative options:
OnActivityResult method is deprecated, what is the alternative?

Kotlin RecyclerView - Update item to DB

I have a category item in my recyclerView.
There is a TextView and two ImageView as button (Edit button and Delete button).
When I click edit button I want to change TextView to EditText and editbutton change for agreebutton. When I write new text just update my old one.
I show you what I have and almost everything working but don't update my new text and I know code don't look nice and maybe someone can show me how to do it better :)
class CategoryAdapter(private val categoryList: List<Category>, val listener: ClickListener) : RecyclerView.Adapter<CategoryAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(CategoryItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.binding.categoryName.text = categoryList[position].name
holder.binding.categoryEditIv.setOnClickListener {
holder.binding.categoryName.visibility = View.GONE
holder.binding.categoryEditName.visibility = View.VISIBLE
holder.binding.categoryEditName.setText(categoryList[position].name)
holder.binding.categoryEditIv.visibility = View.GONE
holder.binding.categoryAgreeIv.visibility = View.VISIBLE
}
val editTxt = holder.binding.categoryEditName
holder.binding.categoryAgreeIv.setOnClickListener {
val edit = editTxt.text.toString()
listener.editAgreeClickItem(edit)
holder.binding.categoryName.visibility = View.VISIBLE
holder.binding.categoryEditName.visibility = View.GONE
holder.binding.categoryAgreeIv.visibility = View.GONE
holder.binding.categoryEditIv.visibility = View.VISIBLE
}
holder.binding.categoryDeleteIv.setOnClickListener {
listener.deleteClickItem(categoryList[position])
}
}
override fun getItemCount(): Int {
return categoryList.size
}
class MyViewHolder(val binding: CategoryItemBinding) : RecyclerView.ViewHolder(binding.root)
interface ClickListener {
fun editAgreeClickItem(text: String)
fun deleteClickItem(category: Category)
}
}
class MainFragment : Fragment(), NewCategory.NewCategoryCreateListener, CategoryAdapter.ClickListener {
private var _binding: FragmentMainBinding? = null
private val binding
get() = _binding!!
private lateinit var shoppingListViewModel: ShoppingListViewModel
private lateinit var categoryAdapter: CategoryAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shoppingListViewModel = ViewModelProvider(requireActivity())[ShoppingListViewModel::class.java]
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.categoryRV.layoutManager = LinearLayoutManager(requireContext())
shoppingListViewModel.allCategories.observe(viewLifecycleOwner, {
updateCategories(it)
})
binding.addCategory.setOnClickListener {
val newCategory = NewCategory(this)
newCategory.show(childFragmentManager, "NewCategory")
}
}
private fun updateCategories(list: List<Category>) {
if(list.size == 0){
binding.noResult.visibility = View.VISIBLE
binding.categoryRV.visibility = View.GONE
}else{
binding.noResult.visibility = View.GONE
binding.categoryRV.visibility = View.VISIBLE
categoryAdapter = CategoryAdapter(list, this)
binding.categoryRV.adapter = categoryAdapter
}
}
override fun newCategoryCreate(text: String) {
val newCat = Category(text)
shoppingListViewModel.insertCategory(newCat)
}
override fun editAgreeClickItem(text: String) {
val newText = Category(text)
shoppingListViewModel.updateCategory(newText)
}
override fun deleteClickItem(category: Category) {
shoppingListViewModel.deleteCategory(category)
}
}

Problems with SmartToolbar not recreating fragments

I'm having a problem with this SmartToolbar, if I open the app and click on the chat or book icon it opens perfectly and shows the fragments, but if I click on another icon to open another fragment, when I go back to them they don't show more The fragments that should be on the smartToolbar, as shown in the prints below, bug everything! I need to help on this as soon as possible !!!
[Opens normally When I click on another item and go back to it, it no longer opens the SmartToolbar fragmentshere]2
enter image description here
I will send the homeAcitivity code, where is the layout that opens the fragments of the buttonNavigationBar
class HomeActivity : AppCompatActivity() {
var MY_ACCOUNT = 1
var LIBRARY = 2
var HOME = 3
var CHAT = 4
var SETTINGS = 5
private var Content: ConstraintLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar!!.hide()
nav.show(HOME)
nav.setBackgroundColor(Color.TRANSPARENT)
abrirHome()
addOnMeowNavigattionBarIcons()
addOnNotificationInform()
chamarFragments()
}
fun abrirHome() {
val fragment = HomeFragment.newInstance()
addFragment(fragment)
}
fun addOnMeowNavigattionBarIcons() {
nav.add(MeowBottomNavigation.Model(MY_ACCOUNT, R.drawable.ic_baseline_account_circle_24))
nav.add(MeowBottomNavigation.Model(LIBRARY, R.drawable.ic_baseline_menu_book_24))
nav.add(MeowBottomNavigation.Model(HOME, R.drawable.ic_baseline_home_24))
nav.add(MeowBottomNavigation.Model(CHAT, R.drawable.ic_baseline_chat_24))
nav.add(MeowBottomNavigation.Model(SETTINGS, R.drawable.ic_baseline_settings_24))
}
fun addOnNotificationInform() {
nav.setCount(CHAT, "99")
}
fun chamarFragments() {
nav.setOnClickMenuListener {
when (it.id) {
HOME -> {
val fragment = HomeFragment.newInstance()
addFragment(fragment)
}
MY_ACCOUNT -> {
val fragment = MyAccountFragment.newInstance()
addFragment(fragment)
}
LIBRARY -> {
val fragment = LibraryFragment.newInstance()
addFragment(fragment)
}
CHAT -> {
val fragment = ChatFragment.newInstance()
addFragment(fragment)
}
SETTINGS -> {
val fragment = SettingsFragment.newInstance()
addFragment(fragment)
}
}
}
}
private fun addFragment(fragment: Fragment) {
supportFragmentManager
.beginTransaction()
.replace(R.id.parentfragments,fragment,fragment.javaClass.simpleName)
.addToBackStack(null)
.commit()
}
fun sair(view: View){
FirebaseAuth.getInstance().signOut()
val bundle = ActivityOptions.makeSceneTransitionAnimation(this).toBundle()
val intent = Intent(this, login::class.java)
startActivity(intent,bundle)
}
}
This is the code of the fragment Library that has a SmartToolbar that calls two more fragments within it, MyLibrary and Store
class LibraryFragment: Fragment() {
companion object{
fun newInstance():LibraryFragment {
val args = Bundle()
val fragment = LibraryFragment()
fragment.arguments = args
return fragment
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.library_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val adapter = FragmentPagerItemAdapter(
fragmentManager, FragmentPagerItems.with(context)
.add("Minha Bilioteca", MyLibraryFragment::class.java)
.add("Loja", StoreFragment::class.java)
.create())
viewpager.adapter = adapter
viewpagertab.setViewPager(viewpager)
}
}
And this is the MyLibrary fragment that is shown inside the Library that is shown inside HomeActivity
class MyLibraryFragment: Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.mylibrary_fragment, container, false)
}
}

How To Show Interstitial Ads in The getView Function in Kotlin?

I'm a Beginner in Kotlin and I want a way to display Interstitial Ad every time I click on the button tvName, but on the contrary, the app crashes whenever I click on the button. I searched for the solution for a long time.
Here's MainActivity
import ...
#Suppress("UNREACHABLE_CODE")
class MainActivity : AppCompatActivity() {
lateinit var mAdView : AdView
var adapter:ChaptersAdapter?=null
var listOfChapters= ArrayList<Chapters>()
#SuppressLint("WrongViewCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
mAdView = findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
loadChapters()
adapter = ChaptersAdapter(listOfChapters, this)
lvchapters.adapter = adapter
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713")
mInterstitialAd = InterstitialAd(this)
mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())
}
fun loadChapters(){
listOfChapters.add(Chapters(" Chapter 1 ", applicationContext.assets.open("Chapter0.txt").bufferedReader().use {
it.readText()
}
))
listOfChapters.add(Chapters(" Chapter 2 ", applicationContext.assets.open("Chapter1.txt").bufferedReader().use {
it.readText()
}
))
}
class ChaptersAdapter: BaseAdapter {
var context:Context?=null
var listOfChaptersLocal= ArrayList<Chapters>()
constructor(listOfChapters:ArrayList<Chapters>,context:Context){
listOfChaptersLocal=listOfChapters
this.context=context
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val chapters= listOfChaptersLocal[p0]
var inflator= context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chaptersView=inflator.inflate(R.layout.list_chapters,null)
chaptersView.tvName.text= chapters.name!!
chaptersView.**tvName.setOnClickListener** {
// **i want to show the Ads in this time frame** but like this example it didn't work
if (mInterstitialAd.isLoaded) {
mInterstitialAd.show()
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.")
}
val intent =Intent(context,ChapterDetails::class.java)
intent.putExtra("name",chapters.name!!)
intent.putExtra("des",chapters.des!!)
context!!.startActivity(intent)
}
return chaptersView
}
override fun getItem(p0: Int): Any {
return listOfChaptersLocal[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return listOfChaptersLocal.size
}
}
}

Resources