Error in Snack bar: Attempt to invoke virtual method

1

I'm trying to show a Snack bar in a fragment but it gives me the following error:

  

Attempt to invoke virtual method 'android.view.View   android.app.Activity.findViewById (int) 'on a null object reference

This error happens when I want to show my Snack bar through a button, I do not understand why the error happens, this is my Snack bar code:

public void desplegar() {
        Snackbar snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content),
                "Se ha añadido a tus favoritos", Snackbar.LENGTH_LONG).setAction(getString(R.string.verfav), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.qwe, new Favoritos());
                transaction.commit();
            }
        });
        //ACTION
        snackbar.setActionTextColor(getResources().getColor(R.color.textoblanco));
        View snackBarView = snackbar.getView();
        //BACKGROUND
        snackBarView.setBackgroundColor(getResources().getColor(R.color.toolbar));
        //MESSAGE
        TextView mensaje = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
        mensaje.setTextColor(getResources().getColor(R.color.textoblanco));

        snackbar.show();
    }

I already tried different ways but they did not work for me, I do not know why that error is shown, this is my complete code:

public class Inicio extends Fragment implements noticiasAdapter.OnEventMovieListener, Response.Listener<JSONObject>, Response.ErrorListener{

    RecyclerView recyclerView;
    private List<Noticias> noticias;
    private noticiasAdapter noticiasadapter;
    public static final String TAG = Noticias.class.getName();

    RequestQueue request;
    JsonObjectRequest jsonObjectRequest;

    Context context;

    public Inicio(){

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.inicio, container, false);
        recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view);

        noticias = new ArrayList<>();
        noticiasadapter = new noticiasAdapter(noticias);
        noticiasadapter.setOnEventMovieListener(this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        request = Volley.newRequestQueue(getActivity());
        cargarWebService();

        return view;
    }

    private void cargarWebService() {

        String url = "http://192.168.1.72:80/webservicemgrex/listaNoticias.php";
        jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
        request.add(jsonObjectRequest);
    }

    @Override
    public void onResponse(JSONObject response) {
        Noticias news = null;
        JSONArray json = response.optJSONArray("inicio");

        try{
            for (int i=0; i<json.length(); i++){
                news = new Noticias();
                JSONObject jsonObject = null;
                jsonObject = json.getJSONObject(i);

                news.setIdNoticia(jsonObject.optInt("idNoticia"));
                news.setTituloNoticia(jsonObject.optString("tituloNoticia"));
                news.setSubtituloNoticia(jsonObject.getString("subtituloNoticia"));
                news.setImagenNoticia(jsonObject.getString("imagenNoticia"));
                news.setDescripcionNoticia(jsonObject.getString("descripcionNoticia"));
                noticias.add(news);
            }

            noticiasAdapter adapter = new noticiasAdapter(noticias);
            recyclerView.setAdapter(adapter);
            noticiasadapter.notifyDataSetChanged();

        }catch (JSONException e){
            Toast.makeText(getActivity(),"Error al cargar la informacion del servidor: "+e, Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(getActivity(),"No se pudo consultar los registros: "+error.toString(), Toast.LENGTH_LONG).show();
        Log.i("Error","No se pudo consultar el registro: "+error.toString());
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //Revisar este bloque

    @Override
    public void vistaDetalle(String tituloNoticia, String subtituloNoticia, String imagenNoticia, String descripcionNoticia) {
        Intent intent = new Intent(getActivity(), DescripcionNoticias.class);
        intent.putExtra("titulon",tituloNoticia);
        intent.putExtra("descripcionn", descripcionNoticia);
        intent.putExtra("imagen", imagenNoticia);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.left_in, R.anim.left_out);
        }


    public void desplegar() {
        Snackbar snackbar = Snackbar.make(getActivity().findViewById(android.R.id.content),
                "Se ha añadido a tus favoritos", Snackbar.LENGTH_LONG).setAction(getString(R.string.verfav), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.qwe, new Favoritos());
                transaction.commit();
            }
        });
        //ACTION
        snackbar.setActionTextColor(getResources().getColor(R.color.textoblanco));
        View snackBarView = snackbar.getView();
        //BACKGROUND
        snackBarView.setBackgroundColor(getResources().getColor(R.color.toolbar));
        //MESSAGE
        TextView mensaje = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
        mensaje.setTextColor(getResources().getColor(R.color.textoblanco));

        snackbar.show();
    }
}

This is the XML that is loaded in that fragment:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:id="@+id/content"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.enriq.seccion15update.Principal"
    tools:showIn="@layout/app_bar_main">

    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="60dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        tools:context=".Principal">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

and this is my cardview that I post to show the content:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingEnd="16dp"
    android:paddingStart="16dp"
    android:paddingTop="16dp">

    <TextView
        android:id="@+id/tituloNoticia"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:text="@string/tituloNoticia"
        android:fontFamily="sans-serif"
        android:textStyle="bold"
        android:layout_marginBottom="5dp"
        android:textSize="18sp" tools:targetApi="jelly_bean"/>


    <TextView
        android:id="@+id/subtituloNoticia"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:layout_marginBottom="5dp"
        android:text="@string/subitutloNoticias"
        android:textSize="15sp"
        android:fontFamily="sans-serif" tools:targetApi="jelly_bean"/>

    <ImageView
        android:id="@+id/imagenNotica"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:contentDescription="@string/linea_divisora_de_texto_y_video"
        android:scaleType="fitCenter"
        app:srcCompat="@drawable/example" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:clickable="true"
        android:tint="@color/barraestatus"
        app:backgroundTint="@color/textoblanco"
        app:elevation="5dp"
        app:rippleColor="@color/barraestatus"
        app:srcCompat="@drawable/unliked" />

    <TextView
        android:id="@+id/descripcionNoticias"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:text="Descripcion"
        android:maxLines="3"
        android:textAppearance="@style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Small"
        android:textSize="14sp" />

    <Button
        android:id="@+id/showMore"
        style="@android:style/Widget.Material.Button.Borderless"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:shadowColor="@color/barraestatus"
        android:text="Ver nota completa"
        android:textColor="@color/barraestatus"
        android:textStyle="bold"
        android:tint="@color/barraestatus"
        app:backgroundTint="@color/textoblanco" tools:targetApi="lollipop"/>


</LinearLayout>

The deploy method I send to call from this class called noticiasWebService, is just a class that you create to be able to run another webService:

public class noticiasWebService extends AppCompatActivity implements Response.Listener<JSONObject>, Response.ErrorListener {

    RequestQueue request;
    JsonObjectRequest jsonObjectRequest;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
    }

    public void update(String tituloNoticia, String subtituloNoticia, String imagenNoticia, String descripcionNoticia, Context context) {

        String url = "http://192.168.1.72:80/webservicemgrex/agregarFavoritos.php?tituloFavorito="+tituloNoticia+"" +
                "&subtituloFavorito="+subtituloNoticia+
                "&imagenFavorito="+imagenNoticia+
                "&descripcionFavoritos="+descripcionNoticia;

        url = url.replace(" ","%20");
        request = Volley.newRequestQueue(context);
        jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
        request.add(jsonObjectRequest);

        Inicio inicio = new Inicio();
        inicio.desplegar();
    }

    @Override
    public void onResponse(JSONObject response) {
        Log.i("Error","Se haregistrado con exito: "+response);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        Log.i("Error","No se pudo consultar el registro: "+error.toString());
    }
}
    
asked by Enrique Espinosa 29.11.2018 в 00:28
source

2 answers

0

You can use your RecyclerView as a reference point for the SnackBar. For example:

  Snackbar snackbar = Snackbar.make(recyclerView, "Se ha añadido a tus favoritos", Snackbar.LENGTH_LONG); 

What happens is that you look for a view that does not exist in the layout of your activity.

    
answered by 29.11.2018 в 02:28
0

The way to load the Snackbar is correct, but the problem here is that you try to call the desplegar() method that is in a Fragment , this is incorrect

  Inicio inicio = new Inicio();
  inicio.desplegar();

What happens here is that this Fragment has not "been loaded from a Activity " so getActivity() will have a value null .

If you want to call the method to create SnackBar from class Inicio , you must create a static method that receives the root view:

public static void desplegar(View rootView) {
        Snackbar snackbar = Snackbar.make(rootView,
                "Se ha añadido a tus favoritos", Snackbar.LENGTH_LONG).setAction(getString(R.string.verfav), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.qwe, new Favoritos());
                transaction.commit();
            }
        });
        //ACTION
        snackbar.setActionTextColor(getResources().getColor(R.color.textoblanco));
        View snackBarView = snackbar.getView();
        //BACKGROUND
        snackBarView.setBackgroundColor(getResources().getColor(R.color.toolbar));
        //MESSAGE
        TextView mensaje = (TextView) snackBarView.findViewById(android.support.design.R.id.snackbar_text);
        mensaje.setTextColor(getResources().getColor(R.color.textoblanco));

        snackbar.show();
    }
}

and you would call the method from your Activity in this way:

Inicio.desplegar(findViewById(android.R.id.content));

This would show the Snackbar without problem in your Activity

    
answered by 29.11.2018 в 18:03