0

Estoy haciendo una App donde muestro un catálogo de productos. Cada vez que entro en una, selecciono un producto cualquiera me salta un NullPointerException cuando lo que debería ocurrir es que pase del fragment con la lista de productos al fragment con el detalle del objeto seleccionado.

////ERROR////

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.usuario.alfapharmashop, PID: 4634
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.usuario.alfapharmashop.Interfaces.IComunicaFragments.enviarIdProducto(int)' on a null object reference
        at com.example.usuario.alfapharmashop.Fragments.GaleriaProductosFragment$1.onClick(GaleriaProductosFragment.java:186)
        at com.example.usuario.alfapharmashop.Adapters.ProductosAdapter.onClick(ProductosAdapter.java:59)
        at android.view.View.performClick(View.java:6312)
        at android.view.View$PerformClick.run(View.java:24811)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:171)
        at android.app.ActivityThread.main(ActivityThread.java:6651)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
I/Process: Sending signal. PID: 4634 SIG: 9
Application terminated.

Dejo las clases involucradas en el proceso

////////////////
//MainActivity//
////////////////

    package com.example.usuario.alfapharmashop.Interfaces;

    import android.support.v4.app.FragmentManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.design.widget.NavigationView;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;

    import com.example.usuario.alfapharmashop.Fragments.CarritoFragment;
    import com.example.usuario.alfapharmashop.Fragments.DetallesProductoFragment;
    import com.example.usuario.alfapharmashop.Fragments.GaleriaCategoriaFragment;
    import com.example.usuario.alfapharmashop.Fragments.GaleriaProductosFragment;
    import com.example.usuario.alfapharmashop.Fragments.PerfilFragment;
    import com.example.usuario.alfapharmashop.R;

    public class MainActivity extends AppCompatActivity
           implements 

 NavigationView.OnNavigationItemSelectedListener,GaleriaCategoriaFragment.OnFrag
  mentInteractionListener, GaleriaProductosFragment.OnFragmentInteractionListener,
           PerfilFragment.OnFragmentInteractionListener, 
   CarritoFragment.OnFragmentInteractionListener, 
   DetallesProductoFragment.OnFragmentInteractionListener , IComunicaFragments{

    public static FragmentManager fragmentManager;

    GaleriaCategoriaFragment fragmentGaleria = null;
    PerfilFragment fragmentPerfil = null;
    CarritoFragment fragmentCarrito = null;
    GaleriaProductosFragment fragmentGaleriaProductos = null;
    DetallesProductoFragment fragmentDetalleProducto = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        fragmentManager = getSupportFragmentManager();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();


        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //elimina el color negro en los iconos del menĂº
        navigationView.setItemIconTintList(null);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        Boolean fragmentoGaleriaSelec = false;
        Boolean fragmentoCarritoSelec = false;
        Boolean fragmentoPerfilSelec = false;

        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_perfil) {

            fragmentPerfil = new PerfilFragment();
            fragmentoPerfilSelec = true;
        } else if (id == R.id.nav_productos) {

            fragmentGaleria = new GaleriaCategoriaFragment();
            fragmentoGaleriaSelec = true;

        } else if (id == R.id.nav_carrito) {

            fragmentCarrito = new CarritoFragment();
            fragmentoCarritoSelec = true;

        } else if (id == R.id.nav_config) {


        }

        if(fragmentoGaleriaSelec==true){
            getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragmentGaleria).addToBackStack(null).commit();
        }else if(fragmentoCarritoSelec==true){
            getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragmentCarrito).addToBackStack(null).commit();
        }else if(fragmentoPerfilSelec==true){
            getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragmentPerfil).addToBackStack(null).commit();

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void enviarNombreCategoria(String categoria){
        fragmentGaleriaProductos= new GaleriaProductosFragment();

        Bundle bundle = new Bundle();
        bundle.putString("categoriaProductos",categoria);
        fragmentGaleriaProductos.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragmentGaleriaProductos).addToBackStack(null).commit();

    }

    @Override
    public void enviarIdProducto(int id) {
        fragmentDetalleProducto = new DetallesProductoFragment();

        Bundle bundle = new Bundle();
        bundle.putInt("productoDetalle", id);
        fragmentDetalleProducto.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_main, fragmentDetalleProducto).addToBackStack(null).commit();
    }
}

//////////////////////////////// //INTERFACE IComunicaFragments// ////////////////////////////////

package com.example.usuario.alfapharmashop.Interfaces;

public interface IComunicaFragments {
    void enviarNombreCategoria(String categoria);
    void enviarIdProducto(int id);
}

//////////////////////////// //GaleriaProductosFragment// ////////////////////////////

    package com.example.usuario.alfapharmashop.Fragments;

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.GridLayout;
    import android.widget.Toast;

    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.example.usuario.alfapharmashop.Adapters.ProductosAdapter;
    import com.example.usuario.alfapharmashop.Adapters.VolleySingleton;
    import com.example.usuario.alfapharmashop.Entidades.Producto;
    import com.example.usuario.alfapharmashop.Interfaces.IComunicaFragments;
    import com.example.usuario.alfapharmashop.R;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;


    public class GaleriaProductosFragment extends Fragment implements 
    Response.ErrorListener, Response.Listener<JSONObject> {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    public static IComunicaFragments comunicaFragments;
    private RecyclerView recyclerProductos;
    private ArrayList<Producto> listaProductos;
    private ProgressDialog dialog;
    private String nombreCat;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;



    // RequestQueue request;
    JsonObjectRequest jsonObjectRequest;
    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment GaleriaProductosFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static GaleriaProductosFragment newInstance(String param1, String param2) {
        GaleriaProductosFragment fragment = new GaleriaProductosFragment();
        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) {
        View vista= inflater.inflate(R.layout.fragment_galeria_productos, container, false);

        listaProductos=new ArrayList<>();

        Bundle bundleNombreCategoria=getArguments();

        if (bundleNombreCategoria != null) {
            nombreCat = bundleNombreCategoria.getString("categoriaProductos");
        }

        recyclerProductos = (RecyclerView) vista.findViewById(R.id.idRecyclerImagen);
        recyclerProductos.setLayoutManager(new GridLayoutManager(this.getContext(), 2));

        cargarWebService(nombreCat);


        return vista;
    }

    private void cargarWebService(String categoria) {

        dialog=new ProgressDialog(getContext());
        dialog.setMessage("Cargando "+ categoria);
        dialog.incrementProgressBy(100);
        dialog.show();

        String url="https://alfapharma.000webhostapp.com/mostrarProductos.php?categoria=" + categoria;
        jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
        // request.add(jsonObjectRequest);
        VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
    }



    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onErrorResponse(VolleyError error) {

    }

    @Override
    public void onResponse(JSONObject response) {
        Producto producto=null;

        JSONArray json=response.optJSONArray("producto");

        try {

            for (int i=0;i<json.length();i++){
                producto = new Producto();
                JSONObject jsonObject=null;
                jsonObject=json.getJSONObject(i);

                producto.setId(jsonObject.optInt("id"));
                producto.setNombre(jsonObject.optString("nombre"));
                producto.setDato(jsonObject.optString("img"));
                listaProductos.add(producto);
            }
            dialog.hide();
            ProductosAdapter adapter=new ProductosAdapter(listaProductos);

            adapter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    Toast.makeText(getContext(),listaProductos.get(recyclerProductos.getChildAdapterPosition(view)).getNombre()+"",Toast.LENGTH_SHORT).show();

                    comunicaFragments.enviarIdProducto(listaProductos.get(recyclerProductos.getChildAdapterPosition(view)).getId());

                }
            });

            recyclerProductos.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "No se ha podido establecer conexión con el servidor" +
                    " "+response, Toast.LENGTH_LONG).show();
            dialog.hide();
        }
    }

/**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

//////////////////////////// //DetallesProductoFragment// ////////////////////////////

package com.example.usuario.alfapharmashop.Fragments;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.usuario.alfapharmashop.Adapters.VolleySingleton;
import com.example.usuario.alfapharmashop.Entidades.Producto;
import com.example.usuario.alfapharmashop.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DetallesProductoFragment extends Fragment implements 
Response.ErrorListener, Response.Listener<JSONObject>{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

private int idProducto;
private ImageView campoImagen;
private TextView nombreProducto;
private TextView pesoProducto;
private TextView precioProducto;
private TextView unidadesxcajaProducto;
private TextView descripcionProducto;

ProgressDialog dialog;

// RequestQueue request;
JsonObjectRequest jsonObjectRequest;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment DetallesProductoFragment.
 */
// TODO: Rename and change types and number of parameters
public static DetallesProductoFragment newInstance(String param1, String param2) {
    DetallesProductoFragment fragment = new DetallesProductoFragment();
    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) {
    // Inflate the layout for this fragment
    View vista = inflater.inflate(R.layout.fragment_detalles_producto, container, false);

    nombreProducto = (TextView) vista.findViewById(R.id.nombreDetalle);
    descripcionProducto= (TextView) vista.findViewById(R.id.descripcionDetalle);
    pesoProducto= (TextView) vista.findViewById(R.id.pesoDetalle);
    precioProducto= (TextView) vista.findViewById(R.id.precioDetalles);
    unidadesxcajaProducto= (TextView) vista.findViewById(R.id.unidadesxCajaDetalle);
    campoImagen = (ImageView) vista.findViewById(R.id.imagenDetalle);

    Bundle bunfleIdItem=getArguments();

    if (bunfleIdItem != null) {
        idProducto = bunfleIdItem.getInt("productoDetalle");
    }

    cargarWebService(idProducto);
    return vista;
}

private void cargarWebService(int id) {

    dialog=new ProgressDialog(getContext());
    dialog.setMessage("Buscando producto...");
    dialog.incrementProgressBy(100);
    dialog.show();

    String url="https://alfapharma.000webhostapp.com/mostrarDetalleProducto.php?id="+id;

    jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
    // request.add(jsonObjectRequest);
    VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
}


// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onErrorResponse(VolleyError error) {
    dialog.hide();
    Toast.makeText(getContext(),"No se pudo Consultar "+error.toString(),Toast.LENGTH_SHORT).show();
    Log.i("ERROR",error.toString());
}

@Override
public void onResponse(JSONObject response) {

    dialog.hide();

    //    Toast.makeText(getContext(),"Mensaje: "+response,Toast.LENGTH_SHORT).show();

    Producto producto=new Producto();

    JSONArray json=response.optJSONArray("detalleProductos");
    JSONObject jsonObject=null;

    try {
        jsonObject=json.getJSONObject(0);

        producto.setNombre(jsonObject.optString("nombre"));
        producto.setDescripcion(jsonObject.optString("descripcion"));
        producto.setPeso(jsonObject.optInt("peso"));
        producto.setPrecio(jsonObject.getLong("precio"));
        producto.setUnidadesxcaja(jsonObject.getInt("unidadesxcaja"));


        producto.setDato(jsonObject.optString("img"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    nombreProducto.setText(producto.getNombre());
    descripcionProducto.setText(producto.getDescripcion());
    precioProducto.setText(producto.getPrecio()+" €");
    pesoProducto.setText(producto.getPeso()+ " gr");
    unidadesxcajaProducto.setText(producto.getUnidadesxcaja()+ "Unds/caja");


    if (producto.getImagen()!=null){
        campoImagen.setImageBitmap(producto.getImagen());
    }else{
        campoImagen.setImageResource(R.drawable.nodisponible);
    }
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

1 respuesta 1

0

En GaleriaProductosFragment tu IComunicaFragments es null. Como es un fragment, y la implementacion esta en tu activity deberias agregar esto:

comunicaFragments = (IComunicaFragments) getActivity();
3
  • En el onAttach()? Creo que has dado con la tecla, la típica tontería de turno que te come todo el tiempo. Cuando esté en casa lo pruebo y te comento. el 26 nov. 2018 a las 16:46
  • yo suelo ponerlo en el onAttach, pero me parece que en el oncreate o algun otra parte del ciclo de vida tambien funciona ;), pero depende donde mandes a llamar la interfaz, suerte, y avisa si es que funciono el 26 nov. 2018 a las 16:48
  • Muchas gracias amigo, era lo que fallaba. Que coraje fallar en estas tonterías! te doy tu upvote :) el 26 nov. 2018 a las 21:43

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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