空指针异常发生在 OnGridImageSelectedListener.onGridImageSelected 上。

huangapple go评论99阅读模式
英文:

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.playersPID29955

    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 &#39;void com.umo2.players.Profile.MomentsActivity$OnGridImageSelectedListener.onGridImageSelected(com.umo2.players.models.Photo, int)&#39; 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 = &quot;param1&quot;;
private static final String ARG_PARAM2 = &quot;param2&quot;;
private static final String TAG = &quot;MomentsActivity&quot;;
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, &quot;onAttach: ClassCastException: &quot; + e.getMessage() );
}
super.onAttach(context);
}
private void setupGridView() {
Log.d(TAG, &quot;setupGridView: Setting up image grid.&quot;);
final ArrayList&lt;Photo&gt; photos = new ArrayList&lt;&gt;();
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&lt;String, Object&gt; objectMap = (HashMap&lt;String, Object&gt;) singleSnapshot.getValue();
}
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
ArrayList&lt;String&gt; imgUrls = new ArrayList&lt;String&gt;();
for(int i = 0; i &lt; photos.size(); i++){
imgUrls.add(photos.get(i).getImage_path());
}
GridImageAdapter adapter = new GridImageAdapter(getActivity(),R.layout.layout_grid_imageview, &quot;&quot;, imgUrls);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
mOnGridImageSelectedListener.onGridImageSelected(photos.get(position), ACTIVITY_NUM);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d(TAG, &quot;onCancelled: query cancelled.&quot;);
}
});
}

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&lt;Photo&gt; CREATOR = new Creator&lt;Photo&gt;() {
@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 &quot;Photo{&quot; +
&quot;caption=&#39;&quot; + caption + &#39;\&#39;&#39; +
&quot;, date_created=&#39;&quot; + date_created + &#39;\&#39;&#39; +
&quot;, image_path=&#39;&quot; + image_path + &#39;\&#39;&#39; +
&quot;, photo_id=&#39;&quot; + photo_id + &#39;\&#39;&#39; +
&quot;, user_id=&#39;&quot; + user_id + &#39;\&#39;&#39; +
&quot;, tags=&#39;&quot; + tags + &#39;\&#39;&#39; +
&#39;}&#39;;
}
@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 = &quot;MomentsActivity&quot;;
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, &quot;onCreate: started.&quot;);
init();
}
private void tempGridSetup() {
ArrayList&lt;String&gt; imgURLs = new ArrayList&lt;&gt;();
imgURLs.add(&quot;https://pbs.twimg.com/profile_images/616076655547682816/6gMRtQyY.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/9bf67ygj710z.jpg&quot;);
imgURLs.add(&quot;https://c1.staticflickr.com/5/4276/34102458063_7be616b993_o.jpg&quot;);
imgURLs.add(&quot;http://i.imgur.com/EwZRpvQ.jpg&quot;);
imgURLs.add(&quot;http://i.imgur.com/JTb2pXP.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/59kjlxxf720z.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/pwduhknig00z.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/clusqsm4oxzy.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/svqvn7xs420z.jpg&quot;);
imgURLs.add(&quot;http://i.imgur.com/j4AfH6P.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/89cjkojkl10z.jpg&quot;);
imgURLs.add(&quot;https://i.redd.it/aw7pv8jq4zzy.jpg&quot;);
//setupImageGrid(imgURLs);
}

/*

    private void setupImageGrid(ArrayList&lt;String&gt; 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, &quot;&quot;, imgURLs);
gridView.setAdapter(adapter);
}

*/

@Override
public void onGridImageSelected(Photo photo, int activityNumber) {
Log.d(TAG, &quot;onGridImageSelected: selected an image gridview: &quot; + 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, &quot;init: inflating &quot; + 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, &quot;init: inflating &quot; + 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);
}

huangapple
  • 本文由 发表于 2020年10月5日 09:23:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64201406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定