-2

This code works fine with activity but not in fragment.. application crash when this run in fragment ...when i delete getData(); below requestQueue application run but data not fetch..

public class LatestFragment extends Fragment {

    //Creating a List of superheroes
    private List<SuperHero> listSuperHeroes;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

    private RequestQueue requestQueue;
    private int requestCount = 1;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View v = inflater.inflate(R.layout.latest, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        //Initializing our superheroes list
        listSuperHeroes = new ArrayList<>();
        requestQueue = Volley.newRequestQueue(getActivity());

        //Calling method to get data to fetch data
       getData();

        //Adding an scroll change listener to recyclerview
        // RecyclerView.setOnScrollChangeListener(this);

          recyclerView.addOnScrollListener(rVOnScrollListener);

        //initializing our adapter
        adapter = new CardAdapter(listSuperHeroes, getActivity());

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);
        return v;
    }

    //Request to get json from server we are passing an integer here
    //This integer will used to specify the page number for the request ?page = requestcount
    //This method would return a JsonArrayRequest that will be added to the request queue
    private JsonArrayRequest getDataFromServer(int requestCount) {
        //Initializing ProgressBar
        final ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progressBar1);

        //Displaying Progressbar
        progressBar.setVisibility(View.VISIBLE);
     //  setProgressBarIndeterminateVisibility(true);

        //JsonArrayRequest of volley
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Calling method parseData to parse the json response
                        parseData(response);
                        //Hiding the progressbar
                        progressBar.setVisibility(View.GONE);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressBar.setVisibility(View.GONE);
                        //If an error occurs that means end of the list has reached
                        //Toast.makeText(citiesdetail.this, "No More Items Available", Toast.LENGTH_SHORT).show();
                    }
                });

        //Returning the request
        return jsonArrayRequest;
    }

    //This method will get data from the web api
    private void getData() {
        //Adding the method to the queue by calling the method getDataFromServer
        requestQueue.add(getDataFromServer(requestCount));
        //Incrementing the request counter
        requestCount++;
    }

    //This method will parse json data
    private void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            //Creating the superhero object
            SuperHero superHero = new SuperHero();
            JSONObject json = null;
            try {
                //Getting json
                json = array.getJSONObject(i);

                //Adding data to the superhero object
                superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
                superHero.setName(json.getString(Config.TAG_NAME));
                superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding the superhero object to the list
            listSuperHeroes.add(superHero);
        }

        //Notifying the adapter that data has been added or changed
        adapter.notifyDataSetChanged();
    }

    //This method would check that the recyclerview scroll has reached the bottom or not
    private boolean isLastItemDisplaying(RecyclerView recyclerView) {
        if (recyclerView.getAdapter().getItemCount() != 0) {
            int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
            if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
                return true;
        }
        return false;
    }

    //Overriden method to detect scrolling
    private RecyclerView.OnScrollListener rVOnScrollListener = new RecyclerView.OnScrollListener(){
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView,
                                         int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

           if (isLastItemDisplaying(recyclerView)) {
                getData();
            }
        }
    };
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

2

You are calling getData() method from onCreateView() and this leading to call parseData() method and in this method you have used "adapter" object and you are not initialized it. You initializing it after getData() method in onCreateView(). So this may lead NullPointerException.

For this you can initialize adapter in parseData() method and set you adapter value from there only.

Mohammad Misbah
  • 870
  • 8
  • 19
1

The reason of the crash is getActivity().findViewById().setVisibility() in getDataFromServer() method.

Why are you getting progressBar from activity view? Probably your progressBar is in fragment view, so your code should be something like this:

public class LatestFragment extends Fragment {
    private ProgressBar progressBar;

    ...

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.latest, container, false);

        ...
        progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
        ...
    }

    ...

    private JsonArrayRequest getDataFromServer(int requestCount) {
        // You don't need the initialization, it was done in onCreateView() in this code. Remove these lines.
        //final ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progressBar1);

        //Displaying Progressbar
        progressBar.setVisibility(View.VISIBLE);
        ...
    }
    ...
}
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98