secend init中view.setonclicklistener处的android java空点实例为何不匹配

时间:2018-07-27 10:14:06

标签: java android nullpointerexception

我遇到了这个问题,它显示了以下错误

请帮助我: 我在init2()中得到了NullPointerException。短信显然是null。 我不明白问题所在

  

进程:com.example.android.projectdestage,PID:11049                                                                                   java.lang.RuntimeException:无法启动活动   ComponentInfo {com.example.android.projectdestage / com.example.android.projectdestage.MainActivity}:   java.lang.NullPointerException:尝试调用虚拟方法'void   android.view.View.setOnClickListener(android.view.View $ OnClickListener)'   在空对象引用上                                                                                       在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)                                                                                       在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)                                                                                       在android.app.ActivityThread.-wrap14(ActivityThread.java)                                                                                       在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1642)                                                                                       在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                       在android.os.Looper.loop(Looper.java:154)                                                                                       在android.app.ActivityThread.main(ActivityThread.java:6776)                                                                                       在java.lang.reflect.Method.invoke(本机方法)                                                                                       在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1518)                                                                                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)                                                                                    原因:java.lang.NullPointerException:尝试调用虚拟方法'void   android.view.View.setOnClickListener(android.view.View $ OnClickListener)'   在空对象引用上                                                                                       在   com.example.android.projectdestage.MainActivity.init2(MainActivity.java:60)                                                                                       在   com.example.android.projectdestage.MainActivity.onCreate(MainActivity.java:38)                                                                                       在android.app.Activity.performCreate(Activity.java:6956)                                                                                       在   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)                                                                                       在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)                                                                                       在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)                                                                                       在android.app.ActivityThread.-wrap14(ActivityThread.java)                                                                                       在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1642)                                                                                       在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                       在android.os.Looper.loop(Looper.java:154)                                                                                       在android.app.ActivityThread.main(ActivityThread.java:6776)                                                                                       在java.lang.reflect.Method.invoke(本机方法)                                                                                       在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1518)                                                                                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

****这是我的主要活动****

    import android.app.Dialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;

    public class MainActivity extends AppCompatActivity


    {

    private Button sms;
    private Button btnMap;


        private static final String TAG = "MainActivity";

        private static final int ERROR_DIALOG_REQUEST = 9001;


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



            if(isServicesOK()){
                init();
                init2();
            }
        }


        private void init(){
            Button btnMap = (Button) findViewById(R.id.btnMap);
            btnMap.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MainActivity.this, MapActivity.class);
                    startActivity(intent);

                }
            });
        }

        private void init2()
        {
            Button sms = (Button) findViewById(R.id.sms);
            sms.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent message = new Intent(MainActivity.this, MainActivity2.class);
                    startActivity(message);
                }
            });
        }







        public boolean isServicesOK()
        {
            Log.d(TAG, "isServicesOK: checking google services version");

            int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MainActivity.this);

            if(available == ConnectionResult.SUCCESS)
            {
                // koulchi mli7 map request
                Log.d(TAG, "isServicesOK: Google Play Services is working");
                return true;
            }
            else if(GoogleApiAvailability.getInstance().isUserResolvableError(available))
            {
                //test d erreur
                Log.d(TAG, "isServicesOK: an error occured but we can fix it");
                Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, available, ERROR_DIALOG_REQUEST);
                dialog.show();
            }else
                {
                Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
                }
            return false;
        }



    }

`**this is my mainactivity xml**`



        <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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.example.android.projectdestage.MainActivity">

        <Button
            android:id="@+id/btnMap"
            android:layout_width="87dp"
            android:layout_height="45dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="244dp"
            android:text="@string/map"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.43"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/smsbtn"
            android:layout_width="wrap_content"
            android:layout_height="43dp"
            android:layout_marginBottom="136dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="@string/enter_your_message"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.43"
            app:layout_constraintStart_toStartOf="parent" />

    </android.support.constraint.ConstraintLayout>

**and the main2activity 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"
    android:gravity="center"

    android:orientation="vertical"
    tools:context="com.example.android.projectdestage.MainActivity2">


    <TextView
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/enter_your_message"
        android:textSize="30sp" />

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

        <TextView
            android:id="@+id/editText2"
            android:layout_width="385dp"
            android:layout_height="410dp"
            android:layout_marginTop="50dp"
            android:layout_weight="1"
            android:text="@string/textview" />

        <Button
            android:id="@+id/btnSendSMSendSms"
            android:layout_width="wrap_content"
            android:layout_height="250dp"
            android:layout_marginLeft="150dp"
            android:layout_marginStart="150dp"
            android:layout_marginVertical="110dp"

            android:layout_weight="1"
            android:text="@string/sendsms"
            tools:targetApi="o" />

    </LinearLayout>

    </LinearLayout>

和mapactivity xml  我认为主要问题在这里

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

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapsActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:elevation="10dp"
        android:background="@drawable/white_border"
        android:id="@+id/relLayout1" tools:targetApi="lollipop">

        <ImageView
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:id="@+id/ic_magnify"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:src="@drawable/ic_magnify" android:contentDescription="@string/todoo" android:layout_marginStart="10dp" />

        <AutoCompleteTextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/ic_magnify"
            android:layout_centerVertical="true"
            android:textSize="15sp"
            android:textColor="#000"
            android:id="@+id/input_search"
            android:background="@null"
            android:hint="@string/enter_address_city_or_zip_code"
            android:imeOptions="actionSearch" android:layout_toEndOf="@+id/ic_magnify" />


    </RelativeLayout>

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_below="@id/relLayout1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:scaleType="centerCrop"
        android:id="@+id/ic_gps"
        android:src="@drawable/ic_gps" android:contentDescription="@string/todo" android:layout_alignParentEnd="true" android:layout_marginEnd="10dp" />

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/place_picker"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:scaleType="centerCrop"
        android:layout_below="@+id/relLayout1"
        android:src="@drawable/ic_map" android:contentDescription="@string/todoml" android:layout_marginStart="10dp" />

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_below="@+id/place_picker"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:scaleType="centerCrop"
        android:id="@+id/place_info"
        android:src="@drawable/ic_info" android:layout_marginStart="10dp" android:contentDescription="@string/todoop" />




</RelativeLayout>

谢谢你 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢

谢谢你 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢 谢谢

2 个答案:

答案 0 :(得分:1)

Button sms = (Button) findViewById(R.id.sms);返回null

这意味着他在您的activity_main.xml布局中找不到R.id.sms。

可能是拼写错误或复制粘贴错误?检查此文件中此按钮的ID是否确实为sms

如果您有多个布局用于不同的屏幕尺寸等,请全部选中。

答案 1 :(得分:0)

You have smsBtn as an id for sms Button in your activity_main.xml, whereas you've passed sms as id .So id with sms is not found and so button is null and throws null pointer exception.

There is better approach that can accomplish this using Butterknife library:



    public class MainActivity extends AppCompatActivity


    {
    @BindView(R.id.smsBtn)
    private Button sms;

    @BindView(R.id.btnMap)
    private Button btnMap;


        private static final String TAG = "MainActivity";

        private static final int ERROR_DIALOG_REQUEST = 9001;


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


        }


    @OnClick({R.id.btnMap, R.id.smsBtn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnMap:
           //Your functionality
                break;
            case R.id.smsBtn:
           //Your functionality
                break;
        }
    }
    }


//Dependency for ButterKnife library
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

//Butterknife link
https://github.com/JakeWharton/butterknife