Android Studio应用程序已在模拟器中关闭[关闭]

问题描述 投票:-1回答:1

我在Android Studio模拟器上运行我的应用程序时遇到问题,它停止了。

进入日志猫我几次发现以下错误:

原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.GridView.setAdapter(android.widget.ListAdapter)'在com.example.stisnijovskiphotography.MainActivity.onCreate(MainActivity.java:39)

请您帮忙,以下是我在Git上的项目:

https://github.com/stisnijovski/StisnijovskiPhotography

谢谢你。

android android-studio nullpointerexception android-emulator
1个回答
0
投票

您在此处引用R.id.myGrid的ID:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridView = findViewById(R.id.myGrid);
        gridView.setAdapter(new ImageAdaptor(mImageIds, this));
}

来自您的XML文件R.layout.activity_main,它是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottomNav"
        android:layout_alignParentBottom="true"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/menu"
        />

</RelativeLayout>

查看XML文件时,您没有R.id.myGrid的gridview,这就是为什么您会得到nullpointer异常的原因。

您必须将以下内容放入XML文件R.layout.activity_main中,以使其停止产生nullpointer:

 <GridView
        android:layout_width="match_parent"
        android:id="@+id/myGrid"
        android:layout_height="wrap_content">


    </GridView>

向前,将代码包含在您的问题中会很有帮助。希望这能回答您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.