3

I have a mapFragment in my accept_a_request_recycleview.xml.

I want to give it's reference or initialise it in my RVAdapterAAR.java's RecyclerView.ViewHolder.

I tried to do it like this: mapFragment = (SupportMapFragment) mapFragment.getChildFragmentManager().findFragmentById(R.id.map_fragment);, but after running the app, it crashed and showed this error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.Fragment.getChildFragmentManager()' on a null object reference at com.abc.xyz.RVAdapterAAR$PersonViewHolder.<init>(RVAdapterAAR.java:48)

Here's full code from RVAdapterAAR.java file:

    public class RVAdapterAAR extends RecyclerView.Adapter<RVAdapterAAR.PersonViewHolder> {

// step 1
Fragment mFragment;
    RVAdapterAAR(List<ListContentAAR> listContentAARs,Fragment mFragment) {
        this.listContentAARs = listContentAARs;
        this.mFragment=mFragment;
    }

            public static class PersonViewHolder extends RecyclerView.ViewHolder {

                CardView cardView;
                TextView nPicTag;
                ImageView hImage;
                TextView nDescriptionTag;
                TextView hDescription;
                TextView hLocation;
                SupportMapFragment mapFragment;
                Button btn_accept;
                Button btn_share;
                TextView postDate;
                TextView postTime;
                TextView postedBy;

                // step 2
                Fragment mFragment;
                PersonViewHolder(View itemView) {
                    super(itemView);
                    this.mFragment = mFragment;
                    cardView = (CardView) itemView.findViewById(R.id.card_accept_request);
                    nPicTag = (TextView) itemView.findViewById(R.id.n_pic_tag);
                    hImage = (ImageView) itemView.findViewById(R.id.h_pic_accept);
                    nDescriptionTag = (TextView) itemView.findViewById(R.id.n_description_tag);
                    hDescription = (TextView) itemView.findViewById(R.id.h_description_accept);
                    hLocation = (TextView) itemView.findViewById(R.id.currentCoordinatesTagAccept);
                    mapFragment = (SupportMapFragment) mFragment.getChildFragmentManager().findFragmentById(R.id.map_fragment);
                    btn_accept = (Button) itemView.findViewById(R.id.btn_accept);
                    btn_share = (Button) itemView.findViewById(R.id.btn_share);
                    postDate = (TextView) itemView.findViewById(R.id.post_date);
                    postTime = (TextView) itemView.findViewById(R.id.post_time);
                    postedBy = (TextView) itemView.findViewById(R.id.posted_by);
                }

            }

            List<ListContentAAR> listContentAARs;

            RVAdapterAAR(List<ListContentAAR> listContentAARs) {
                this.listContentAARs = listContentAARs;
            }

            public void onAttachedToRecyclerView(RecyclerView recyclerView) {
                super.onAttachedToRecyclerView(recyclerView);
            }

            public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_accept_a_request, viewGroup, false);
                PersonViewHolder personViewHolder = new PersonViewHolder(view);
                return personViewHolder;
            }

            public void onBindViewHolder (PersonViewHolder personViewHolder, int i) {
                personViewHolder.nPicTag.setText(listContentAARs.get(i).nPicTag);
                personViewHolder.hImage.setImageBitmap(listContentAARs.get(i).hImage);
                personViewHolder.nDescriptionTag.setText(listContentAARs.get(i).nDescriptionTag);
                personViewHolder.hDescription.setText(listContentAARs.get(i).hDescription);
                personViewHolder.hLocation.setText(listContentAARs.get(i).hLocation);
                 // step 3 
                personViewHolder.mapFragment.getChildFragmentManager().findFragmentById(R.id.map_fragment);
                personViewHolder.btn_accept.findViewById(R.id.btn_accept);
                personViewHolder.btn_share.findViewById(R.id.btn_share);
                personViewHolder.postDate.setText(listContentAARs.get(i).postDate);
                personViewHolder.postTime.setText(listContentAARs.get(i).postTime);
                personViewHolder.postedBy.setText(listContentAARs.get(i).postedBy);
            }

            public int getItemCount() {
                return listContentAARs.size();
            }

        }

Code from AcceptARequest.java(in which I'm using RVAdapterAAR):

public class AcceptARequest extends Fragment implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    public List<ListContentAAR> listContentAARs;
    public RecyclerView recyclerView;

    ImageView hPicAccept;
    TextView nPicTag, nDescriptionTag, hDescriptionAccept, hLocationTagAccept, currentCoordinatesTagAccept, post_date, post_time, posted_by;
    String nPicTagAcceptS, nDescriptionTagAcceptS, hDescriptionAcceptS, hLocationTagAcceptS, currentCoordinatesTagAcceptS, post_dateS, post_timeS, posted_byS;
    Button btn_accept, btn_share;
    LinearLayout dateTimeContainer;
    Bitmap bitmap;

    ParseQuery<ParseObject> query;


    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private static final int MILLISECONDS_PER_SECOND = 1000;

    private static final int UPDATE_INTERVAL_IN_SECONDS = 5;

    private static final int FAST_CEILING_IN_SECONDS = 1;

        private static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
            * UPDATE_INTERVAL_IN_SECONDS;

    private static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
            * FAST_CEILING_IN_SECONDS;

    private static final float METERS_PER_FEET = 0.3048f;

    private static final int METERS_PER_KILOMETER = 1000;

    private static final double OFFSET_CALCULATION_INIT_DIFF = 1.0;

    private static final float OFFSET_CALCULATION_ACCURACY = 0.01f;

    private static final int MAX_POST_SEARCH_RESULTS = 20;

    private static final int MAX_POST_SEARCH_DISTANCE = 100;

    SupportMapFragment mapFragment;

    Circle mapCircle;

    float radius;
    float lastRadius;

    final Map<String, Marker> mapMarkers = new HashMap<String, Marker>();
    int mostRecentMapUpdate;
    boolean hasSetUpInitialLocation;
    String selectedPostObjectId;
    Location lastLocation;
    Location currentLocation;
    LocationManager locationManager;

    LocationRequest locationRequest;

    GoogleApiClient locationClient;
    ParseGeoPoint myPoint;
    double latitude, longitude;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        locationRequest = LocationRequest.create();

        locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        locationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        locationClient = new GoogleApiClient.Builder(getContext())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.

            currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (currentLocation != null) {
                latitude = currentLocation.getLatitude();
                longitude = currentLocation.getLongitude();
            }
            return;
        }
        //currentLocation = LocationServices.FusedLocationApi.getLastLocation(locationClient);
        myPoint = new ParseGeoPoint(latitude, longitude);

        Handler handler1 = new Handler();
        handler1.postDelayed(new Runnable() {
            @Override
            public void run() {
                mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
                mapFragment.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(GoogleMap googleMap) {
                        googleMap.setMyLocationEnabled(true);
                        googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
                            public void onCameraChange(CameraPosition position) {
                                theMainThing();
                            }
                        });
                    }
                });

            }
        }, 1500);

    }

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

        View rootView = inflater.inflate(R.layout.fragment_accept_a_request, container, false);


        listContentAARs = new ArrayList<>();

        nPicTag = (TextView) rootView.findViewById(R.id.n_pic_tag);
        hPicAccept = (ImageView) rootView.findViewById(R.id.h_pic_accept);
        nDescriptionTag = (TextView) rootView.findViewById(R.id.n_description_tag);
        hDescriptionAccept = (TextView) rootView.findViewById(R.id.h_description_accept);
        currentCoordinatesTagAccept = (TextView) rootView.findViewById(R.id.currentCoordinatesTagAccept);
        btn_accept = (Button) rootView.findViewById(R.id.btn_accept);
        btn_share = (Button) rootView.findViewById(R.id.btn_share);
        dateTimeContainer = (LinearLayout) rootView.findViewById(R.id.date_time_container);
        post_date = (TextView) rootView.findViewById(R.id.post_date);
        post_time = (TextView) rootView.findViewById(R.id.post_time);
        posted_by = (TextView) rootView.findViewById(R.id.posted_by);

        nPicTagAcceptS = nPicTag.getText().toString();
        nDescriptionTagAcceptS = nDescriptionTag.getText().toString();
        hDescriptionAcceptS = hDescriptionAccept.getText().toString();
        currentCoordinatesTagAcceptS = currentCoordinatesTagAccept.getText().toString();
        post_dateS = post_date.getText().toString();
        post_timeS = post_time.getText().toString();
        posted_byS = posted_by.getText().toString();

        currentCoordinatesTagAccept.setVisibility(View.INVISIBLE);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
               theMainThing();
            }
        }, 1000);

        recyclerView = (RecyclerView) rootView.findViewById(R.id.accept_request_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Button btnAccept = (Button) view.findViewById(R.id.btn_accept);
                btnAccept.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(R.string.request_accepted_txt);
                        builder.setPositiveButton("Navigate me", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(getActivity(), "Navigating you to the needy...", Toast.LENGTH_LONG).show();
                            }
                        });
                        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(getActivity(), "The help-request has been rejected.", Toast.LENGTH_LONG).show();
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                });
                Button btnShare = (Button) view.findViewById(R.id.btn_share);
                    btnShare.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // share the help-request here.
                        }
                    });
                }

                @Override
                public void onLongClick (View view,int position) {

            }
        }));

        return rootView;
    }

    public void theMainThing() {

        query = ParseQuery.getQuery("ClassName");
                query.addDescendingOrder("createdAt");
                query.whereWithinKilometers("location", myPoint, MAX_POST_SEARCH_DISTANCE);
                query.findInBackground(new FindCallback<ParseObject>() {
                    @Override
                    public void done(List<ParseObject> list, ParseException e) {

                        Toast.makeText(getContext(), "RIGHT", Toast.LENGTH_LONG).show();

                        if (e == null) {

                            Toast.makeText(getContext(), "Data fetched from parse", Toast.LENGTH_LONG).show();

                            for (int i = 0; i < list.size(); i++) {
                                String id = list.get(i).getObjectId();

                                Set<String> toKeep = new HashSet<String>();

                                toKeep.add(list.get(i).getObjectId());
                                // 4
                                Marker oldMarker = mapMarkers.get(list.get(i).getObjectId());
                                // 5
                                MarkerOptions markerOpts =
                                        new MarkerOptions().position(new LatLng(latitude, longitude));

                                ParseGeoPoint parseGeoPoint = list.get(0).getParseGeoPoint("location");

                                if (parseGeoPoint.distanceInKilometersTo(myPoint) > radius * METERS_PER_FEET
                                        / METERS_PER_KILOMETER) {
                                    if (oldMarker != null) {
                                        if (oldMarker.getSnippet() == null) {
                                            continue;
                                        } else {
                                            oldMarker.remove();
                                        }
                                    }
                                    markerOpts =
                                            markerOpts.title("Needy is far away")
                                                    .icon(BitmapDescriptorFactory.defaultMarker(
                                                            BitmapDescriptorFactory.HUE_RED));
                                } else {
                                    if (oldMarker != null) {
                                        if (oldMarker.getSnippet() != null) {
                                            continue;
                                        } else {
                                            oldMarker.remove();
                                        }
                                    }
                                    markerOpts =
                                            markerOpts.title("Needy\'s location")
                                                    .snippet("by " + posted_byS)
                                                    .icon(BitmapDescriptorFactory.defaultMarker(
                                                            BitmapDescriptorFactory.HUE_GREEN));

                                }

                                Marker marker = mapFragment.getMap().addMarker(markerOpts);
                                mapMarkers.put(list.get(i).getObjectId(), marker);
                                // 8
                                if (list.get(i).getObjectId().equals(selectedPostObjectId)) {
                                    marker.showInfoWindow();
                                    selectedPostObjectId = null;
                                }

                                cleanUpMarkers(toKeep);

                                try {
                                    ParseFile parseFile = list.get(i).getParseFile("hImage");
                                    byte[] data = parseFile.getData();
                                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                } catch (Exception err) {
                                    err.printStackTrace();
                                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
                                    builder.setTitle("");
                                    builder.setMessage(err.getMessage());
                                    builder.setPositiveButton(android.R.string.ok, null);
                                    builder.show();
                                }

                                hDescriptionAcceptS = (String) list.get(i).get("hDescription");



                                currentLatAcceptS = (String) list.get(i).get("hLatitude");

                                currentLngAcceptS = (String) list.get(i).get("hLongitude");

                                post_timeS = (String) list.get(i).get("currentTime");
                                post_dateS = (String) list.get(i).get("currentDate");
                                posted_byS = (String) list.get(i).get("postedBy");

                                ListContentAAR score = new ListContentAAR(nPicTagAcceptS, bitmap, nDescriptionTagAcceptS, hDescriptionAcceptS, currentCoordinatesTagAcceptS, mapFragment, R.id.btn_accept, R.id.btn_share, post_dateS, post_timeS, "by " + posted_byS);
                                listContentAARs.add(score);

                                initializeAdapter();

                            }

                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder.setMessage(e.getMessage());
                            builder.setPositiveButton(android.R.string.ok, null);
                            AlertDialog dialog = builder.create();
                            dialog.show();

                            Log.d("error retrieving data", e.getMessage());
                        }
                    }
                });
    }

    private void initializeAdapter(){
        RVAdapterAAR adapter = new RVAdapterAAR(listContentAARs);
        recyclerView.setAdapter(adapter);
    }

    public void cleanUpMarkers(Set<String> markersToKeep) {
        for (String objId : new HashSet<String>(mapMarkers.keySet())) {
            if (!markersToKeep.contains(objId)) {
                Marker marker = mapMarkers.get(objId);
                marker.remove();
                mapMarkers.get(objId).remove();
                mapMarkers.remove(objId);
            }
        }
    }

    public Location getLocation() {
        // If Google Play Services is available
        if (servicesConnected()) {
            // Get the current location
            return LocationServices.FusedLocationApi.getLastLocation(locationClient);
        } else {
            return null;
        }
    }

     public void itemClicked(View view, int position) {

    }

    @Override
    public void onConnected(Bundle bundle) {

    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        theMainThing();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                    super.onLongPress(e);
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

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

}

Please let me know what is wrong here.

Sorry if format of question is not good, I'm still learning to post good questions.

Please do not mark as duplicate and give me an answer instead! I do not know how to fix this. This is not duplicate as I'm not asking how to fix nullPointerException, instead, I'm asking how to give reference of a fragment in RecyclerView.ViewHolder.

1 Answers1

3

How to give reference of a fragment in RecyclerView.ViewHolder?

Get Fragment reference in PersonViewHolder class as:

1. Add Fragment parameter in RVAdapterAAR class constructor :

Fragment mFragment;
RVAdapterAAR(List<ListContentAAR> listContentAARs,Fragment mFragment) {
    this.listContentAARs = listContentAARs;
    this.mFragment=mFragment;
 }

2. Add Fragment parameter in PersonViewHolder class constructor :

Fragment mFragment;
PersonViewHolder(View itemView,Fragment mFragment) {
 super(itemView);
 this.mFragment=mFragment;
 ....your code here...
 mapFragment = (SupportMapFragment) mFragment.getChildFragmentManager().
               findFragmentById(R.id.map_fragment);
}

3. Now pass Fragment Reference using Your_Fragment_Name.this from Fragment class in which creating object of RVAdapterAAR class.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • thanks for help. But still I'm getting the same error on same line. :( –  Jan 17 '16 at 13:35
  • maybe I'm doing something wrong with the 3rd step! Please do 3rd step also for me! PLEASE! –  Jan 17 '16 at 13:38
  • @HammadNasir: please share what you are doing in step 3? – ρяσѕρєя K Jan 17 '16 at 17:33
  • I have edited the code in the question according to what you said. Steps are also mentioned. –  Jan 17 '16 at 18:32
  • dude, I really don't know what to do. Sorry, if that seems stupid to you. Please help with this! –  Jan 18 '16 at 03:06
  • @HammadNasir : you are not doing as in step 1 and 2 – ρяσѕρєя K Jan 18 '16 at 03:09
  • Bro, the main problem is that I'm still struggling to be a good Android developer, but I'm just a beginner. Please tell me what is wrong and what should I do by editing my code. Please! –  Jan 18 '16 at 03:11
  • @HammadNasir: show ur class code in which u are using `RVAdapterAAR ` class – ρяσѕρєя K Jan 18 '16 at 04:39
  • I have added that class named `AcceptARequest.java`, the code is long...sorry for that, but I have tried my level best to trim it. –  Jan 18 '16 at 06:35
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100936/discussion-between--k-and-hammad-nasir). – ρяσѕρєя K Jan 18 '16 at 06:36
  • please reply prosper K –  Jan 18 '16 at 17:34
  • would you help any further, prosper K? –  Jan 19 '16 at 17:13
  • @HammadNasir: How can we help you ? you have posted different issue as question which is "How to give reference of a fragment in RecyclerView.ViewHolder" i answered according to your issue. but now after getting Fragment reference you are saying it is crashing in same posted. – ρяσѕρєя K Jan 19 '16 at 17:17
  • should I post another question for that issue? –  Jan 19 '16 at 17:21
  • @HammadNasir: Yes sure post new question with crash logs and code here app is crashing including xml and java code – ρяσѕρєя K Jan 19 '16 at 17:24
  • @HammadNasir: Also share question link with me – ρяσѕρєя K Jan 19 '16 at 17:25
  • here's the link: http://stackoverflow.com/questions/34883485/app-crashing-due-to-android-view-inflateexception-error-please-see-details Please see it –  Jan 19 '16 at 17:41