定义的TextView上的NullPointerException

时间:2018-07-11 02:19:51

标签: java android nullpointerexception

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

CardView菜单显示了不同的工具,其中包括“位置”,该位置使用了我最近使用的第三方库来检索经度和纬度。

当用户单击该卡片的“位置”时,将弹出一个弹出窗口,并在按下“更新”按钮后,我在该弹出窗口中将两个文本视图设置为检索到的经度和纬度。

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

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

这是我的代码的主要部分:

菜单类-启动器活动:

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:RHellstrom@bridgew.edu"));
            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>

StackTrace:

 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)

因此,问题文本视图在popup.xml中定义。

请帮忙。我尝试过,我搜寻了。我什么都找不到。

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

PSA:我还有3个其他的片段类,一个viewpager和一个使用Google Volley库从URL检索数据的类,但它们似乎与这里的问题不符。让我知道您是否需要它们。

2 个答案:

答案 0 :(得分:2)

如果视图在对话框中,则必须在对话框上调用findViewById,如下所示:

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

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

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

答案 1 :(得分:1)

经度Tv是locationPopupDialog的子视图,您需要设置对话框的布局( popup_location.xml )。然后用longitudeTv = (TextView) locationPopupDialog.findViewById(R.id.longitudeTv);

初始化