我的accept_a_request_recycleview.xml
中有一个mapFragment。
我想在RVAdapterAAR.java
的{{1}}中提供引用或初始化。
我尝试这样做:RecyclerView.ViewHolder
,但在运行应用后,它崩溃并显示此错误:mapFragment = (SupportMapFragment) mapFragment.getChildFragmentManager().findFragmentById(R.id.map_fragment);
以下是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)
文件的完整代码:
RVAdapterAAR.java
来自 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();
}
}
的代码(我正在使用RVAdapterAAR):
AcceptARequest.java
请告诉我这里有什么问题。
对不起,如果问题格式不好,我还在学习发表好问题。
请不要标记为重复,而是给我一个答案!我不知道如何解决这个问题。这不重复,因为我没有问如何修复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();
}
}
,相反,我问的是如何在nullPointerException
中引用fragment
。
答案 0 :(得分:1)
如何在RecyclerView.ViewHolder中引用片段?
在PersonViewHolder
类中获取片段参考:
1。在RVAdapterAAR
类构造函数中添加Fragment参数:
Fragment mFragment;
RVAdapterAAR(List<ListContentAAR> listContentAARs,Fragment mFragment) {
this.listContentAARs = listContentAARs;
this.mFragment=mFragment;
}
2. 在PersonViewHolder
类构造函数中添加Fragment参数:
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。现在使用Fragment
类中的Your_Fragment_Name.this
引用Fragment
引用,其中RVAdapterAAR
类创建对象。