OnGridImageSelectedListener.onGridImageSelected 上的空指针异常
Posted
技术标签:
【中文标题】OnGridImageSelectedListener.onGridImageSelected 上的空指针异常【英文标题】:Null pointer exception on OnGridImageSelectedListener.onGridImageSelected 【发布时间】:2021-01-19 21:26:18 【问题描述】:我收到java.lang.NullPointerException
:尝试在空对象引用上调用接口方法“void com.umo2.players.Profile.MomentsActivity$OnGridImageSelectedListener.onGridImageSelected(com.umo2.players.models.Photo, int)”
我是这方面的新手,我不明白我是如何得到错误的,有人可以告诉我出路吗
这是我的日志猫
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:创建 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;
// 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.");
);
这是我的照片模特
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);
这是我的活动
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】:在你的片段内部:
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);
【讨论】:
当我尝试在我的片段中创建 OnGridImageSelectedListener 时,它会显示一个错误,因为它不是一个类 移除 onAttach 方法 fragment.setListener(MomentsACtivity.this)有错误 Moments 活动也有错误,@Override public void onGridImageSelected(Photo photo, int activityNumber) Log.d(TAG, "onGridImageSelected: selected an image gridview: " + photo.toString( )); ViewPostFragment 片段 = 新 ViewPostFragment();捆绑参数 = 新捆绑(); args.putParcelable(getString(R.string.photo), photo); args.putInt(getString(R.string.activity_number), activityNumber);片段.setArguments(args); 在你的活动中移除接口 OnGridImageSelectedListener 然后在你的片段中使用接口 OnGridImageSelectedListener以上是关于OnGridImageSelectedListener.onGridImageSelected 上的空指针异常的主要内容,如果未能解决你的问题,请参考以下文章