英文:
Null pointer exception on OnGridImageSelectedListener.onGridImageSelected
问题
我得到了`java.lang.NullPointerException`:尝试在空对象引用上调用接口方法'void com.umo2.players.Profile.MomentsActivity$OnGridImageSelectedListener.onGridImageSelected(com.umo2.players.models.Photo, int)'
我在这方面是新手,不明白为什么会出现错误,有人能给我指条明路吗?
以下是我的日志记录:
E/AndroidRuntime: 致命异常:主线程
进程:com.umo2.players,PID:29955
java.lang.NullPointerException:尝试在空对象引用上调用接口方法'void com.umo2.players.Profile.MomentsActivity$OnGridImageSelectedListener.onGridImageSelected(com.umo2.players.models.Photo, int)'
在com.umo2.players.Profile.MomentsFragment$1$1.onItemClick(MomentsFragment.java:163)
在android.widget.AdapterView.performItemClick(AdapterView.java:318)
在android.widget.AbsListView.performItemClick(AbsListView.java:1158)
在android.widget.AbsListView$PerformClick.run(AbsListView.java:3127)
在android.widget.AbsListView$3.run(AbsListView.java:4073)
在android.os.Handler.handleCallback(Handler.java:790)
在android.os.Handler.dispatchMessage(Handler.java:99)
在android.os.Looper.loop(Looper.java:164)
在android.app.ActivityThread.main(ActivityThread.java:6739)
在java.lang.reflect.Method.invoke(Native Method)
在com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:449)
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
D/HprofFactory: 创建HprofDebugEx
这是我的片段:
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG = "MomentsActivity";
private static final int NUM_GRID_COLUMNS = 3;
private ProgressBar mProgreesBar;
private GridView gridView;
private Toolbar toolbar;
private FrameLayout parentFrameLayout;
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
MomentsActivity.OnGridImageSelectedListener mOnGridImageSelectedListener;
private BottomNavigationViewEx bottomNavigationView;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
private Context mContext;
private static final int ACTIVITY_NUM = 4;
private String mParam1;
private String mParam2;
public MomentsFragment() {
}
public static MomentsFragment newInstance(String param1, String param2) {
MomentsFragment fragment = new MomentsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_moments, container, false);
gridView = (GridView) view.findViewById(R.id.gridView);
toolbar = (Toolbar) view.findViewById(R.id.momentToolBar);
bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
parentFrameLayout = getActivity().findViewById(R.id.momentsFrame);
setupBottomNavigationView();
setupGridView();
return view;
}
@Override
public void onAttach(Context context) {
try{
mOnGridImageSelectedListener = (MomentsActivity.OnGridImageSelectedListener) getActivity();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
super.onAttach(context);
}
private void setupGridView() {
Log.d(TAG, "setupGridView: Setting up image grid.");
final ArrayList<Photo> photos = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_photos))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
photos.add(singleSnapshot.getValue(Photo.class));
}
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
ArrayList<String> imgUrls = new ArrayList<>();
for(int i = 0; i < photos.size(); i++){
imgUrls.add(photos.get(i).getImage_path());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview, "", imgUrls);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mOnGridImageSelectedListener.onGridImageSelected(photos.get(position), ACTIVITY_NUM);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
这是我的照片模型:
public class Photo implements Parcelable
{
// 照片的属性和方法
}
这是我的活动:
public class MomentsActivity extends AppCompatActivity implements MomentsFragment.OnGridImageSelectedListener {
// 活动的属性和方法
}
英文:
I am getting a java.lang.NullPointerException
: Attempt to invoke interface method 'void com.umo2.players.Profile.MomentsActivity$OnGridImageSelectedListener.onGridImageSelected(com.umo2.players.models.Photo, int)' on a null object reference
I am new on this stuff and I don't understand how I am getting an error can someone show me the way out
here is my log cat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.umo2.players, PID: 29955
java.lang.NullPointerException: Attempt to invoke interface method 'void com.umo2.players.Profile.MomentsActivity$OnGridImageSelectedListener.onGridImageSelected(com.umo2.players.models.Photo, int)' on a null object reference
at com.umo2.players.Profile.MomentsFragment$1$1.onItemClick(MomentsFragment.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3127)
at android.widget.AbsListView$3.run(AbsListView.java:4073)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6739)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:449)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
D/HprofFactory: Create HprofDebugEx
this is my fragment
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String TAG = "MomentsActivity";
private static final int NUM_GRID_COLUMNS = 3;
private ProgressBar mProgreesBar;
private GridView gridView;
private Toolbar toolbar;
private FrameLayout parentFrameLayout;
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
MomentsActivity.OnGridImageSelectedListener mOnGridImageSelectedListener;
private BottomNavigationViewEx bottomNavigationView;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
private Context mContext;
private static final int ACTIVITY_NUM = 4;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public MomentsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MomentsFragment.
*/
// TODO: Rename and change types and number of parameters
public static MomentsFragment newInstance(String param1, String param2) {
MomentsFragment fragment = new MomentsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_moments, container, false);
// tempGridSetup();
gridView = (GridView) view.findViewById(R.id.gridView);
toolbar = (Toolbar) view.findViewById(R.id.momentToolBar);
bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mContext = getActivity();
parentFrameLayout = getActivity().findViewById(R.id.momentsFrame);
setupBottomNavigationView();
setupGridView();
return view;
}
@Override
public void onAttach(Context context) {
try{
mOnGridImageSelectedListener = (MomentsActivity.OnGridImageSelectedListener) getActivity();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage() );
}
super.onAttach(context);
}
private void setupGridView() {
Log.d(TAG, "setupGridView: Setting up image grid.");
final ArrayList<Photo> photos = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_photos))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
photos.add(singleSnapshot.getValue(Photo.class));
// Photo photo = new Photo();
//Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();
}
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
ArrayList<String> imgUrls = new ArrayList<String>();
for(int i = 0; i < photos.size(); i++){
imgUrls.add(photos.get(i).getImage_path());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview, "", imgUrls);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mOnGridImageSelectedListener.onGridImageSelected(photos.get(position), ACTIVITY_NUM);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
this is my photo model
public class Photo implements Parcelable
{
private String caption;
private String date_created;
private String image_path;
private String photo_id;
private String user_id;
private String tags;
public Photo(String caption, String date_created, String image_path, String photo_id, String user_id, String tags) {
this.caption = caption;
this.date_created = date_created;
this.image_path = image_path;
this.photo_id = photo_id;
this.user_id = user_id;
this.tags = tags;
}
public Photo() {
}
protected Photo(Parcel in) {
caption = in.readString();
date_created = in.readString();
image_path = in.readString();
photo_id = in.readString();
user_id = in.readString();
tags = in.readString();
}
public static final Creator<Photo> CREATOR = new Creator<Photo>() {
@Override
public Photo createFromParcel(Parcel in) {
return new Photo(in);
}
@Override
public Photo[] newArray(int size) {
return new Photo[size];
}
};
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getDate_created() {
return date_created;
}
public void setDate_created(String date_created) {
this.date_created = date_created;
}
public String getImage_path() {
return image_path;
}
public void setImage_path(String image_path) {
this.image_path = image_path;
}
public String getPhoto_id() {
return photo_id;
}
public void setPhoto_id(String photo_id) {
this.photo_id = photo_id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Photo{" +
"caption='" + caption + '\'' +
", date_created='" + date_created + '\'' +
", image_path='" + image_path + '\'' +
", photo_id='" + photo_id + '\'' +
", user_id='" + user_id + '\'' +
", tags='" + tags + '\'' +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(caption);
parcel.writeString(date_created);
parcel.writeString(image_path);
parcel.writeString(photo_id);
parcel.writeString(user_id);
parcel.writeString(tags);
}
this is my activity
public class MomentsActivity extends AppCompatActivity implements
MomentsFragment.OnGridImageSelectedListener {
private static final String TAG = "MomentsActivity";
private static final int NUM_GRID_COLUMNS = 3;
private ProgressBar mProgreesBar;
private GridView gridView;
private Toolbar toolbar;
private FrameLayout parentFrameLayout;
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
OnGridImageSelectedListener mOnGridImageSelectedListener;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
private static final int ACTIVITY_NUM = 4;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_moments);
Log.d(TAG, "onCreate: started.");
init();
}
private void tempGridSetup() {
ArrayList<String> imgURLs = new ArrayList<>();
imgURLs.add("https://pbs.twimg.com/profile_images/616076655547682816/6gMRtQyY.jpg");
imgURLs.add("https://i.redd.it/9bf67ygj710z.jpg");
imgURLs.add("https://c1.staticflickr.com/5/4276/34102458063_7be616b993_o.jpg");
imgURLs.add("http://i.imgur.com/EwZRpvQ.jpg");
imgURLs.add("http://i.imgur.com/JTb2pXP.jpg");
imgURLs.add("https://i.redd.it/59kjlxxf720z.jpg");
imgURLs.add("https://i.redd.it/pwduhknig00z.jpg");
imgURLs.add("https://i.redd.it/clusqsm4oxzy.jpg");
imgURLs.add("https://i.redd.it/svqvn7xs420z.jpg");
imgURLs.add("http://i.imgur.com/j4AfH6P.jpg");
imgURLs.add("https://i.redd.it/89cjkojkl10z.jpg");
imgURLs.add("https://i.redd.it/aw7pv8jq4zzy.jpg");
//setupImageGrid(imgURLs);
}
/*
private void setupImageGrid(ArrayList<String> imgURLs) {
GridView gridView = (GridView) findViewById(R.id.gridView);
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview, "", imgURLs);
gridView.setAdapter(adapter);
}
*/
@Override
public void onGridImageSelected(Photo photo, int activityNumber) {
Log.d(TAG, "onGridImageSelected: selected an image gridview: " + photo.toString());
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
args.putInt(getString(R.string.activity_number), activityNumber);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.momentsFrame, fragment);
transaction.addToBackStack(getString(R.string.view_post_fragment));
transaction.commit();
}
private void init() {
Log.d(TAG, "init: inflating " + getString(R.string.moments_fragment));
MomentsFragment fragment = new MomentsFragment();
FragmentTransaction transaction = MomentsActivity.this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.moments_fragment));
transaction.commit();
}
}
答案1
得分: 1
在你的片段内部:
OnGridImageSelectedListener mOnGridImageSelectedListener;
public void setListener(OnGridImageSelectedListener listener) {
mOnGridImageSelectedListener = listener;
}
在你的活动中:
移除:
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
然后添加 fragment.setListener
:
private void init() {
Log.d(TAG, "init: inflating " + getString(R.string.moments_fragment));
MomentsFragment fragment = new MomentsFragment();
FragmentTransaction transaction = MomentsActivity.this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.moments_fragment));
transaction.commit();
fragment.setListener(MomentsActivity.this);
}
英文:
Inside your fragment:
OnGridImageSelectedListener mOnGridImageSelectedListener;
public void setListener(OnGridImageSelectedListener listener) {
mOnGridImageSelectedListener = listener;
}
In your activity:
remove
public interface OnGridImageSelectedListener{
void onGridImageSelected(Photo photo, int activityNumber);
}
then add fragment.setListener
private void init() {
Log.d(TAG, "init: inflating " + getString(R.string.moments_fragment));
MomentsFragment fragment = new MomentsFragment();
FragmentTransaction transaction = MomentsActivity.this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.moments_fragment));
transaction.commit();
fragment.setListener(MomentsActivity.this);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论