Tengo una vista de reciclaje, quiero que se abra un nuevo fragmento mientras hago clic en el elemento en la vista de reciclaje. getActivity () devuelve nulo cuando accedo a él en el método onCreateView, aunque cuando accedo desde el método onItemClick para pasar a otro fragmento, devuelve una excepción de puntero nulo.

public class DailyMenuFrag extends Fragment implements 

    DailyDataAdapter.onItemClickListener {

            private List<DailyData> daily_data_list;
            public List<DailyData> popular_data_list;
            DailyDataAdapter adapter = null;
            Activity activity;

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                daily_data_list = new ArrayList<>();
                popular_data_list = new ArrayList<>();
                load_data();
                View view = inflater.inflate(R.layout.fragment_daily_menu, container, false);
                RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);

                adapter = new DailyDataAdapter(getActivity(), daily_data_list);
                if(getActivity() == null){
                    Log.i("info","null");
                }
                else Log.i("info","notnull");
                adapter.setOnItemClickListner(new DailyMenuFrag());
                recyclerView.setAdapter(adapter);

                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2);
                recyclerView.setLayoutManager(gridLayoutManager);

                return view;
            }

            public void load_data() {
                task.execute("http://yemekapp.kuarkdijital.com.tr/home.php");
            }
                AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {

                    @Override
                    protected String doInBackground(String... params) {

                        URL url;
                        HttpURLConnection URLConnection = null;
                        String current = "";

                        try {
                            url = new URL(params[0]);

                            URLConnection = (HttpURLConnection) url.openConnection();
                            URLConnection.connect();

                            InputStream inputStream = URLConnection.getInputStream();

                            InputStreamReader reader = new InputStreamReader(inputStream);

                            int data = reader.read();

                            while (data != -1) {
                                current += (char) data;
                                data = reader.read();
                            }

                            JSONObject dailyObject = null;
                            JSONObject popularObject = null;

                            JSONObject jsonObject = new JSONObject(current);
                            JSONObject banner = jsonObject.getJSONObject("banner");

                            String daily = jsonObject.getString("daily");
                            String popular = jsonObject.getString("popular");

                            JSONArray dailyArray = new JSONArray(daily);
                            JSONArray popularArray = new JSONArray(popular);

                            for (int i = 0; i < dailyArray.length(); i++) {

                                dailyObject = dailyArray.getJSONObject(i);
                                popularObject = popularArray.getJSONObject(i);

                                DailyData DailyData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
                                DailyData PopularData = new DailyData(popularObject.getInt("id"), popularObject.getString("Servings"), popularObject.getString("Title"), popularObject.getString("CookTime"), popularObject.getString("Image"));
                                daily_data_list.add(DailyData);
                                popular_data_list.add(PopularData);
                                }

                            }
                            catch (JSONException e) {
                                e.printStackTrace();
                            }
                            catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                 e.printStackTrace();
                        }

                        return current;
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        adapter.notifyDataSetChanged();


                    }
                };
            @Override
            public void onAttach(Activity activity) {
                super.onAttach(activity);
                this.activity = activity;
            }

            @Override
            public void onItemClick(int position) {
                Log.i("info","clicked");
                if(getActivity() == null){
                    Log.i("info","null");//why it is null here
                }
                else Log.i("info","notnull");
                DetailViewPager detailViewPager = new DetailViewPager();
        //        FragmentManager manager = getActivity().getSupportFragmentManager();
        //        FragmentTransaction transaction = manager.beginTransaction();
        //        transaction.replace(R.id.fragment_container,detailViewPager);
        //        transaction.commit();
            }
        }
   }

Error de registro

02-22 08:49:26.186 20849-20849/com.nejat.yemektarifiproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.nejat.yemektarifiproject, PID: 20849
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
                                                                                  at com.nejat.yemektarifiproject.DailyMenuFrag$override.onItemClick(DailyMenuFrag.java:151)
                                                                                  at com.nejat.yemektarifiproject.DailyMenuFrag$override.access$dispatch(DailyMenuFrag.java)
                                                                                  at com.nejat.yemektarifiproject.DailyMenuFrag.onItemClick(DailyMenuFrag.java:0)
                                                                                  at com.nejat.yemektarifiproject.DailyDataAdapter$ViewHolder$1.onClick(DailyDataAdapter.java:79)
                                                                                  at android.view.View.performClick(View.java:5637)
-8
Nejweti 22 feb. 2018 a las 11:41

2 respuestas

La mejor respuesta
 adapter.setOnItemClickListner(new DailyMenuFrag());

El new DailyMenuFrag() aquí es un nuevo fragmento y no está adjunto a ninguna actividad y por lo tanto getActivity() devuelve un valor nulo.

Parece que deberías usar

adapter.setOnItemClickListner(this);

En su lugar, utilizar la instancia DailyMenuFrag actual como oyente de clics en el elemento.

1
laalto 22 feb. 2018 a las 09:46

Parece que onPostExecute () de loadData () (AsyncTask) está notificando al adaptador antes de su inicialización.

            load_data();
            View view = inflater.inflate(R.layout.fragment_daily_menu, container, false);
            RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);

            adapter = new DailyDataAdapter(getActivity(), daily_data_list);
0
mnp343 22 feb. 2018 a las 09:33