I have an error with the Toolbar, I do not know why, since the same code I use in another fragment

0

This is the fragment

public class TalleresFragment extends Fragment implements Response.Listener<JSONObject>,Response.ErrorListener {
RecyclerView recyclerTalleres;
ArrayList<DatosTalleres> listaTalleres;
//ProgressDialog progres;
//RequestQueue request;
JsonObjectRequest jsonObjectRequest;
private SharedPreferences pref;



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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_talleres, container, false);
    setHasOptionsMenu(true);
    pref = this.getActivity().getSharedPreferences("Preferences", Context.MODE_PRIVATE);
    showToolbar(getResources().getString(R.string.tab_talleres),false,view);

    listaTalleres=new ArrayList<>();
    recyclerTalleres=view.findViewById(R.id.talleresRecycler);
    recyclerTalleres.setLayoutManager(new LinearLayoutManager(this.getContext()));
    recyclerTalleres.setHasFixedSize(true);
    //request = Volley.newRequestQueue(getContext());

    cargardatos();
    return view;
}

private void cargardatos() {

    /*progres=new ProgressDialog(getContext());
    progres.setMessage("Consultando Datos");
    progres.show();*/
    String url="http://conecit.pe/talleres.json";
    jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
    //request.add(jsonObjectRequest);
    SingletonConecit.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
}
@Override
public void onErrorResponse(VolleyError error) {
    Toast.makeText(getContext(),"no se pudo conectar"+error.toString(),Toast.LENGTH_SHORT).show();
    System.out.println();
    //progres.hide();
    Log.d("Error: ",error.toString());

}

@Override
public void onResponse(JSONObject response) {
    DatosTalleres talleres=null;
    JSONArray json=response.optJSONArray("taller");
    try{
        for (int i=0;i<json.length();i++){
            talleres =new DatosTalleres();
            JSONObject jsonObject=null;
            jsonObject=json.getJSONObject(i);

            talleres.setTituloTaller(jsonObject.optString("tituloTaller"));
            talleres.setPonenteTaller(jsonObject.optString("ponenteTaller"));
            talleres.setDescripcionTaller(jsonObject.optString("descripcionTaller"));
            talleres.setDuracionTaller(jsonObject.optString("duracionTaller"));
            talleres.setPrecioTaller(jsonObject.optString("precioTaller"));
            talleres.setImagenTalleres(jsonObject.optString("imagenTaller"));
            talleres.setFotoPonente(jsonObject.optString("fotoPonente"));
            listaTalleres.add(talleres);

        }
        //progres.hide();

        TalleresAdapterRecyclerview adapter = new TalleresAdapterRecyclerview(listaTalleres,getActivity(),getContext());
        recyclerTalleres.setAdapter(adapter);

    }catch (JSONException e){
        e.printStackTrace();
        Toast.makeText(getContext(),"No se puede conectar"+e.toString(),Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.logout :
            logout();
            //Log.i("item id ", item.getItemId() + "");
        default:
            return super.onOptionsItemSelected(item);
    }
}
private void logout(){
    Intent i = new Intent(getContext(), LoginActivity.class);
    pref.edit().clear().apply();
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);

}


public void showToolbar(String tittle, boolean upButton, View view){
    Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(tittle);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);


}

}

and this is the error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
                  at com.conecit.angelo.conecit2018.fragments.TalleresFragment.showToolbar(TalleresFragment.java:155)
                  at com.conecit.angelo.conecit2018.fragments.TalleresFragment.onCreateView(TalleresFragment.java:66)
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
                  at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
                  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
                  at android.os.Handler.handleCallback(Handler.java:743)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:150)
                  at android.app.ActivityThread.main(ActivityThread.java:5659)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
    
asked by Angelo tapullima del aguila 01.06.2018 в 21:37
source

1 answer

0

The problem can be caused by one of these two situations:

1) You are trying to access the Toolbar before the view is inflated.

2) The fragment_talleres.xml layout that you load in your fragment does not contain a Toolbar with id toolbar , it ensures that the layout actually contains this element.

Both cause the error:

  

java.lang.NullPointerException: support.v7.app.ActionBar.setTitle (java.lang.CharSequence) 'on a null   object reference

Ensure the two previous options to call your method without problem.

    public void showToolbar(String tittle, boolean upButton, View view){
        Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(upButton);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(tittle);    

    }
    
answered by 01.06.2018 в 23:02