【发布时间】:2020-03-17 06:21:41
【问题描述】:
由于某种原因,我在onActivityResult 中的观点为空。以下是我的实现方式:
public class Player extends AppCompatActivity {
RelativeLayout selectVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
selectVideo = findViewById(R.id.selectVideo);
selectVideo.setOnClickListener(view -> {
Intent intent = new Intent(Player.this, SelectVideo.class);
startActivityForResult(intent, 852);
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == 852){
if (resultCode == RESULT_OK) {
if (data != null) {
// The view is null here
selectVideo.setVisibility(View.GONE);
}
}
}
}
}
在SelectVideo 中,我将结果设置为:
public void returnToPlayer(String path){
Intent output = new Intent();
output.putExtra("path", path);
setResult(RESULT_OK, output);
finish();
}
我无法重现这个,但我在 crashlytics 中得到了这个
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setVisibility(int)' on a null object reference
我知道我可以做到以下几点:(但我想知道为什么会这样)
if (selectVideo != null){
selectVideo.setVisibility(View.GONE);
}
视图怎么可能为空?
编辑1:
我怀疑这个问题与我的xml 有关,但这里是,按照评论部分的要求:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".Player">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/selectVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<ImageView
android:id="@+id/addimg"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/ab_add_video"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
/>
<TextView
android:layout_marginTop="10dp"
android:id="@+id/addtxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT A VIDEO"
android:layout_below="@+id/addimg"
android:textColor="@android:color/white"
android:textSize="20sp"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:layout_marginBottom="20dp"/>
</RelativeLayout>
</RelativeLayout>
【问题讨论】:
-
您尚未在活动的 oncreate 中调用 setcontentview(R.layout.yourxml) 如果已设置请分享您的 xml 文件
-
@NehaRathore 抱歉,我已经编辑了我的问题。
-
请分享您的布局activity_player
-
@NehaRathore 我不明白这会有什么帮助。如果
xml出现问题,则崩溃将发生在onCreate。 -
检查问题,我将使用与您编写的代码相同的代码在我的机器上复制
标签: java android nullpointerexception