I have a RecyclerView adapter for user added favorites. The recyclerview is populated in a dialog box fragment.
public class FavoriteAdapter extends RecyclerView.Adapter<FavoriteViewHolder> implements ILatLong {
private Context context;
View view;
MainActivity mainActivity;
private List<Favorite> listFavorites;
private SQLiteDB mDatabase;
private int position;
private ILatLong mCallback;
public FavoriteAdapter(ILatLong mCallback){
this.mCallback = mCallback;
}
public FavoriteAdapter(Context context, List<Favorite> listFavorites) {
this.context = context;
this.listFavorites = listFavorites;
mDatabase = new SQLiteDB(context);
}
@Override
public void onBindViewHolder(final FavoriteViewHolder holder, final int mPosition) {
final Favorite singleFavorite = listFavorites.get(mPosition);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Clicked " + "'" + singleFavorite.getName() + "'", Toast.LENGTH_SHORT, true).show();
//mainActivity.onLatLngData(singleFavorite.getLat(), singleFavorite.getLong());
mCallback.onLatLngData(singleFavorite.getLat(), singleFavorite.getLong());
}
});
//other stuff
@Override
public void onLatLngData(Double lat, Double lng) {
try {
mCallback = (ILatLong) context;
}
catch (ClassCastException e) {
Log.d("MyDialog", "Activity doesn't implement the ILatLong interface");
}
}
}
Interface:
public interface ILatLong {
void onLatLngData(Double lat, Double lng);
}
MainActivity method:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ILatLong {
@Override
public void onLatLngData(Double lat, Double lng) {
//use the values
}
}
I've set up the onclicklistener in the onBindViewHolder as you can see, so I know which item is clicked, and when a recyclerview item is clicked it displays a toast with the correct item name (or whatever other attribute I want).
When I try and send the latitude and longitude back to my mainactivity method by uncommenting the line in onclick I get "java.lang.NullPointerException: Attempt to invoke virtual method ...onLatLngData(java.lang.Double, java.lang.Double)' on a null object reference".
How can I send this data back to my mainactivity? I've tried using an interface to callback to MainActivity with no luck but maybe I wasn't doing it right.
Edit: included the interface callback stuff