0

Tengo una app en android que contiene un recycler en un fragment, entonces al dar click a un item del recycler debo pasar datos a otro fragment. El problema es que lleno el recycler desde un webservice con volley y mi app no hace nada, pero si lleno el recycler manualmente (lo hice solo para hacer la prueba) la app funciona bien, alguien sabe porque pasa esto y como se soluciona? Gracias

Fragment

public class Inicio extends Fragment implements Response.Listener<JSONArray>,Response.ErrorListener{
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    public static final int MY_DEFAULT_TIMEOUT = 15000;

    ArrayList<MyModel> lista;
    RecyclerView recyclerView;
    Activity activity;
    IFragments interface_frag;
    DataAdapter dataAdapter;
    ProgressDialog progressDialog;
    RequestQueue request;
    JsonArrayRequest jsonArrayRequest;
    conexion con;
    SQLiteDatabase bd;
    BD.Utilidades.MyModel _mymodel;
     

    public Inicio() {
        // Required empty public constructor
    }

    public static Inicio newInstance(String param1, String param2) {
        Inicio fragment = new Inicio();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_inicio, container, false);
        lista=new ArrayList<>();
        recyclerView= (RecyclerView) rootView.findViewById(R.id.list_m);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        con = new conexion(getContext());
        request = Volley.newRequestQueue(getContext());
        new cargar_data().execute();

        dataAdapter = new DataAdapter(lista);
        recyclerView.setAdapter(dataAdapter);
        
//este codigo no hace nada cuando lleno el recycler desde volley
        dataAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),"Seleccion: "+
                        lista.get(recyclerView.
                                getChildAdapterPosition(view)).getNombre(),Toast.LENGTH_SHORT).show();
                interface_frag.solicitud(lista.get(recyclerView.getChildAdapterPosition(view)));
            }
        });
        return rootView;
    }    
  
    public class cargar_data extends AsyncTask<String, Integer,String> {

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            try{
                //llenarLista();
                mostrar_lista();                
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return "Finalizo la tarea";        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.e("Terminado", result);
        }
    }

//aqui lleno mi modelo con volley
    private void llenarLista() {
        Entidades.MyModel mymodel = null;

        int Id = 1;
        String Nombre = "CHRISTIAN";
        ...etc        

         mymodel = new MyModel(Id, Nombre, etc...);

        bd = con.getReadableDatabase();
        String[] par = {String.valueOf(Id)};
        String[] campos = {_mymodel.};
        Cursor cursor = bd.query(_mymodel.MyTabla, campos, _mymodel.Id + "=?", par, null, null, null);

        if (!cursor.moveToFirst()) {
            bd.close();
            bd = con.getWritableDatabase();
            con.isertModel(Id, Nombre, etc...);
            bd.close();
        }
        cursor.close();
        bd.close();
        lista.add(_mymodel);
    }

//aqui lo lleno desde volley
    private void mostrar_lista() {
        try {
            int id = getFromSharedPref("Id");
            bd = con.getReadableDatabase();
            String[] par = {String.valueOf(id)};
            String[] campos = {MyModel.Id, etc...};

            Cursor cursor = bd.query(_mymodel.MyTabla, campos, _mymodel.Id + "=?", par, null, null, null);  
             int id = 0;

            if (cursor.moveToFirst()) {
                id = cursor.getInt(0);                

                String url = "http://www.xxx.mx/yyy/zzz.svc/GetAllData/" + id + "";
                url = url.replace(" ", "%20");

                jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, this, this);
                jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(MY_DEFAULT_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                request.add(jsonArrayRequest);
            } else {
                Toast.makeText(getContext(), "No se encontraron datos", Toast.LENGTH_SHORT).show();
            }
            cursor.close();
            bd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int getFromSharedPref(String id) {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Login_pref", getContext().MODE_PRIVATE);
        return sharedPreferences.getInt(id, 0);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(getContext(), "ERROR " + error.toString(), Toast.LENGTH_SHORT).show();
        System.out.println();
        Log.d("ERROR ", error.toString());
    }

    @Override
    public void onResponse(JSONArray response) {
        Entidades.MyModel mymodel = null;

        if (response != null) {
            try {
                for (int i = 0; i < response.length(); i++) {

                    JSONObject jsonObject = null;
                    jsonObject = response.getJSONObject(i);

                    int Id = jsonObject.optInt("Id");
                    String Nombre = jsonObject.optString("Nombre");
                    ...etc

                    mymodel = new Entidades.MyModel(Id, Nombre, etc...);

                    bd = con.getReadableDatabase();
                    String[] par = {String.valueOf(Id)};
                    String[] campos = {_mymodel.Id,etc...};
                    Cursor cursor = bd.query(_mymodel.Tabla, campos, _mymodel.Id + "=?", par, null, null, null);

                    if (!cursor.moveToFirst()) {
                        bd.close();
                        bd = con.getWritableDatabase();
                        con.insert(Id, Nombre, etc);
                        bd.close();
                    }

                    cursor.close();
                    bd.close();

                    lista.add(mymodel);
                }
                DataAdapter dataAdapter = new DataAdapter(lista);
                recyclerView.setAdapter(dataAdapter);
            } catch (JSONException e) {
                Toast.makeText(getContext(), "Error: " + e.toString(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();               
            }
        } else {
            Toast.makeText(getContext(), "No se encontraron datos", Toast.LENGTH_SHORT).show();
        }
    }

}

Gracias

1 respuesta 1

-1

Creo que todo lo tiene en un solo lugar y deberias de separlo el adatador por aparte para que sea escuchado por tu actividad

dataAdapter.setOnClickListener(new View.OnClickListener() 

esta funcion te recomiendo hacerla por fuera y alla que regrese aqui te dirijo a una buena pagina que me sirvio mucho

https://android.jlelse.eu/click-listener-for-recyclerview-adapter-2d17a6f6f6c9

1
  • hola así es como lo tengo y no funciona
    – sunflower
    el 18 abr. 2020 a las 16:53

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.