获取'尝试调用虚方法' java.lang.String java.lang.Object.toString()'在null对象引用'什么时候没有这种方法

时间:2016-09-15 20:47:28

标签: java android nullpointerexception

我收到此错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference即使我的活动中没有此类方法。

以下是代码:

    public class MyActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

            AppCompatSpinner iSpinner, nSpinner, dSpinner, vSpinner;
            AppCompatButton btnP;
            String itemID, currentLatString, currentLngString;
            GoogleApiClient mGoogleApiClient;
            Location mLastLocation;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_my);
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);

                // Create an instance of GoogleAPIClient.
                if (mGoogleApiClient == null) {
                    mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this)
                            .addApi(LocationServices.API)
                            .build();
                }

    iSpinner = (AppCompatSpinner) findViewById(R.id.tag1);
            nSpinner = (AppCompatSpinner) findViewById(R.id.tag2);
            d = (AppCompatSpinner) findViewById(R.id.tag3);
            vSpinner = (AppCompatSpinner) findViewById(R.id.tag4);
            btnP = (AppCompatButton) findViewById(R.id.btnP);

                DateFormat currentTime = new SimpleDateFormat("h:mm a");
                final String time = currentTime.format(Calendar.getInstance().getTime());

                final DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                final String utcFormatDateTimeString = utcFormat.format(Calendar.getInstance().getTimeInMillis());
                Date utc = null;
                try {
                    utc = utcFormat.parse(utcFormatDateTimeString);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                final String utcFormatDateTime = utcFormat.format(utc);

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

                    if (ActivityCompat.checkSelfPermission(PostGameRequest.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(PostGameRequest.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                            mGoogleApiClient);
                    if (mLastLocation != null) {
                        currentLatString = String.valueOf(mLastLocation.getLatitude());
                        currentLngString = String.valueOf(mLastLocation.getLongitude());
                        Toast.makeText(getBaseContext(), currentLatString + ", " + currentLngString, Toast.LENGTH_SHORT).show();
                    }

                    if (!currentLatString.isEmpty() || !currentLngString.isEmpty()) {

                        iSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                iString = adapterView.getItemAtPosition(i).toString();

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });

                        nSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                nString = adapterView.getItemAtPosition(i).toString();

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });

                        dSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                dString = adapterView.getItemAtPosition(i).toString();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });

                        vSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                vString = adapterView.getItemAtPosition(i).toString();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });


                    } else {
                        Snackbar snackbar = Snackbar
                                .make(coordinatorLayout, "Some error occurred. Please retry.", Snackbar.LENGTH_SHORT);
                        snackbar.show();
                        if (ActivityCompat.checkSelfPermission(PostGameRequest.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(PostGameRequest.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                                mGoogleApiClient);
                        if (mLastLocation != null) {
                            currentLatString = String.valueOf(mLastLocation.getLatitude());
                            currentLngString = String.valueOf(mLastLocation.getLongitude());
                            Toast.makeText(getBaseContext(), currentLatString + ", " + currentLngString, Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case android.R.id.home:
                        onBackPressed();
                        return true;
                }
                return super.onOptionsItemSelected(item);
            }

            protected void onStart() {
                mGoogleApiClient.connect();
                super.onStart();
            }

            protected void onStop() {
                mGoogleApiClient.disconnect();
                super.onStop();
            }

            @Override
            public void onConnected(@Nullable Bundle bundle) {

            }

            @Override
            public void onConnectionSuspended(int i) {

            }

            @Override
            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

            }

        }

这是布局代码:

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.playrapp.playr.PostGameRequest"
    tools:showIn="@layout/activity_post_game_request">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentPadding="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tag1:"
                android:layout_marginStart="7dp"
                android:layout_marginLeft="7dp"
                android:textSize="16sp"/>

            <android.support.v7.widget.AppCompatSpinner
                android:id="@+id/tag1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="16dp"
                android:entries="@array/list1"
                style="@style/Base.Widget.AppCompat.Spinner">
            </android.support.v7.widget.AppCompatSpinner>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tag2:"
                android:layout_marginTop="8dp"
                android:layout_marginStart="7dp"
                android:layout_marginLeft="7dp"
                android:textSize="16sp"/>

            <android.support.v7.widget.AppCompatSpinner
                android:id="@+id/tag2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="16dp"
                android:entries="@array/list2"
                style="@style/Base.Widget.AppCompat.Spinner">
            </android.support.v7.widget.AppCompatSpinner>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tag3:"
                android:layout_marginTop="8dp"
                android:layout_marginStart="7dp"
                android:layout_marginLeft="7dp"
                android:textSize="16sp"/>

        <android.support.v7.widget.AppCompatSpinner
            android:id="@+id/tag3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="16dp"
            android:entries="@array/list3"
            style="@style/Base.Widget.AppCompat.Spinner">
        </android.support.v7.widget.AppCompatSpinner>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tag4:"
                android:layout_marginTop="8dp"
                android:layout_marginStart="7dp"
                android:layout_marginLeft="7dp"
                android:textSize="16sp"/>

            <android.support.v7.widget.AppCompatSpinner
                android:id="@+id/tag4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="25dp"
                android:entries="@array/list4"
                style="@style/Base.Widget.AppCompat.Spinner">
            </android.support.v7.widget.AppCompatSpinner>

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btnP"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Text"
                android:layout_gravity="end|right"/>

    </LinearLayout>

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

</RelativeLayout>

这里是strings.xml:

<array name="list1">
        <item>11</item>
        <item>22</item>
        <item>33</item>
    </array>

    <array name="list2">
        <item>a</item>
        <item>b</item>
        <item>c</item>
    </array>

    <array name="list3">
        <item>A</item>
        <item>B</item>
        <item>C</item>
    </array>

    <array name="list4">
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
        <item>6</item>
        <item>7</item>
        <item>8</item>
        <item>9</item>
        <item>10</item>
        <item>11</item>
        <item>12</item>
    </array>

此外,logcat没有显示错误所在的行!

这是logcat显示的内容:

FATAL EXCEPTION: main
Process: com.app.myapp, PID: 18035
java.lang.NullPointerException: Attempt to invoke virtual method
java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:197)
at android.widget.Spinner.onMeasure(Spinner.java:507)
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416)
at android.view.View.measure(View.java:17438)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17438)at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.CardView.onMeasure(CardView.java:211)at android.view.View.measure(View.java:17438)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
at android.view.View.measure(View.java:17438)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:706)
at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1364)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:771)
at android.view.View.measure(View.java:17438)at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:17438)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17438)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17438)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17438)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5464)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2678)
at android.view.View.measure(View.java:17438)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2034)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1191)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1398)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1079)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5839)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:836)
at android.view.Choreographer.doCallbacks(Choreographer.java:635)
at android.view.Choreographer.doFrame(Choreographer.java:601)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:822)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at and

这里出了什么问题?

请告诉我。

0 个答案:

没有答案