问:
findNavController() in Fragment gives "does not have a NavController set" error
I'm new to Android Development and I'm stuck on this error for days now..

I have an activity with a FragmentContainerView and BottomNavigationView. The BottomNavigationView has 2 fragments to switch from: ScanFragment and ProfileFragment.

When I switch to the ProfileFragment and press on a button (payMethodButton) with this code:

```<code> val payMethodButton = view.findViewById<TableRow>(R.id.trMyPayMethod)
        payMethodButton.setOnClickListener {

    findNavController().navigate(
       R.id.action_profileFragment_to_bankFragment
    )
}
</code>```

the application will crash with this error message: View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set

What am I doing wrong? Why is there no NavController?

DashboardActivity.kt

```<code>package com.app.app.activities.dashboard

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.app.app.R
import com.app.app.activities.BaseActivity
import com.app.app.fragments.ProfileFragment
import com.app.app.fragments.ScanFragment

class DashboardActivity : BaseActivity() {

    private val scanFragment: Fragment = ScanFragment()
    private val profileFragment: Fragment = ProfileFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)

        val navigation = findViewById<View>(R.id.bottomNavigationView) as BottomNavigationView
        navigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_scan -> replaceFragment(scanFragment)
                R.id.navigation_profile -> replaceFragment(profileFragment)
            }
            true
        }

    }

    private fun replaceFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.dashboardNavHostFragment, fragment)
        transaction.commit()
    }

}
</code>```

activity_dashboard.xml

```<code><?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/dashboardNavHostFragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/dashboard_nav" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/bottom_menu_bar"
        app:itemIconTint="@drawable/bottom_nav_selector"
        app:itemTextAppearanceActive="@style/BottomNavigationView.Active"
        app:itemTextAppearanceInactive="@style/BottomNavigationView"
        app:itemTextColor="@drawable/bottom_nav_selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_dash_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

ProfileFragment.kt

```<code>package com.app.app.fragments

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.TableRow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavHost
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.app.app.BuildConfig
import com.app.app.R
import com.app.app.activities.account.login.LoginActivity

class ProfileFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_profile, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        (activity as AppCompatActivity).supportActionBar?.title = "Profile"

        val payMethodButton = view.findViewById<Button>(R.id.btPayMethod)
        payMethodButton.setOnClickListener {

            findNavController().navigate(
                R.id.action_profileFragment_to_bankFragment
            )
        }

    }

}
</code>```

dashboard_nav.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation 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/dashboard_nav"
    app:startDestination="@id/scanFragment">
    <fragment
        android:id="@+id/scanFragment"
        android:name="com.app.app.fragments.ScanFragment"
        android:label="fragment_scan"
        tools:layout="@layout/fragment_scan" />
    <fragment
        android:id="@+id/profileFragment"
        android:name="com.app.app.fragments.ProfileFragment"
        android:label="fragment_profile"
        tools:layout="@layout/fragment_profile">
        <action
            android:id="@+id/action_profileFragment_to_bankFragment"
            app:destination="@id/bankFragment" />
    </fragment>
    <fragment
        android:id="@+id/bankFragment"
        android:name="com.app.app.fragments.BankFragment"
        android:label="BankFragment"
        tools:layout="@layout/fragment_bank" />
</navigation>
</code>```

Crash:

```<code>2022-02-04 18:09:44.524 23247-23247/com.app.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.app.app, PID: 23247
    java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set
        at androidx.navigation.Navigation.findNavController(Navigation.java:84)
        at androidx.navigation.fragment.NavHostFragment.findNavController(NavHostFragment.java:120)
        at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
        at com.app.app.fragments.ProfileFragment.onViewCreated$lambda-0(ProfileFragment.kt:45)
        at com.app.app.fragments.ProfileFragment.$r8$lambda$0UCyAyd5HwAmhAbNeILyUNaedgA(Unknown Source:0)
        at com.app.app.fragments.ProfileFragment$$ExternalSyntheticLambda2.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:7862)
        at android.view.View.performClickInternal(View.java:7831)
        at android.view.View.access$3600(View.java:879)
        at android.view.View$PerformClick.run(View.java:29359)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
</code>```

答:
I've downloaded an example from Github that helped me fix this problem.

According to the example this code worked for me:

```<code>class DashboardActivity : BaseActivity() {

    private lateinit var navController: NavController
    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)

        val navHostFragment = supportFragmentManager.findFragmentById(
            R.id.dashboardNavHostFragment
        ) as NavHostFragment
        navController = navHostFragment.navController

        // Setup the bottom navigation view with navController
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        bottomNavigationView.setupWithNavController(navController)

        // Setup the ActionBar with navController and 2 top level destinations
        appBarConfiguration = AppBarConfiguration(
            setOf(R.id.scanFragment, R.id.profileFragment)
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp(appBarConfiguration)
    }

}
</code>```

Body:
I'm new to Android Development and I'm stuck on this error for days now..

I have an activity with a FragmentContainerView and BottomNavigationView. The BottomNavigationView has 2 fragments to switch from: ScanFragment and ProfileFragment.

When I switch to the ProfileFragment and press on a button (payMethodButton) with this code:

 val payMethodButton = view.findViewById<TableRow>(R.id.trMyPayMethod)
        payMethodButton.setOnClickListener {

    findNavController().navigate(
       R.id.action_profileFragment_to_bankFragment
    )
}

the application will crash with this error message: View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set

What am I doing wrong? Why is there no NavController?

DashboardActivity.kt

package com.app.app.activities.dashboard

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.app.app.R
import com.app.app.activities.BaseActivity
import com.app.app.fragments.ProfileFragment
import com.app.app.fragments.ScanFragment

class DashboardActivity : BaseActivity() {

    private val scanFragment: Fragment = ScanFragment()
    private val profileFragment: Fragment = ProfileFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)

        val navigation = findViewById<View>(R.id.bottomNavigationView) as BottomNavigationView
        navigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_scan -> replaceFragment(scanFragment)
                R.id.navigation_profile -> replaceFragment(profileFragment)
            }
            true
        }

    }

    private fun replaceFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.dashboardNavHostFragment, fragment)
        transaction.commit()
    }

}

activity_dashboard.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/dashboardNavHostFragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/dashboard_nav" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/bottom_menu_bar"
        app:itemIconTint="@drawable/bottom_nav_selector"
        app:itemTextAppearanceActive="@style/BottomNavigationView.Active"
        app:itemTextAppearanceInactive="@style/BottomNavigationView"
        app:itemTextColor="@drawable/bottom_nav_selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_dash_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

ProfileFragment.kt

package com.app.app.fragments

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.TableRow
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavHost
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import com.app.app.BuildConfig
import com.app.app.R
import com.app.app.activities.account.login.LoginActivity

class ProfileFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_profile, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        (activity as AppCompatActivity).supportActionBar?.title = "Profile"

        val payMethodButton = view.findViewById<Button>(R.id.btPayMethod)
        payMethodButton.setOnClickListener {

            findNavController().navigate(
                R.id.action_profileFragment_to_bankFragment
            )
        }

    }

}

dashboard_nav.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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/dashboard_nav"
    app:startDestination="@id/scanFragment">
    <fragment
        android:id="@+id/scanFragment"
        android:name="com.app.app.fragments.ScanFragment"
        android:label="fragment_scan"
        tools:layout="@layout/fragment_scan" />
    <fragment
        android:id="@+id/profileFragment"
        android:name="com.app.app.fragments.ProfileFragment"
        android:label="fragment_profile"
        tools:layout="@layout/fragment_profile">
        <action
            android:id="@+id/action_profileFragment_to_bankFragment"
            app:destination="@id/bankFragment" />
    </fragment>
    <fragment
        android:id="@+id/bankFragment"
        android:name="com.app.app.fragments.BankFragment"
        android:label="BankFragment"
        tools:layout="@layout/fragment_bank" />
</navigation>

Crash:

2022-02-04 18:09:44.524 23247-23247/com.app.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.app.app, PID: 23247
    java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{2aaced1 V.E...... ........ 0,0-1080,1668} does not have a NavController set
        at androidx.navigation.Navigation.findNavController(Navigation.java:84)
        at androidx.navigation.fragment.NavHostFragment.findNavController(NavHostFragment.java:120)
        at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
        at com.app.app.fragments.ProfileFragment.onViewCreated$lambda-0(ProfileFragment.kt:45)
        at com.app.app.fragments.ProfileFragment.$r8$lambda$0UCyAyd5HwAmhAbNeILyUNaedgA(Unknown Source:0)
        at com.app.app.fragments.ProfileFragment$$ExternalSyntheticLambda2.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:7862)
        at android.view.View.performClickInternal(View.java:7831)
        at android.view.View.access$3600(View.java:879)
        at android.view.View$PerformClick.run(View.java:29359)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)

Body:
I've downloaded an example from Github that helped me fix this problem.

According to the example this code worked for me:

class DashboardActivity : BaseActivity() {

    private lateinit var navController: NavController
    private lateinit var appBarConfiguration: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)

        val navHostFragment = supportFragmentManager.findFragmentById(
            R.id.dashboardNavHostFragment
        ) as NavHostFragment
        navController = navHostFragment.navController

        // Setup the bottom navigation view with navController
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        bottomNavigationView.setupWithNavController(navController)

        // Setup the ActionBar with navController and 2 top level destinations
        appBarConfiguration = AppBarConfiguration(
            setOf(R.id.scanFragment, R.id.profileFragment)
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp(appBarConfiguration)
    }

}


来源: stackexchange

问:
RecyclerViewAdapter lags with mapview
I'm facing an issue regarding RecyclerViewAdapter.
I'm using fragments, i have 4 fragments. 3 fragments are working fine with no lags. but in 4th fragment, i used mapview and my recyclerViewslows down means not a smooth scrolling as previous fragments when i scroll.

Here is my recyclerViewAdapter:

```<code>public class VenturesAdapter extends RecyclerView.Adapter<VenturesAdapter.MyViewHolder>{
    Context mContext;
    List<venturesPojo> venturesList=new ArrayList<>();
    OnBottomReachedListener onBottomReachedListener;
    GoogleMap googleMap1;

    public class MyViewHolder extends RecyclerView.ViewHolder

    {

        TextView title,description,address;
        ImageView logo;
        Button viewWeb;
        private MapView mapView;
        public MyViewHolder(View itemView) {
            super(itemView);

            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
            address = (TextView) itemView.findViewById(R.id.address);
            logo = (ImageView) itemView.findViewById(R.id.logo);
            viewWeb = (Button) itemView.findViewById(R.id.viewWebsites);
            mapView = (MapView) itemView.findViewById(R.id.mapView);
            description.setMovementMethod(new ScrollingMovementMethod());
            description.setNestedScrollingEnabled(true);
            description.setVerticalScrollBarEnabled(true);
            description.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    // Disallow the touch request for parent scroll on touch of child view
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    return false;
                }
            });
        }

    }

    public VenturesAdapter(Context mContext, List<venturesPojo> venturesList) {
        this.mContext = mContext;
        this.venturesList = venturesList;
    }

    @Override
    public VenturesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.single_ventures_list, parent, false);
        return new VenturesAdapter.MyViewHolder(itemView);
    }

    public void setOnBottomReachedListener(OnBottomReachedListener onBottomReachedListener) {
        this.onBottomReachedListener = onBottomReachedListener;
    }
    @Override
    public void onBindViewHolder(VenturesAdapter.MyViewHolder holder, int position) {
        venturesPojo venturesPojo=venturesList.get(position);

        if (position ==venturesList.size() - 2  ){

            onBottomReachedListener.onBottomReached(position);

        }
        holder.mapView.onCreate(null);

        holder.mapView.onResume();

     final   String lat=venturesPojo.getLatitude();
     final   String lng=venturesPojo.getLongitude();

     if(!TextUtils.isEmpty(lat) || !TextUtils.isEmpty(lng)) {
         final LatLng target=new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));

         holder.mapView.getMapAsync(new OnMapReadyCallback() {
             @Override
             public void onMapReady(GoogleMap googleMap) {
                 googleMap1=googleMap;
                 googleMap.addMarker(new MarkerOptions().position(target));
                 googleMap.getUiSettings().setZoomControlsEnabled(true);
                 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(target,16));
                 googleMap.animateCamera(CameraUpdateFactory.zoomIn());
                 googleMap.animateCamera(CameraUpdateFactory.zoomTo(16), 1500, null);

             }
         });
     }

        holder.title.setText(venturesPojo.getAgency_name());
        holder.description.setText(Html.escapeHtml(venturesPojo.getDescription()));
        holder.address.setText(venturesPojo.getAddress());

        if(!TextUtils.isEmpty(Config.agencyLogo+venturesPojo.getLogo().trim()))
        {
            String logoUrl=Config.agencyLogo+venturesPojo.getLogo().replace(" ","%20");
            Log.d("images",logoUrl);
            Glide
                    .with(mContext)
                    .load(logoUrl)
                    .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE))
                    .into(holder.logo);
        }
        else
        {
            holder.logo.setImageResource(R.drawable.thum);
        }

    }

    @Override
    public int getItemCount() {
        return venturesList.size();
    }

    @Override
    public void onViewRecycled(MyViewHolder holder) {

        if(googleMap1!=null)
        {
           googleMap1.clear();
           googleMap1.setMapType(GoogleMap.MAP_TYPE_NONE);
        }
    }
}
</code>```

i added onViewRecycled because when i searched some members gave this solution but didn't work for me, still lags.

答:
You can reach some performance improvements by applying the following:

```<code>recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheEnabled(true);
</code>```

..in combination with lite mode of MapsView:

```<code><com.google.android.gms.maps.MapView
        ...
        app:liteMode="true"
        app:mapType="normal" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: RecyclerViewAdapter lags with mapview

Body:
I'm facing an issue regarding RecyclerViewAdapter.
I'm using fragments, i have 4 fragments. 3 fragments are working fine with no lags. but in 4th fragment, i used mapview and my recyclerViewslows down means not a smooth scrolling as previous fragments when i scroll.

Here is my recyclerViewAdapter:

public class VenturesAdapter extends RecyclerView.Adapter<VenturesAdapter.MyViewHolder>{
    Context mContext;
    List<venturesPojo> venturesList=new ArrayList<>();
    OnBottomReachedListener onBottomReachedListener;
    GoogleMap googleMap1;

    public class MyViewHolder extends RecyclerView.ViewHolder

    {

        TextView title,description,address;
        ImageView logo;
        Button viewWeb;
        private MapView mapView;
        public MyViewHolder(View itemView) {
            super(itemView);

            title = (TextView) itemView.findViewById(R.id.title);
            description = (TextView) itemView.findViewById(R.id.description);
            address = (TextView) itemView.findViewById(R.id.address);
            logo = (ImageView) itemView.findViewById(R.id.logo);
            viewWeb = (Button) itemView.findViewById(R.id.viewWebsites);
            mapView = (MapView) itemView.findViewById(R.id.mapView);
            description.setMovementMethod(new ScrollingMovementMethod());
            description.setNestedScrollingEnabled(true);
            description.setVerticalScrollBarEnabled(true);
            description.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {
                    // Disallow the touch request for parent scroll on touch of child view
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    return false;
                }
            });
        }

    }

    public VenturesAdapter(Context mContext, List<venturesPojo> venturesList) {
        this.mContext = mContext;
        this.venturesList = venturesList;
    }

    @Override
    public VenturesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.single_ventures_list, parent, false);
        return new VenturesAdapter.MyViewHolder(itemView);
    }

    public void setOnBottomReachedListener(OnBottomReachedListener onBottomReachedListener) {
        this.onBottomReachedListener = onBottomReachedListener;
    }
    @Override
    public void onBindViewHolder(VenturesAdapter.MyViewHolder holder, int position) {
        venturesPojo venturesPojo=venturesList.get(position);

        if (position ==venturesList.size() - 2  ){

            onBottomReachedListener.onBottomReached(position);

        }
        holder.mapView.onCreate(null);

        holder.mapView.onResume();

     final   String lat=venturesPojo.getLatitude();
     final   String lng=venturesPojo.getLongitude();

     if(!TextUtils.isEmpty(lat) || !TextUtils.isEmpty(lng)) {
         final LatLng target=new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));

         holder.mapView.getMapAsync(new OnMapReadyCallback() {
             @Override
             public void onMapReady(GoogleMap googleMap) {
                 googleMap1=googleMap;
                 googleMap.addMarker(new MarkerOptions().position(target));
                 googleMap.getUiSettings().setZoomControlsEnabled(true);
                 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(target,16));
                 googleMap.animateCamera(CameraUpdateFactory.zoomIn());
                 googleMap.animateCamera(CameraUpdateFactory.zoomTo(16), 1500, null);

             }
         });
     }

        holder.title.setText(venturesPojo.getAgency_name());
        holder.description.setText(Html.escapeHtml(venturesPojo.getDescription()));
        holder.address.setText(venturesPojo.getAddress());

        if(!TextUtils.isEmpty(Config.agencyLogo+venturesPojo.getLogo().trim()))
        {
            String logoUrl=Config.agencyLogo+venturesPojo.getLogo().replace(" ","%20");
            Log.d("images",logoUrl);
            Glide
                    .with(mContext)
                    .load(logoUrl)
                    .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE))
                    .into(holder.logo);
        }
        else
        {
            holder.logo.setImageResource(R.drawable.thum);
        }

    }

    @Override
    public int getItemCount() {
        return venturesList.size();
    }

    @Override
    public void onViewRecycled(MyViewHolder holder) {

        if(googleMap1!=null)
        {
           googleMap1.clear();
           googleMap1.setMapType(GoogleMap.MAP_TYPE_NONE);
        }
    }
}

i added onViewRecycled because when i searched some members gave this solution but didn't work for me, still lags.

Body:
You can reach some performance improvements by applying the following:

recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheEnabled(true);

..in combination with lite mode of MapsView:

<com.google.android.gms.maps.MapView
        ...
        app:liteMode="true"
        app:mapType="normal" />

ContentLicense: CC BY-SA 4.0


问:
How do I change the learning rate of my readout layer? (PyTorch)
I found how to change the learning rate for a specific layer, but I'm not sure if I have the right thing.

Here I have a single-layer nn and I'm trying to change the learning rate for the readout weights.

I suppose that the "relu1" would be where I could access the readout weights but I'm not sure.

```<code>class NN(nn.Module):

    def __init__(self, input_size, num_classes):

        super(NN, self).__init__()
        self.path1 = nn.Linear(input_size, num_classes)
        self.relu1 = nn.ReLU()

    def forward(self, x):
        x = self.path1(x)
        x = self.relu1(x)

        return x
</code>```

答:
I think you are a bit confused. You don't need to place the learning rate parameter inside your neural net. Instead, go through the Per-Parameter Option while defining your optimizer. You can write the parameter name by printing out your model and specifying the particular parameter you want to change.

Cheers ;)

Body:
I found how to change the learning rate for a specific layer, but I'm not sure if I have the right thing.

Here I have a single-layer nn and I'm trying to change the learning rate for the readout weights.

I suppose that the "relu1" would be where I could access the readout weights but I'm not sure.

class NN(nn.Module):

    def __init__(self, input_size, num_classes):

        super(NN, self).__init__()
        self.path1 = nn.Linear(input_size, num_classes)
        self.relu1 = nn.ReLU()

    def forward(self, x):
        x = self.path1(x)
        x = self.relu1(x)

        return x


问:
Duplicate row for each item in column
I can do things in PowerQuery but I can't find how to achieve the following result:

Before:

After:

The goal is to duplicate the last row (filtered with Project Code=null) for each item in Project Code column. I think duplicating the row as is is important to keep the Metadata Table and expand it later.

Thank you very much for your help.

答:
Try this

Grab all rows except null row

Get unique values of Project column in a list

Grab null row

Create row with the list and expand it

Put the two tables back together.
```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
AllButNull=Table.SelectRows( Source, each ([Project Code] <> null)),
UniqueProjects=List.Distinct(AllButNull[Project Code]),
OnlyNull = Table.SelectRows(#"Added Custom", each ([Project Code] = null)),
#"Replaced Value" = Table.ReplaceValue(OnlyNull,null,   UniqueProjects,Replacer.ReplaceValue,{"Project Code"}),
#"Expanded Project Code" = Table.ExpandListColumn(#"Replaced Value" , "Project Code"),
combined = AllButNull & #"Expanded Project Code"
in  combined
</code>```

Alternately, grab the last row instead of the null row:

Grab all rows except last

Get unique values of Project column in a list

Grab last row

Create row with the list and expand it

Put the two tables back together.
```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
AllButLast=Table.RemoveLastN(Source ,1),
UniqueProjects=List.Distinct(AllButLast[Project Code]),
OnlyBottomRow = Table.LastN(#"Added Custom", 1),
#"Replaced Value" = Table.ReplaceValue(OnlyBottomRow,null,   UniqueProjects,Replacer.ReplaceValue,{"Project Code"}),
#"Expanded Project Code" = Table.ExpandListColumn(#"Replaced Value", "Project Code"),
combined = AllButLast & #"Expanded Project Code"
in combined
</code>```

Title: Duplicate row for each item in column

Body:
Try this

Grab all rows except null row

Get unique values of Project column in a list

Grab null row

Create row with the list and expand it

Put the two tables back together.

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
AllButNull=Table.SelectRows( Source, each ([Project Code] <> null)),
UniqueProjects=List.Distinct(AllButNull[Project Code]),
OnlyNull = Table.SelectRows(#"Added Custom", each ([Project Code] = null)),
#"Replaced Value" = Table.ReplaceValue(OnlyNull,null,   UniqueProjects,Replacer.ReplaceValue,{"Project Code"}),
#"Expanded Project Code" = Table.ExpandListColumn(#"Replaced Value" , "Project Code"),
combined = AllButNull & #"Expanded Project Code"
in  combined

Alternately, grab the last row instead of the null row:

Grab all rows except last

Get unique values of Project column in a list

Grab last row

Create row with the list and expand it

Put the two tables back together.

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
AllButLast=Table.RemoveLastN(Source ,1),
UniqueProjects=List.Distinct(AllButLast[Project Code]),
OnlyBottomRow = Table.LastN(#"Added Custom", 1),
#"Replaced Value" = Table.ReplaceValue(OnlyBottomRow,null,   UniqueProjects,Replacer.ReplaceValue,{"Project Code"}),
#"Expanded Project Code" = Table.ExpandListColumn(#"Replaced Value", "Project Code"),
combined = AllButLast & #"Expanded Project Code"
in combined


问:
How to add an anchor  tag / html to a Swal call
I am trying to add an anchor tag to my swal tag (I am using Sweetalert with cdn). Is there any way to do this specifically with jQuery (not Angular/React)?

I have tried using a variable with the value of the link as below:

swal({
text: "foo",
content: "link" + (backtick)Link(backtick)
});
```

But why this did not work?

Thanks.

答:
As @Louys pointed out in the comment above, use SweetAlert2 (the latest)

```
<p>Then you can utilise the <code>html</code> field, like so:</p>
<pre class="lang-js prettyprint-override"><code>Swal.fire({
  title: '<strong>HTML <u>example</u></strong>',
  icon: 'info',
  html:
    'You can use <b>bold text</b>, ' +
    'links ' +
    'and other HTML tags'
})
</code>```

Using a 'template literal' - backticks (`) - you can insert variables and add a link like so:

var my_link = 'http://google.com';
Swal.fire({
  title: 'HTML example',
  icon: 'info',
  html: `Click here!`
})
```

Title: How to add an anchor <a> tag / html to a Swal call

Body:
I am trying to add an anchor tag to my swal tag (I am using Sweetalert with cdn). Is there any way to do this specifically with jQuery (not Angular/React)?

I have tried using a variable with the value of the link as below:

swal({
text: "foo",
content: "link" + (backtick)Link(backtick)
});

But why this did not work?

Thanks.

Body:
As @Louys pointed out in the comment above, use SweetAlert2 (the latest)

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Then you can utilise the html field, like so:

Swal.fire({
  title: '<strong>HTML <u>example</u></strong>',
  icon: 'info',
  html:
    'You can use <b>bold text</b>, ' +
    '<a href="//sweetalert2.github.io">links</a> ' +
    'and other HTML tags'
})

Using a 'template literal' - backticks (`) - you can insert variables and add a link like so:

var my_link = 'http://google.com';
Swal.fire({
  title: '<strong>HTML <u>example</u></strong>',
  icon: 'info',
  html: `<a href="${my_link}">Click here!</a>`
})


问:
process execution problem in linux
I wanted to open a file in notepad(using   JAVA) by...

proc.exec("notepad "+curDir+"\auto_saved.txt");

where...

```<code> String curDir = System.getProperty("user.home");
 curDir=curDir+"/txt-files";
 Runtime proc = Runtime.getRuntime();
</code>```

this works properly in WIN7 but says      'home..........\auto_saved.txt'  PATH     not found. in LINUX.
but if I save  a file to  (curDir+"\auto_saved.txt");..it creates a file and saves  it in LINUX.

So, how to open a file in /home/user/some-folder/...??

答: You're expecting the \ in "\auto_saved.txt" to be a directory separator, but in Linux it isn't, it's just an ordinary character that can be part of a filename.  Use File.pathSeparator (a static field in java.io.File) instead; it'll be / on Linux/Unix and \ on Windows.

Title: process execution problem in linux

Body:
I wanted to open a file in notepad(using   JAVA) by...

proc.exec("notepad "+curDir+"\auto_saved.txt");

where...

 String curDir = System.getProperty("user.home");
 curDir=curDir+"/txt-files";
 Runtime proc = Runtime.getRuntime();

this works properly in WIN7 but says      'home..........\auto_saved.txt'  PATH     not found. in LINUX.
but if I save  a file to  (curDir+"\auto_saved.txt");..it creates a file and saves  it in LINUX.

So, how to open a file in /home/user/some-folder/...??


问:
How can I make cross-platform Kivy app with system-tray/taskbar icon which would detect keyboard input even when app is not focused/in taskbar mode
I want to create application with taskbar/system-tray icon. Crossplatform. OSX, Windows, Linux (Ubuntu/Centos/Mint/Manjaro and other popular distros).

This app should detect keyboard input and react to it. Basically do some actions on specific keys. Example: user wants to play some music, presses shift+ctrl+p. Music starts playing.

I know that Kivy capable of detecting

答:
If you're willing to depart from Kivy and use another framework, PySimpleGUI has a System Tray capability (at least for Windows, and perhaps Linux/Mac) when running the tkinter version.  The PySimpleGUIQt port has a more "official" System Tray feature.

The GitHub Repo PySimpleHotkey is one example of how to use the psgtray package to make a hotkey program.

https://github.com/PySimpleGUI/PySimpleHotkey


问:
Nuget restore exception when deleting subproject
I currently have a project in dotnet that has several different projects within it. I am attempting to move out one of the projects to a separate repo and replace it with a git submodule. The issue I'm having is how to remove the package from the original repo. I can delete the directory of the package and I updated the dirs.proj to not contain those proj files.

```<code><Project Sdk="Microsoft.Build.Traversal">
  <ItemGroup>
    <ProjectFile Include="Proj1\dirs.proj" />
    <ProjectFile Include="Proj2\dirs.proj" />
    ...
    // Removed this line <ProjectFile Include="ProjBeingMovedToNewRepo\dirs.proj" />
  </ItemGroup>
</Project>
</code>```

However, when I try to build the resulting solution (msbuild dirs.proj), I get the following exception:

C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Microsoft\NuGet\NuGet.RestoreEx.targets(19,5): error :
The project file could not be loaded. Could not find a part of the path
'D:\git\Networking-Tycoon\src\ProjBeingMovedToNewRepo\ProjBeingMovedToNewRepo.csproj'.  D:\git\Networking-Tycoon\src\ProjBeingMovedToNewRepo\ProjBeingMovedToNewRepo.csproj [D:\git\Networking-Tycoon\dirs.proj]

It isn't clear to me exactly why the nuget restoreEx targets is trying to pull that project that was removed or where I can update those settings. I tried to disable nuget auto restore and to clean the solution before building but so far have not had luck.

One other note is that the project that is being removed is still being referenced in the project elsewhere (I was planning on referencing the submodule for those later) but wanted to see if there was something more simple I was missing first. What would be the steps that would need to be taken to remove a project like this generally?

答:
In Visual Studio, first close the solution.
Then goto Tools, Nuget package manager, Package Manager Settings.

Then Clear all Nuget cache.

That should clear the problem.

Body:
I currently have a project in dotnet that has several different projects within it. I am attempting to move out one of the projects to a separate repo and replace it with a git submodule. The issue I'm having is how to remove the package from the original repo. I can delete the directory of the package and I updated the dirs.proj to not contain those proj files.

<Project Sdk="Microsoft.Build.Traversal">
  <ItemGroup>
    <ProjectFile Include="Proj1\dirs.proj" />
    <ProjectFile Include="Proj2\dirs.proj" />
    ...
    // Removed this line <ProjectFile Include="ProjBeingMovedToNewRepo\dirs.proj" />
  </ItemGroup>
</Project>

However, when I try to build the resulting solution (msbuild dirs.proj), I get the following exception:

C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Microsoft\NuGet\NuGet.RestoreEx.targets(19,5): error :
The project file could not be loaded. Could not find a part of the path
'D:\git\Networking-Tycoon\src\ProjBeingMovedToNewRepo\ProjBeingMovedToNewRepo.csproj'.  D:\git\Networking-Tycoon\src\ProjBeingMovedToNewRepo\ProjBeingMovedToNewRepo.csproj [D:\git\Networking-Tycoon\dirs.proj]

It isn't clear to me exactly why the nuget restoreEx targets is trying to pull that project that was removed or where I can update those settings. I tried to disable nuget auto restore and to clean the solution before building but so far have not had luck.

One other note is that the project that is being removed is still being referenced in the project elsewhere (I was planning on referencing the submodule for those later) but wanted to see if there was something more simple I was missing first. What would be the steps that would need to be taken to remove a project like this generally?


问:
How to use view binding in Android
I have been using findViewById and then ButterKnife to bind views. Recently, I came across this article and am not quite sure how to use it.

I tried doing it but it does not seem to work in Android Studio 3.4.2

```<code>val binding = MainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
</code>```

then afterwards using these values, as an example :

```<code>binding.button....
binding.textView....
</code>```

答:
in kotlin

The important note is view binding is only available for android studio 3.6+. implement view binding in the project you can follow the below steps.

Step 1: upgrade your Gradle version(3.6.1+) in the build.gradle (Project Level) file.

```<code>   dependencies {
            classpath 'com.android.tools.build:gradle:7.0.3'
    }
</code>```

Step 2: Add this line to your build.gradle (App Level) file in android{}

```<code> buildFeatures {
        viewBinding = true
    }
</code>```

Step 3: Add this code (Depend on Your Activity name).

```<code>class MainActivity : AppCompatActivity() {

 private lateinit var binding: ActivityMainBinding

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root //you can use directly setContentView(binding.root)
    setContentView(view)
    binding.textview.text="Hii"
</code>```

}

or you can achieve the above functionality in this code. I personally prefer to goes to the second one.

```<code>class MainActivity : AppCompatActivity() {

    private val binding by lazy {

        ActivityMainBinding.inflate(layoutInflater)
    }

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.textview.text="Hii"

    }
}
</code>```

Title: How to use view binding in Android

Body:
I have been using findViewById and then ButterKnife to bind views. Recently, I came across this article and am not quite sure how to use it.

I tried doing it but it does not seem to work in Android Studio 3.4.2

val binding = MainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)

then afterwards using these values, as an example :

binding.button....
binding.textView....

Body:
in kotlin

The important note is view binding is only available for android studio 3.6+. implement view binding in the project you can follow the below steps.

Step 1: upgrade your Gradle version(3.6.1+) in the build.gradle (Project Level) file.

   dependencies {
            classpath 'com.android.tools.build:gradle:7.0.3'
    }

Step 2: Add this line to your build.gradle (App Level) file in android{}

 buildFeatures {
        viewBinding = true
    }

Step 3: Add this code (Depend on Your Activity name).

class MainActivity : AppCompatActivity() {

 private lateinit var binding: ActivityMainBinding

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root //you can use directly setContentView(binding.root)
    setContentView(view)
    binding.textview.text="Hii"

}

or you can achieve the above functionality in this code. I personally prefer to goes to the second one.

class MainActivity : AppCompatActivity() {

    private val binding by lazy {

        ActivityMainBinding.inflate(layoutInflater)
    }

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.textview.text="Hii"

    }
}


问:
change the date format in excel, date picker
Im using the date picker add in and the format of the date is with backslashes 01/02/2022. Preferable format is 01.02.2022. Is there a way to change this inside the add in rather then using substitute formula or Format cells.

I would use substitute formula but then SAP gui scripting seems like is not picking up another updated date, it just copies the date that was first entered as constant value.

答: I just have changed the format on my pc (since excel picks the format from pc) and worked well but would be interesting if anyone can explain how it can be done without changing the format on pc.</p>


问:
Trying to run a calculation inside an if-else statement and it's stalling - C
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.</p>
```<code>#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", &square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}
</code>```

答:
you don't have to use & in printf</p>
```<code>#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}
</code>```

Body:
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.

#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", &square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}

Body:
you don't have to use & in printf

#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}


问:
Is it a must to provide "sign in with apple" if we provide a "sign in with microsoft" Azure Active Directory. in our iOS App?
4.8 Sign in with Apple

According to the guideline above, we must provide "sign in with apple" if we're providing a 3rd party mean of authentication.

Except if "Your app is an education, enterprise, or business app that requires the user to sign in with an existing education or enterprise account." and some other cases.

My question is; If using MSAL to authenticate with Azure Active directory is considered using a 3rd party authentication method, or it'd be exempted as it's an enterprise account?

We need to support MSAL to one of our clients, and trying to figure out whether "sign in with apple is mandatory"

答:
As I read it you have to use Sign in with Apple in your case. Here is the official text from the guidelines:

Apps that use a third-party or social login service (such as Facebook Login, Google Sign-In, Sign in with Twitter, Sign In with LinkedIn, Login with Amazon, or WeChat Login) to set up or authenticate the user’s primary account with the app must also offer Sign in with Apple as an equivalent option. A user’s primary account is the account they establish with your app for the purposes of identifying themselves, signing in, and accessing your features and associated services.


答:
There is no notepad editor in Linux.  Many linux distributions have a text editor called "nano", in /usr/bin/nano;  Ubuntu/Debian puts a text editor in /etc/alternatives/editor ; you could also also check env{EDITOR}, which sometimes contains a user set pathname to a text editor, and override your choice of editor if present to allow for user customization.

You might want to use the full path to the executable when you call exec, in case it is not on the path.

Title: process execution problem in linux


问:
how to print star hypen pattern in python
How to print the pattern like this:

(need to print n-1 lines)

input=3

```<code>----@
--@-@-@
</code>```

input=6

```<code>----------@
--------@-@-@
------@---@---@
----@-----@-----@
--@-------@-------@
</code>```

My code:

```<code>row = int(input())
for i in range(1, row):
    for j in range(1,row-i+1):
        print("-", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("@", end="")
        else:
            print("-", end="")
    print()
</code>```

MY OUTPUT:
input=5

```<code>----@
---@-@
--@---@
-@-----@
</code>```

Please explain how to do??

答:
```<code>row = int(input())
for i in range(1, row):
    for j in range(1,2*(row-i)+1):
        print("-", end="")
    for j in range(1, 4*i):
        if j==1 or j==2*i-1 or j==4*i-3:
            print("@", end="")
        elif j<=4*i-3:
            print("-", end="")
    print()
</code>```

Body:
How to print the pattern like this:

(need to print n-1 lines)

input=3

----@
--@-@-@

input=6

----------@
--------@-@-@
------@---@---@
----@-----@-----@
--@-------@-------@

My code:

row = int(input())
for i in range(1, row):
    for j in range(1,row-i+1):
        print("-", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("@", end="")
        else:
            print("-", end="")
    print()

MY OUTPUT:
input=5

----@
---@-@
--@---@
-@-----@

Please explain how to do??


问:
Bitrise Firebase App Distribution Error: failed to upload release. HTTP Error: 403, The caller does not have permission
I am getting the below error while uploading the APK on firebase app distribution via Bitrise.</p>
```<code>Error: Failed to upload release. HTTP Error: 403, The caller does not have permission
</code>```

答:
The answer is I forgot to add bitrise email in the firebase project under users & Permission as an owner. Then you need to accept the invitation by logging in to the email which you have added.</p>
```<code>Steps :

- Login to firebase project
- Go to Project Setting
- User & Permissions
- Add User with owner access (Add the email id which used in the bitrise)
- You will receive the invite to the added email id.
- Login to the email & Accept the invitation.
</code>```

Body:
I am getting the below error while uploading the APK on firebase app distribution via Bitrise.

Error: Failed to upload release. HTTP Error: 403, The caller does not have permission

Body:
The answer is I forgot to add bitrise email in the firebase project under users & Permission as an owner. Then you need to accept the invitation by logging in to the email which you have added.

Steps :

- Login to firebase project
- Go to Project Setting
- User & Permissions
- Add User with owner access (Add the email id which used in the bitrise)
- You will receive the invite to the added email id.
- Login to the email & Accept the invitation.


问:
VueJs the input value doesnt cleared with the keypress ESC the first time
I want to clear the input when i press the ESC key, the bug that i've is when i press the ESC key the first time, the input isnt cleared but when i press ESC second time it is cleard

When i display in console the value of the input after first press, it's empty but not in the UI

Here is the small piece of code that ma,age the ESC Key :

Html :

```<code><input
      type="text"
      :name="context.name"
      :id="context.id"
      v-model="context.model"
      @blur="context.blurHandler"
      @keyup="getSuggestions"
      autocomplete="no"
      class="mc-text-input"
      ref="autocompleteInput"
    />
</code>```

And the ESC event :

```<code>case 27: {
          console.log('Before : ' + this.$refs.autocompleteInput.value)
          this.$refs.autocompleteInput.value = ''
          console.log('After : ' + this.$refs.autocompleteInput.value)
          this.resetAutocompleteElt() // hide the autocomplete list
          break
}
</code>```

I need to force the first ESC press to clear this input

答:
v-model uses two-way binding, so you should update context.model instead of trying to update the element value directly, as this is likely causing your problem.

i.e. assuming you have access to context.model in your function that handles the event.

Replace:

```<code>this.$refs.autocompleteInput.value = ''
</code>```

with:

```<code>this.context.model = '';
</code>```

Body:
I want to clear the input when i press the ESC key, the bug that i've is when i press the ESC key the first time, the input isnt cleared but when i press ESC second time it is cleard

When i display in console the value of the input after first press, it's empty but not in the UI

Here is the small piece of code that ma,age the ESC Key :

Html :

<input
      type="text"
      :name="context.name"
      :id="context.id"
      v-model="context.model"
      @blur="context.blurHandler"
      @keyup="getSuggestions"
      autocomplete="no"
      class="mc-text-input"
      ref="autocompleteInput"
    />

And the ESC event :

case 27: {
          console.log('Before : ' + this.$refs.autocompleteInput.value)
          this.$refs.autocompleteInput.value = ''
          console.log('After : ' + this.$refs.autocompleteInput.value)
          this.resetAutocompleteElt() // hide the autocomplete list
          break
}

I need to force the first ESC press to clear this input

Body:
v-model uses two-way binding, so you should update context.model instead of trying to update the element value directly, as this is likely causing your problem.

i.e. assuming you have access to context.model in your function that handles the event.

Replace:

this.$refs.autocompleteInput.value = ''

with:

this.context.model = '';


问:
React - Extra table row printing incorrectly
I am looping through an array of objects, then based on a condition I am display that row in one Table or the other. However, when i call that condition, the object reacts how I would like (it displays in Table1) but in Table2 a number is being printed out also. The following is a snippit example. files contains and array of objects, person. If the person is male, they are added to an array and that array is passed to a seperate componenet and rendered elsewhere, This works. If the person is not male, they are returned in the table underneath the condiditon.

```<code><tbody>
{props.files.map(person=> (
    <div>
        {(person.gender === "male") ? maleArray.push(person) :
            <tr>
                <td>{person.name}</td>
                <td>{person.age}</td>
            </tr>
         }
    </div>
))}
</tbody>

</code>```

The problem is, everytime a male is detected, they are not displayed in the female table but a number is printed instead. For example,

Name
Age

Mary
51

1

Jane
19

The male table works as expected but if a male is detected in the loop, i get this output in the female table.

EDIT: Table is printing weird in final version. It would look something like this

Name    Age

Mary    51

1

Jane    19

答:
Array.Map performs an action on every element of the array and takes the return value.

maleArray.push(person) returns 1 if successfull, so 1 gets rendered instead of the values.

You could create a male- and a female-array inside a forEach-loop and map those arrays instead.

Body:
I am looping through an array of objects, then based on a condition I am display that row in one Table or the other. However, when i call that condition, the object reacts how I would like (it displays in Table1) but in Table2 a number is being printed out also. The following is a snippit example. files contains and array of objects, person. If the person is male, they are added to an array and that array is passed to a seperate componenet and rendered elsewhere, This works. If the person is not male, they are returned in the table underneath the condiditon.

{props.files.map(person=> (

        {(person.gender === "male") ? maleArray.push(person) :

                {person.name}
                {person.age}

         }

))}

The problem is, everytime a male is detected, they are not displayed in the female table but a number is printed instead. For example,

Name
Age

Mary
51

1

Jane
19

The male table works as expected but if a male is detected in the loop, i get this output in the female table.

EDIT: Table is printing weird in final version. It would look something like this

Name    Age

Mary    51

1

Jane    19


问:
How to update the object key's value in state using useState() hook?
I have a array of objects state that has two key-value pairs [{name: 'Max', value: 1}]

when updating the state i am receiving the name from api and comparing with api.name == state.name. if it is true i need to update the value like value + 1. How do i achieve with setState()?

答:
You could update the state like this:</p>
```<code>    const stateUpdated = state.map((item) => {
      if (name === item.name) {
        return {
          ...item,
          value: ++item.value,
        };
      } else {
        return item;
      }
    });

    setState(stateUpdated);
</code>```

Body:
You could update the state like this:

    const stateUpdated = state.map((item) => {
      if (name === item.name) {
        return {
          ...item,
          value: ++item.value,
        };
      } else {
        return item;
      }
    });

    setState(stateUpdated);


问:
Recyclerview in Recyclerview scrolling first time laggy
I have Recyclerview multiple view types and have Recyclerview in Recyclerview when scroll lag first time I do not know why scroll lag first time

here my layout fragment

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".presentation.LottoFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/teal_700"
        android:padding="20dp">

        <LinearLayout
            android:id="@+id/searchLinearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/menuTextInputLayout"
                style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/label">

                <AutoCompleteTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="none" />

            </com.google.android.material.textfield.TextInputLayout>

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>

    <LinearLayout
        android:id="@+id/contentLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:behavior_peekHeight="56dp"
        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_list_header_background"
            android:clickable="true"
            android:elevation="4dp"
            android:orientation="horizontal"
            android:padding="20dp">

            <TextView
                android:id="@+id/lotto_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/kanit_light"
                android:text="0 items(s)" />

            <ImageView
                android:id="@+id/filterIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:src="@android:drawable/arrow_up_float"
                android:visibility="gone" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/front_layer_linear_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:orientation="vertical">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/lotto_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipToPadding="false"
                android:paddingBottom="64dp"
                tools:itemCount="3"
                tools:listitem="@layout/item_lotto_prizes_one" />

        </LinearLayout>
    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

here my fragment

```<code> lottoRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = lottoLatestAdapter
        }
</code>```

here my Adapter:

```<code>class LottoLatestAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val VIEW_TYPE_LOTTO_PRIZE_ONE = 1
        private const val VIEW_TYPE_LOTTO_PRIZE_RUNNING_NUMBER = 2
        private const val VIEW_TYPE_LOTTO_PRIZE_ONE_NEAR = 3
        private const val VIEW_TYPE_LOTTO_PRIZE_OTHER = 4
    }
    var latestList: MutableList<LottoPrizesLatestModel> = mutableListOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    private val viewPool : RecycledViewPool = RecycledViewPool()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            VIEW_TYPE_LOTTO_PRIZE_ONE -> {
                LottoPrizeOneHolder(ItemLottoPrizesOneBinding.inflate(inflater, parent, false))
            }
            VIEW_TYPE_LOTTO_PRIZE_RUNNING_NUMBER -> {
                LottoPrizeRunningNumberHolder(
                    ItemLottoRunningNumbersBinding.inflate(
                        inflater,
                        parent,
                        false
                    )
                )
            }
            VIEW_TYPE_LOTTO_PRIZE_ONE_NEAR -> {
                LottoPrizeOneNearHolder(
                    ItemLottoPrizesOneNearBinding.inflate(
                        inflater,
                        parent,
                        false
                    )
                )
            }
            VIEW_TYPE_LOTTO_PRIZE_OTHER -> {
                LottoPrizeOtherListHolder(
                    ItemLottoPrizesOtherListBinding.inflate(
                        inflater,
                        parent,
                        false
                    ),
                    LottoLatestPrizeOtherAdapter()
                )
            }
            else -> throw NullPointerException("Not have view Type")
        }
    }

    override fun getItemViewType(position: Int): Int {
        return when (latestList[position]) {
            is LottoPrizesLatestModel.LottoLatestPrizeOne -> VIEW_TYPE_LOTTO_PRIZE_ONE
            is LottoPrizesLatestModel.LottoLatestRunningNumbers -> VIEW_TYPE_LOTTO_PRIZE_RUNNING_NUMBER
            is LottoPrizesLatestModel.LottoLatestPrizeFirstNear -> VIEW_TYPE_LOTTO_PRIZE_ONE_NEAR
            is LottoPrizesLatestModel.LottoLatestPrizeOther -> VIEW_TYPE_LOTTO_PRIZE_OTHER
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is LottoPrizeOneHolder -> holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestPrizeOne)

            is LottoPrizeRunningNumberHolder -> holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestRunningNumbers)

            is LottoPrizeOneNearHolder -> holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestPrizeFirstNear)

            is LottoPrizeOtherListHolder -> {
                viewPool.putRecycledView(holder)
                holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestPrizeOther, viewPool)
            }

        }
    }

    override fun getItemCount(): Int = latestList.size
}
</code>```

here my layout holder

```<code><?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="wrap_content"
    android:layout_margin="8dp">

    <TextView
        android:id="@+id/title_prize_other_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="@font/kanit_light"
        android:gravity="center"
        android:textSize="26sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/prize_other_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title_prize_other_text_view"
        tools:itemCount="10"
        tools:listitem="@layout/item_lotto_prizes_other" />

    <GridLayout
        android:id="@+id/prize_other_grip_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="2"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title_prize_other_text_view" />

    <TextView
        android:id="@+id/text_prize_one_near_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/kanit_light"
        android:text="@string/lotto_prize_per_baht"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/prize_other_recycler_view" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

and here my holder recyclerView in RecyclerView

```<code>class LottoPrizeOtherListHolder(
    private val binding: ItemLottoPrizesOtherListBinding,
    private val lottoLatestPrizeOtherAdapter: LottoLatestPrizeOtherAdapter
) :
    RecyclerView.ViewHolder(binding.root) {

    fun bind(
        lottoLatestPrizeOther: LottoPrizesLatestModel.LottoLatestPrizeOther,
        viewPool: RecyclerView.RecycledViewPool
    ) = with(binding) {

        prizeOtherRecyclerView.apply {
            layoutManager = GridLayoutManager(
                context,
                2,
                GridLayoutManager.VERTICAL,
                false
            ).apply {
                initialPrefetchItemCount = lottoLatestPrizeOther.prizeModel.number.size
            }
            this.adapter = lottoLatestPrizeOtherAdapter
            setRecycledViewPool(viewPool)
        }
        lottoLatestPrizeOtherAdapter.numberList =
            lottoLatestPrizeOther.prizeModel.number.toMutableList()
        titlePrizeOtherTextView.text = lottoLatestPrizeOther.prizeModel.name
        textPrizeOneNearTextView.text = itemView.context.getString(
            R.string.lotto_prize_per_baht,
            lottoLatestPrizeOther.prizeModel.reward
        )
    }
}
</code>```

my problem is : When i scroll recyclerview for first time it is not smooth and logcat show recyclerview Skipped 51 frames! adapter but when I reach end of recyclerView and scroll to up then scroll down it is very smooth and my recyclerview have TextView Only !!! how can I solve this issue?

this my video App https://youtu.be/Li7aKWmEfXQ

答:
You can reach some performance improvements by applying the following:

```<code>recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheEnabled(true);
</code>```

..in combination with lite mode of MapsView:

```<code><com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:liteMode="true"
        app:mapType="normal" />
</code>```

For it was not an option to disable nestedScrollingEnabled as mentioned by @Narendra_Nath, which further improves performance.

Body:
I have Recyclerview multiple view types and have Recyclerview in Recyclerview when scroll lag first time I do not know why scroll lag first time

here my layout fragment

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".presentation.LottoFragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/teal_700"
        android:padding="20dp">

        <LinearLayout
            android:id="@+id/searchLinearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/menuTextInputLayout"
                style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/label">

                <AutoCompleteTextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="none" />

            </com.google.android.material.textfield.TextInputLayout>

        </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>

    <LinearLayout
        android:id="@+id/contentLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:behavior_peekHeight="56dp"
        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_list_header_background"
            android:clickable="true"
            android:elevation="4dp"
            android:orientation="horizontal"
            android:padding="20dp">

            <TextView
                android:id="@+id/lotto_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/kanit_light"
                android:text="0 items(s)" />

            <ImageView
                android:id="@+id/filterIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:src="@android:drawable/arrow_up_float"
                android:visibility="gone" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/front_layer_linear_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:orientation="vertical">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/lotto_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipToPadding="false"
                android:paddingBottom="64dp"
                tools:itemCount="3"
                tools:listitem="@layout/item_lotto_prizes_one" />

        </LinearLayout>
    </LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

here my fragment

 lottoRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = lottoLatestAdapter
        }

here my Adapter:

class LottoLatestAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val VIEW_TYPE_LOTTO_PRIZE_ONE = 1
        private const val VIEW_TYPE_LOTTO_PRIZE_RUNNING_NUMBER = 2
        private const val VIEW_TYPE_LOTTO_PRIZE_ONE_NEAR = 3
        private const val VIEW_TYPE_LOTTO_PRIZE_OTHER = 4
    }
    var latestList: MutableList<LottoPrizesLatestModel> = mutableListOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    private val viewPool : RecycledViewPool = RecycledViewPool()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            VIEW_TYPE_LOTTO_PRIZE_ONE -> {
                LottoPrizeOneHolder(ItemLottoPrizesOneBinding.inflate(inflater, parent, false))
            }
            VIEW_TYPE_LOTTO_PRIZE_RUNNING_NUMBER -> {
                LottoPrizeRunningNumberHolder(
                    ItemLottoRunningNumbersBinding.inflate(
                        inflater,
                        parent,
                        false
                    )
                )
            }
            VIEW_TYPE_LOTTO_PRIZE_ONE_NEAR -> {
                LottoPrizeOneNearHolder(
                    ItemLottoPrizesOneNearBinding.inflate(
                        inflater,
                        parent,
                        false
                    )
                )
            }
            VIEW_TYPE_LOTTO_PRIZE_OTHER -> {
                LottoPrizeOtherListHolder(
                    ItemLottoPrizesOtherListBinding.inflate(
                        inflater,
                        parent,
                        false
                    ),
                    LottoLatestPrizeOtherAdapter()
                )
            }
            else -> throw NullPointerException("Not have view Type")
        }
    }

    override fun getItemViewType(position: Int): Int {
        return when (latestList[position]) {
            is LottoPrizesLatestModel.LottoLatestPrizeOne -> VIEW_TYPE_LOTTO_PRIZE_ONE
            is LottoPrizesLatestModel.LottoLatestRunningNumbers -> VIEW_TYPE_LOTTO_PRIZE_RUNNING_NUMBER
            is LottoPrizesLatestModel.LottoLatestPrizeFirstNear -> VIEW_TYPE_LOTTO_PRIZE_ONE_NEAR
            is LottoPrizesLatestModel.LottoLatestPrizeOther -> VIEW_TYPE_LOTTO_PRIZE_OTHER
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is LottoPrizeOneHolder -> holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestPrizeOne)

            is LottoPrizeRunningNumberHolder -> holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestRunningNumbers)

            is LottoPrizeOneNearHolder -> holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestPrizeFirstNear)

            is LottoPrizeOtherListHolder -> {
                viewPool.putRecycledView(holder)
                holder.bind(latestList[position] as LottoPrizesLatestModel.LottoLatestPrizeOther, viewPool)
            }

        }
    }

    override fun getItemCount(): Int = latestList.size
}

here my layout holder

<?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="wrap_content"
    android:layout_margin="8dp">

    <TextView
        android:id="@+id/title_prize_other_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="@font/kanit_light"
        android:gravity="center"
        android:textSize="26sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/prize_other_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title_prize_other_text_view"
        tools:itemCount="10"
        tools:listitem="@layout/item_lotto_prizes_other" />

    <GridLayout
        android:id="@+id/prize_other_grip_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnCount="2"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title_prize_other_text_view" />

    <TextView
        android:id="@+id/text_prize_one_near_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/kanit_light"
        android:text="@string/lotto_prize_per_baht"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/prize_other_recycler_view" />

</androidx.constraintlayout.widget.ConstraintLayout>

and here my holder recyclerView in RecyclerView

class LottoPrizeOtherListHolder(
    private val binding: ItemLottoPrizesOtherListBinding,
    private val lottoLatestPrizeOtherAdapter: LottoLatestPrizeOtherAdapter
) :
    RecyclerView.ViewHolder(binding.root) {

    fun bind(
        lottoLatestPrizeOther: LottoPrizesLatestModel.LottoLatestPrizeOther,
        viewPool: RecyclerView.RecycledViewPool
    ) = with(binding) {

        prizeOtherRecyclerView.apply {
            layoutManager = GridLayoutManager(
                context,
                2,
                GridLayoutManager.VERTICAL,
                false
            ).apply {
                initialPrefetchItemCount = lottoLatestPrizeOther.prizeModel.number.size
            }
            this.adapter = lottoLatestPrizeOtherAdapter
            setRecycledViewPool(viewPool)
        }
        lottoLatestPrizeOtherAdapter.numberList =
            lottoLatestPrizeOther.prizeModel.number.toMutableList()
        titlePrizeOtherTextView.text = lottoLatestPrizeOther.prizeModel.name
        textPrizeOneNearTextView.text = itemView.context.getString(
            R.string.lotto_prize_per_baht,
            lottoLatestPrizeOther.prizeModel.reward
        )
    }
}

my problem is : When i scroll recyclerview for first time it is not smooth and logcat show recyclerview Skipped 51 frames! adapter but when I reach end of recyclerView and scroll to up then scroll down it is very smooth and my recyclerview have TextView Only !!! how can I solve this issue?

this my video App https://youtu.be/Li7aKWmEfXQ

Body:
You can reach some performance improvements by applying the following:

recyclerView.setHasFixedSize(true);
recyclerView.setDrawingCacheEnabled(true);

..in combination with lite mode of MapsView:

<com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:liteMode="true"
        app:mapType="normal" />

For it was not an option to disable nestedScrollingEnabled as mentioned by @Narendra_Nath, which further improves performance.


问:
php null replacement function
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

```<code>function replace_null($value, $replace) {
    if (!isset($value)) {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null($data['address'], 'Address is not available.');
</code>```

of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.

i'm currently using ternary

```<code>(isset(data['address']) ? data['address'] : 'Address is not available.');
</code>```

but i think replace_null, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.

答:
A bit roundabout: If you only use this to check for array members, you could pass the key separately:

```<code>function get_with_default($arr, $key, $defval)
{
  return isset($arr[$key]) ? $arr[$key] : $defval;
}
</code>```

If the variable could be set but null (Edit: which it cannot, thanks @deceze), add another check:

```<code>function get_and_coalesce_with_default($arr, $key, $defval)
{
  return (isset($arr[$key]) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
</code>```

As pointed out, isset() only succeeds on non-null values, so the above doesn't add anything. We can write a non-trivial check with array_key_exists, though:

```<code>function get_with_default_v2($arr, $key, $defval)
{
  return (array_key_exists($key, $arr) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}
</code>```

Title: php null replacement function

Body:
there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

function replace_null($value, $replace) {
    if (!isset($value)) {
        return $replace;
    } else {
        return $value;
    }
}

$address = replace_null($data['address'], 'Address is not available.');

of course, if $data['address'] is found null, php will stop executing the code and replace_null won't be called.

i'm currently using ternary

(isset(data['address']) ? data['address'] : 'Address is not available.');

but i think replace_null, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.

Body:
A bit roundabout: If you only use this to check for array members, you could pass the key separately:

function get_with_default($arr, $key, $defval)
{
  return isset($arr[$key]) ? $arr[$key] : $defval;
}

If the variable could be set but null (Edit: which it cannot, thanks @deceze), add another check:

function get_and_coalesce_with_default($arr, $key, $defval)
{
  return (isset($arr[$key]) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}

As pointed out, isset() only succeeds on non-null values, so the above doesn't add anything. We can write a non-trivial check with array_key_exists, though:

function get_with_default_v2($arr, $key, $defval)
{
  return (array_key_exists($key, $arr) && !is_null($arr[$key]) ? $arr[$key] : $defval;
}


问:
PHP categories showing only one item
I'm trying to create a categories list, where user will be able to choose item with certain category, but as soon as I'm opening any of the categories, where "soon = '2'", there is only one item coming up. Everything else works.

The code bellow is for categories, where user can chose which caegory s/he want to see.

```<code>//navbar.php
<!-- Categories -->
              <div class="dropdown-item menu_cat" type="button" id="catMenuButton"><i class="fas fa-caret-left"></i> Categories</div>
              <form method="POST" class="dropdown-menu dropleft categories_menu row" id="cat_dropdown">
                <button class="dropdown-item" name="candle"> Candles</button>
                <button class="dropdown-item" name="cloth"> Clothes</button>
                <button type="submit"class="dropdown-item" name="tech"> Tech</button>
                </form>

</code>```

Than here is everything else, that is suppose to exectute commands that will show products from category that user choose. The issue comes upp where 'if($row["soon"] == "2")' is.

```<code>//products.php

<?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row["soon"] == "2"){
        ?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>

      <?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic_soon" src="productsImages/comingSoon.png" height="150px" width="120px"></img>
          <style>
          </style>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>

  <?php

    }
}
}
else if(empty($result) || $result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
  }
  $conn->close();
  ?>
</code>```

答:
In the original post was duplicate  $row = $result->fetch_assoc(); statement.

In updated post there is first condition out of the while loop.

Solution bellow is wrapping all the if($row['soon'] into the while loop:

```<code><div class="card-deck col-lg-12 col-md-12 col-sm-12 justify-content-center text-center">
  <?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){
          echo "<h2 class='col-12'> Sorry! </h2>";
          echo "<h3 class='col-12'> This product will be soon avaiable </h3>";
        }
        if($row["soon"] == "2"){
        ?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>
  <?php
        }
  }
}else if($result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
  }
  $conn->close();
  ?>
</div>

  }
}else if($result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category     yet! </h3>";
  }
  $conn->close();
  ?>
</div>
</code>```

Recommendation: Always debug your scripts with enabled PHP Error Reporting!

Title: PHP categories showing only one item

Body:
I'm trying to create a categories list, where user will be able to choose item with certain category, but as soon as I'm opening any of the categories, where "soon = '2'", there is only one item coming up. Everything else works.

The code bellow is for categories, where user can chose which caegory s/he want to see.

//navbar.php

 Categories

              <form method="POST" class="dropdown-menu dropleft categories_menu row" id="cat_dropdown">
                <button class="dropdown-item" name="candle"> Candles</button>
                <button class="dropdown-item" name="cloth"> Clothes</button>
                <button type="submit"class="dropdown-item" name="tech"> Tech</button>
                </form>

Than here is everything else, that is suppose to exectute commands that will show products from category that user choose. The issue comes upp where 'if($row["soon"] == "2")' is.

//products.php

<?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row["soon"] == "2"){
        ?>

 <?php echo $row["productName"] ?>

          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px">

            <?php echo $row["productPrice"]; ?> SEK

          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">

              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product </button>

      <?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>

 <?php echo $row["productName"] ?>

            <?php echo $row["productPrice"]; ?> SEK

          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">

              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product </button>

  <?php

    }
}
}
else if(empty($result) || $result->num_rows == 0){
    echo "
 Sorry!
";
    echo "
 There is not any product in this category yet!
";
  }
  $conn->close();
  ?>

Body:
In the original post was duplicate  $row = $result->fetch_assoc(); statement.

In updated post there is first condition out of the while loop.

Solution bellow is wrapping all the if($row['soon'] into the while loop:

<div class="card-deck col-lg-12 col-md-12 col-sm-12 justify-content-center text-center">
  <?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){
          echo "<h2 class='col-12'> Sorry! </h2>";
          echo "<h3 class='col-12'> This product will be soon avaiable </h3>";
        }
        if($row["soon"] == "2"){
        ?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>
  <?php
        }
  }
}else if($result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
  }
  $conn->close();
  ?>
</div>

  }
}else if($result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category     yet! </h3>";
  }
  $conn->close();
  ?>
</div>

Recommendation: Always debug your scripts with enabled PHP Error Reporting!