android – How to make a recyclerView scroll to the top position by clicking menu item?

I need so that if one clicks the menu item “turn All Words On” (look below), then the view scrolls to the top position.
How to do this from the onOptionItemSelected() method and what to type there?

Appreciate any help.

@AndroidEntryPoint
class VocabularyFragment : Fragment(R.layout.recycler_layout),
    VocabularyAdapter.OnVocItemClickListener {

    private val viewModel: VocabularyViewModel by viewModels()
    private lateinit var searchView: SearchView

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

        val binding = RecyclerLayoutBinding.bind(view)
        val vocabularyAdapter = VocabularyAdapter(this)
        binding.apply {
            recyclerView.apply {
                adapter = vocabularyAdapter
                layoutManager = LinearLayoutManager(requireContext())
                setHasFixedSize(true)
                itemAnimator = null // ХЗ НАДО ЛИ
            }
        }

        viewModel.words.observe(viewLifecycleOwner) {
            vocabularyAdapter.submitList(it)
        }

        setHasOptionsMenu(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_choose_all_categories -> {
                viewModel.onChooseCategoryClick(0)
                // HERE I NEED TO call the recycler view and make it scroll to the top to the 1st position
                true
            }
            //other items ...

java – Layout Inflater com bug, pela Classe Adapter Android

Desculpe-me pelo texto longo. É assim:

Estou inflando um layout personalizado no clique de um TextView pelo “MyViewHolder holder” utilizando o AlertDialog.Builder implementado em uma classe Adapter.

Infla perfeitamente, sem erros.

O fato é que quando clico no layout inflado para alterar o valor no EditText, normalmente com um clique de velocidade média, o App simplesmente fecha. Coloquei tudo em um bloco try/catch, mesmo assim não mostra o erro. Se eu clico e seguro um pouco ele aceita (nem sempre), não fecha e a ação, quando confirmo no botão do AlertDialog, é executada sem problemas.

Tentei depurar e todos os valores são preenchidos corretamente. Não traz exceções.

E normalmente é no primeiro click depois que carrega o App após um período inativo ou na primeira execução. Aí o App fecha, eu abro novamente e depois segue mais firme, sem erros constantes, mas, ainda ocorrendo um ou outro. Como se faltasse carregar algo completamente!

Observando mais minuciosamente, está sendo inflado pela classe Adapter e os erros só ocorrem nas classes Fragments, quando são chamados e clicados. Nas Activity`s não ocorre o fechamento.

Não poderia inflar pelo recycler, pois, são muitos fragments e eu teria que implementar em cada um.

Obs. Eu inflo por um clique na Imagem do adapter (uma ação) e no textView do adapter (outra ação) = carrinho e favoritos que funcionam em conjunto, mas, com ações distintas..

Alguém teria uma maneira ou um recurso diferente que possa me ajudar à resolver isto? O mais detalhado possível, pois, não tenho muito habilidade ainda.

Desde já fico muito grato.

Abaixo foram as tentativas que eu fiz e todas funcionam. É só a questão do bug de clique mesmo:

01- import androidx.appcompat.app.AlertDialog;
 
ou
 
02- import android.app.AlertDialog;

03-
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.dialog_Solicitacao, null, false);

builder.setView(view); 

 
04-
View view = View.inflate(context,R.layout.dialog_Solicitacao,null);
 
builder.setView(view); 

 
05-

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Solicitação");
builder.setMessage("Digite o valor");

EditText editValor = new EditText(context);

builder.setView(editValor);

LAYOUT ORIGINAL INFLADO PELA CLASSE ADAPTER

    try{    
        // >>> Caixa de diálogo
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        // builder = construtor
        builder.setTitle("Carrinho");
        builder.setMessage("Exemplo: 2 (igual à 2UN)");
        builder.setIcon(R.drawable.logo_marca);
            
        //LayoutInflater inflater = LayoutInflater.from(context);
        //View viewQuantidade = inflater.inflate(R.layout.dialog_quantidade_car, null, false);
        
        // ou
        
        //View viewQuantidade = LayoutInflater.from(context).inflate(R.layout.dialog_quantidade_car, null);
        
        // ou
        
        View viewQuantidade = View.inflate(context,R.layout.dialog_quantidade_car,null);
                        
        editQuantidade = viewQuantidade.findViewById(R.id.editText_DialogQteCar_Quantidade);
        editQuantidade.setText("1"); // Já recebe um valor padrão
        editQuantidade.requestFocus();    
        editQuantidade.selectAll(); // Para focar e selecionar
        
        TextView textUnidade =  viewQuantidade.findViewById(R.id.textView_DialogQteCar_Unidade);
        textUnidade.setText("Unidade");
        
        TextView textObserv =  viewQuantidade.findViewById(R.id.textView_DialogQteCar_Observacao);
        textObserv.setText(textObserv.getText()); // Texto padrão do Layout
                        
        builder.setView(viewQuantidade);

        builderUp.setPositiveButton("Confirmar", new DialogInterface.OnClickListener(){...
            closeKeyboard()

        builderUp.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {...
            closeKeyboard()

        AlertDialog dialogUp = builderUp.create(); // Criar
        dialogUp.show(); // Exibir
        showKeyboard();

private void showKeyboard(){...

private void closeKeyboard(){...

What is needed to have an Android app as a copy for test mode

Is there a way to have same app twice on same device using some simple patch?

  1. One copy is current version downloaded from the store
  2. A testing copy is an APK coming out of a CI/CD system (built using React Native)

What I have tried so far:

  • Replace app name in the source file src/main/res/values/strings.xml; but on one device the copy replaces the original, on another device the install routing reports a general error without further detail.

Android SD card encryption – Android Enthusiasts Stack Exchange


Your privacy


By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




storage – Is it possible to backup data from a locked android phone?

is it possible to get files from a locked android phone with PC ? I searched the entire internet but couldn’t get any reliable source. Although i can simply hard reset the phone to bypass the lock, but the data inside is really important to me. I want to try adb command to remove the pin lock but unfortunately i didn’t turn on the usb debugging .. Anyone have any ideas on this?

Info
My phone model: Vivo 7 Plus
USB debugging: Not turned on

applications – How to enable/disable “ELF” load on Android

Sir,
I have a online game(pubg),in pubg application have some native library(ELF file).when I am run the game it will decompress and load all librarys in runtime game memory so I want to disable load librarys in game memory that’s all it means I want game don’t check her runtime memories..

Android Studio – datos no se muestran en recyclerview

Estoy creando una aplicación donde la página principal está dividida en 2 tabs. Quiero mostrar los datos de un JSON, he probado en otro proyecto (poniendo todo en el main, sin tabs ni en fragmentos), y muestra los datos correctamente. El problema viene cuando intento hacer lo mismo en un fragmento.

No veo el problema por ningún lado, he consultado y mirado por diferentes sitios, pero sigo sin encontrar el error, al lanzar la aplicación el tab donde debería de aparecer la información se muestra vacío.

El Log muestra los nombres e imágenes del JSON correctamente, así que el error creo que es a la hora de intentar mostrarlos.

SurvisFragment:

@Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment_personajes_survis, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(SurvisViewModel.class);
        // TODO: Use the ViewModel

        configView();
    }

    private void configView()
    {
        initializeComponents();
        getSurvis("https://api.npoint.io/840b16c025f4b9eaa1f0");
    }

    private void initializeComponents()
    {
        recyclerView = getActivity().findViewById(R.id.recyclerViewPersonajes);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
    }

    private void getSurvis(String url)
    {
        pd = new ProgressDialog(getContext());
        pd.setMessage("Cargando personajes...");
        pd.show();

        StringRequest request = new StringRequest(Request.Method.GET, url, new com.android.volley.Response.Listener<String>()
        {
            @Override
            public void onResponse(String response)
            {
                pd.dismiss();

                try
                {
                    JSONObject object = new JSONObject(response);
                    JSONArray array = object.getJSONArray("personajes");
                    for (int i = 0; i < array.length(); i++)
                    {
                        JSONObject object1 = array.getJSONObject(i);
                        if (object1.getString("Tipo").equals("Superviviente"))
                        {
                            data.add(
                                    new Personaje(
                                            object1.getString("Nombre"),
                                            object1.getString("Imagen")
                                    )
                            );

                            Log.e("PERSONAJES ", data.get(i).getNombre() + " - " + data.get(i).getImagen());

                        }
                    }

                    setPersonajes(data);

                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                pd.dismiss();
                Log.e("ERROR", "Error occurred " + error.getMessage());
            }
        });

        Volley.newRequestQueue(mContext).add(request);

    }

    private void setPersonajes(ArrayList<Personaje> data)
    {
        Log.i("ELEMENTOS", "Elementos a cargar " + data.size());
        personajesAdapter = new PersonajesAdapter(mContext, data);
        personajesAdapter.notifyDataSetChanged();
        recyclerView.setAdapter(personajesAdapter);
    }

PersonajesAdapter:

public class PersonajesAdapter extends RecyclerView.Adapter<PersonajesAdapter.ViewHolder>
{
    Context context;
    ArrayList<Personaje> data;

    public PersonajesAdapter(Context context, ArrayList<Personaje> data)
    {
        this.context = context;
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.fragment_personajes, null));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position)
    {
        Glide.with(context).asBitmap().load(data.get(position).getImagen()).into(holder.image);

        holder.name.setText(data.get(position).getNombre());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder
    {
        ImageView image;
        TextView name;

        public ViewHolder(@NonNull View itemView)
        {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            name = itemView.findViewById(R.id.name);
        }
    }

    public Context getContext()
    {
        return context;
    }

    public void setContext(Context context)
    {
        this.context = context;
    }

    public ArrayList<Personaje> getData()
    {
        return data;
    }

    public void setData(ArrayList<Personaje> data)
    {
        this.data = data;
    }

fragment_personajes_survis.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:theme="@style/Theme.MaterialComponents.Light"
    app:cardCornerRadius="7dp"
    app:cardElevation="4dp"
    android:padding="7dp">

    <LinearLayout
        android:id="@+id/layoutProducto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardCornerRadius="8dp">

            <ImageView
                android:id="@+id/image"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:scaleType="centerCrop" />

        </androidx.cardview.widget.CardView>

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/image"
            android:layout_marginTop="10dp"
            android:ellipsize="end"
            android:lines="2"
            android:text="DWIGHT FAIRFIELD"
            android:textAlignment="center"
            android:textColor="#363636"
            android:textSize="14sp"
            android:textStyle="bold" />

    </LinearLayout>

</com.google.android.material.card.MaterialCardView>

applications – Can’t authorise android lenovo tablet in USB debugging mode

I have Lenovo YOGA Tablet 2 830LC X86.

Rescue and Smart Assistant tool is a software to work with this tablet.
When i activate USB-Debugging in tablet i face the error below in Rescue and Smart Assistant tool.

Unauthorized

Unauthorized is because after activating USB-Debugging mode in tablet and connecting my tablet to PC, there is no popup asking me if i want to trust this PC, which i have to agree (permanently).

By deleting the adbkey file found in C:Users(Username).android folder the permission dialog did n’t appear on my device.

What should i do to fix this issue?

Android Studio IDE: I want to prevent the last executed Gradle task from being default run configuration

I have a custom gradle task that clean, build and copy the output apk to a certain location to release the apk to my customers.

However, every time I run the custom gradle task, the run configuration of Android Studio IDE is changed to that gradle task.

For example,

enter image description here

This is changed as the following picture after running the task.
(In this picture I use gradle clean for example)

enter image description here

Thus, if I forgot to change back the configuration to default app module and ‘run (Shift + F10 in Windows)’, the task is running again unexpectedly and it struck me.

After an hour of googling, I couldn’t found a solution for this. Is there a way to prevent this behavior?

reverse proxy – MTLS on the cheap that works on Android clients?

Is there a way to pull off MTLS/Two-Way SSL/Client Certificates that work on unrooted v10+ Android Clients on the cheap?

I’ve done the whole private setup with OpenSSL and it works absolutely fantastic with the lone exception of 3rd-Party Android Apps that use the default network security setting of only allowing system trust stores and ignore user trust stores. I’m sure there will be a valid reason for that being the default because of security and MITM exposure?

If you can only do it with public well-known root CA’s can you do it with a cheap DV then do your own CSR and generate your own client certs?

Setting up OpenVPN service and making tunnels seems like overkill in comparison?

Cheers