java - 定义的 TextView 上出现 NullPointerException

标签 java android nullpointerexception

我正在开发一个使用 CardView 菜单的应用程序,并且遇到了一些麻烦。

CardView 菜单提供了不同的工具,其中有一个“位置”,它使用我最近用来检索经度和纬度的第三方库。

当用户单击此卡“位置”时,会出现一个弹出窗口,按下“更新”按钮后,我将该弹出窗口中的两个 TextView 设置为检索到的经度和纬度。

但是,当我尝试时,我似乎遇到了 NullPointerException:

longitudeTv.setText("Longitude: " + deviceLongitude);  

以下是我的代码的主要部分:

菜单类 - 启动器 Activity :

public class Menu extends AppCompatActivity {

GridLayout menuGrid;
SimpleLocation myLocation;

public static double deviceLongitude;
public static double deviceLatitude;

public static Dialog infoPopupDialog;
static TextView messageTv;
public static Dialog locationPopupDialog;
public static TextView longitudeTv;
public static TextView latitudeTv;


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

    menuGrid = (GridLayout) findViewById(R.id.menuGrid);
    myLocation = new SimpleLocation(this);


    infoPopupDialog = new Dialog(this);
    messageTv = (TextView) findViewById(R.id.messageTv);

    locationPopupDialog = new Dialog(this);
    longitudeTv = (TextView) findViewById(R.id.longitudeTv);
    latitudeTv = (TextView) findViewById(R.id.latitudeTv);

    // if we can't access the location yet
    if (!myLocation.hasLocationEnabled()) {
        // ask the user to enable location access
        SimpleLocation.openSettings(this);
    }


    CardView dataCard = (CardView) findViewById(R.id.dataCard);
    CardView locationCard = (CardView) findViewById(R.id.locationCard);
    CardView timeCard = (CardView) findViewById(R.id.timeCard);
    CardView websiteCard = (CardView) findViewById(R.id.websiteCard);
    CardView emailCard = (CardView) findViewById(R.id.emailCard);
    CardView infoCard = (CardView) findViewById(R.id.infoCard);

    infoCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MainActivity.showInfoPopup();
        }
    });

    dataCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent dataActivity = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(dataActivity);
        }
    });

    locationCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final double longit = roundCoordinates(myLocation.getLongitude());
            final double latit = roundCoordinates(myLocation.getLatitude());

            deviceLongitude = longit;
            deviceLatitude = latit;

            MainActivity.showLocationPopup();

        }
    });

    timeCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(Menu.this, "Next update in 11 mns", Toast.LENGTH_SHORT).show();
        }
    });

    websiteCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent openWebsite = new Intent(Intent.ACTION_VIEW, Uri.parse("http://159.203.78.94/rpilog/weatherstation.txt")); //Insert website.
            startActivity(openWebsite);
        }
    });

    emailCard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "Weather Station Data Report");
            intent.putExtra(Intent.EXTRA_TEXT, MainActivity.dataFromURL); //Add string variable holding entire data here.
            intent.setData(Uri.parse("mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f3d270a03031c1b1d00022f0d1d060b080a18410a0b1a" rel="noreferrer noopener nofollow">[email protected]</a>"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
            startActivity(intent);
        }
    });
}



//function to round to 2 decimal places our GPS coordinates.
public static double roundCoordinates(double coordinate){

    String result = String.format("%.2f", coordinate);

    double roundedValue = Double.parseDouble(result);

    return roundedValue;

}


public void closePopup(View v){   //ONCLICK OF CLOSE ICON
    infoPopupDialog.dismiss();
    locationPopupDialog.dismiss();

}


public void updateCoordinates(View v){ //ONCLICK BTN "UPDATE"

        Menu.latitudeTv.setText("Latitude: " + Menu.deviceLatitude);
        Menu.longitudeTv.setText("Longitude: " + Menu.deviceLongitude);

  }

}

Menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.myapps.toualbiamine.weathertracker.Menu"
android:background="@drawable/bg"
android:weightSum="10"
android:orientation="vertical"
android:backgroundTintMode="multiply"
android:backgroundTint="@color/background"
>

<RelativeLayout
    android:layout_weight="2"
    android:layout_width="match_parent"
    android:layout_height="0dp">

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Weather Tracker"
        android:textSize="34sp"
        android:textColor="@color/titleColor"
        android:layout_centerInParent="true"/>


</RelativeLayout>

<GridLayout
    android:id="@+id/menuGrid"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="8"
    android:alignmentMode="alignMargins"
    android:columnCount="2"
    android:columnOrderPreserved="false"
    android:padding="14dp"
    android:rowCount="3"
    >

    <!-- Row 1 -->
    <!-- Column 1 -->
    <android.support.v7.widget.CardView
        android:id="@+id/dataCard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="20dp"
        >

        <LinearLayout
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_marginLeft="16dp"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/data"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="18dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_marginRight="32dp"
                android:text="Data"
                android:textColor="@color/textColor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>
    <!-- Column 2 -->
    <android.support.v7.widget.CardView
        android:id="@+id/locationCard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="20dp"
        >

        <LinearLayout
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_marginLeft="16dp"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/location"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="18dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_marginRight="29dp"
                android:text="Location"
                android:textColor="@color/textColor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>

    <!-- Row 2 -->
    <!-- Column 1 -->
    <android.support.v7.widget.CardView
        android:id="@+id/timeCard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="20dp"
        >

        <LinearLayout
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_marginLeft="16dp"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/time"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="18dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_marginRight="30dp"
                android:text="Update Time"
                android:textColor="@color/textColor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>
    <!-- Column 2 -->
    <android.support.v7.widget.CardView
        android:id="@+id/emailCard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="20dp"
        >

        <LinearLayout
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_marginLeft="16dp"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/email"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="18dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_marginRight="35dp"
                android:text="Email"
                android:textColor="@color/textColor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>

    <!-- Row 3 -->
    <!-- Column 1 -->
    <android.support.v7.widget.CardView
        android:id="@+id/websiteCard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="20dp"
        >

        <LinearLayout
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_marginLeft="16dp"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/web"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="18dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_marginRight="30dp"
                android:text="Website"
                android:textColor="@color/textColor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>
    <!-- Column 2 -->
    <android.support.v7.widget.CardView
        android:id="@+id/infoCard"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="20dp"
        >

        <LinearLayout
            android:layout_gravity="center_horizontal|center_vertical"
            android:layout_marginLeft="16dp"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/info"
                android:layout_gravity="center_horizontal"
                android:layout_marginRight="17dp"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:layout_marginRight="34dp"
                android:text="Info"
                android:textColor="@color/textColor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>









</GridLayout>

Popup_location.xml:

    <?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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:gravity="center">

    <ImageView
        android:id="@+id/closePopup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/close"
        android:layout_alignParentRight="true"
        android:elevation="5dp"
        android:layout_marginTop="7dp"
        android:layout_marginRight="7dp"
        android:onClick="closePopup"/>

    <android.support.v7.widget.CardView
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="15dp"
        app:cardBackgroundColor="@color/background"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginTop="25dp"
            android:layout_marginBottom="25dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginTop="25dp"
                android:layout_marginBottom="25dp">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:src="@drawable/location_popup"
                    />
                <TextView
                    android:id="@+id/longitudeTv"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginBottom="20dp"
                    android:layout_marginTop="10dp"
                    android:textAlignment="center"
                    android:textSize="18dp"
                    android:text="Longitude: "
                    />
                <TextView
                    android:id="@+id/latitudeTv"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginBottom="20dp"
                    android:textAlignment="center"
                    android:textSize="18dp"
                    android:text="Latitude: "
                    />
                <Button
                    android:id="@+id/btn"
                    android:layout_width="200dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:text="UPDATE"
                    android:textColor="@color/colorWhite"
                    android:background="@drawable/update_btn_circle"
                    android:layout_gravity="center_horizontal"
                    android:onClick="updateCoordinates"
                    />
            </LinearLayout>

        </LinearLayout>


    </android.support.v7.widget.CardView>

    </RelativeLayout>

堆栈跟踪:

 E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.myapps.toualbiamine.weathertracker, PID: 24053

java.lang.IllegalStateException: Could not execute method for 
android:onClick

 at 
   android.support.v7.app.AppCompatViewInflater$
   DeclaredOnClickListener.
   onClick(AppCompatViewInflater.java:293)

at android.view.View.performClick(View.java:6294)

at android.view.View$PerformClick.run(View.java:24770)

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:6494)

at java.lang.reflect.Method.invoke(Native Method)

   at          com.android.internal.os.RuntimeInit$MethodAndArgsCaller.
  run(RuntimeInit.java:438)

 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

 Caused by: java.lang.reflect.InvocationTargetException

  at java.lang.reflect.Method.invoke(Native Method)

   at android.support.v7.app.AppCompatViewInflater$
   DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)

  at android.view.View.performClick(View.java:6294) 

  at android.view.View$PerformClick.run(View.java:24770) 

  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:6494) 

  at java.lang.reflect.Method.invoke(Native Method) 

  at 
       com.android.internal.os.RuntimeInit$MethodAndArgsCaller
       .run(RuntimeInit.java:438) 

   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

   Caused by: java.lang.NullPointerException: Attempt to invoke virtual 
   method 'void android.widget.TextView.setText(java.lang.CharSequence)' 
   on a null object reference

     at
      com.myapps.weathertracker.Menu.updateCoordinates(Menu.java:149)

因此,有问题的 TextView 是在 popup.xml 中定义的。

请帮忙。我尝试过,我寻找过。我找不到任何东西。

社区,你是我最后的希望。

PSA:我还有 3 个其他 fragment 类,一个 viewpager 和一个使用 Google 的 Volley 库从 URL 检索数据的类,但它们似乎与这里的问题不一致。如果您需要它们,请告诉我。

最佳答案

如果 View 位于对话框中,则必须在对话框上调用 findViewById,如下所示:

longitudeTv = (TextView) locationPopupDialog.findViewById(R.id.longitudeTv);

它们在菜单 Activity 中找不到,并且为空。

不过,您不能立即调用它,它必须在设置对话框布局之后调用。但是,我没有看到您在发布的代码中实际将对话框的布局设置为 popup_location.xml 的位置。大概是在 showLocationPopup 方法中。

关于java - 定义的 TextView 上出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276329/

相关文章:

java - 如何以编程方式从 Java 中的 FLV 文件中提取预览图像(如第一帧)?

java - JProgressBar 不确定线程

android - 如何用 ActivityResultLauncher 替换 startActivityForResult 但仍然包含选项 Bundle?

android - Fresco:使用当前显示在 Drawee 中的图像作为下一次请求的占位符

java - 在 fragment 中显示 RecyclerView

java - setContentPane() 和 addActionListener 收到 NullPointerException

java - 添加(插入)时尝试平衡 AVL 树 : Java

Java - 由计时器控制的多个对象(用于游戏)

java - 实时匹配记录

java - 使用 GSON 反序列化通用容器与特定对象