ChanceVI
ChanceVI

Reputation: 220

NullPointerException on defined TextView

I am working on an app using a CardView menu & I am running into some troubles.

The CardView menu presents different tools & among those, there is "location" which uses a third-party library that I used very recently to retrieve the longitude and latitude.

When the user clicks into this card "location", a popup shows up & after pressing the button "update", I set two textviews in that popup to the retrieved longitude and latitude.

However, I seem to run into a NullPointerException when I try:

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

Here are the main parts of my code:

The Menu Class - the launcher 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:[email protected]"));
            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)

So, the problematics textviews are defined in the popup.xml.

Please, help. I tried, I searched. I can't find anything.

Community, you're my last hope.

PSA: I also have 3 other fragment classes, a viewpager and a a class retrieving data from a URL using the Volley library by Google but they don't seem to coincide with the problem here. Let me know if you need them.

Upvotes: 2

Views: 73

Answers (2)

Rookie Ma
Rookie Ma

Reputation: 11

The longitudeTv is childview of locationPopupDialog,you need set the layout of the dialog (popup_location.xml). then init with longitudeTv = (TextView) locationPopupDialog.findViewById(R.id.longitudeTv);

Upvotes: 1

Tyler V
Tyler V

Reputation: 10910

If the views are in your dialog you have to call findViewById on the dialog, as in:

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

They can't be found in the menu activity and are null.

You can't call this right away though, it has to be after you have set the layout of the dialog. However, I don't see where you actually set the layout of the dialog to popup_location.xml in the code you posted. Presumably that's in the showLocationPopup method.

Upvotes: 2

Related Questions