0

I have this problem and it shows me following error

please help me: I get a NullPointerException in init2(). Apperently sms is null. I don't understand the problem

Process: com.example.android.projectdestage, PID: 11049 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.projectdestage/com.example.android.projectdestage.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) at android.app.ActivityThread.-wrap14(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6776) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.android.projectdestage.MainActivity.init2(MainActivity.java:60) at com.example.android.projectdestage.MainActivity.onCreate(MainActivity.java:38) at android.app.Activity.performCreate(Activity.java:6956) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)  at android.app.ActivityThread.-wrap14(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6776)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

****this is my main activity****

    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>

and the the mapactivity xml i think the main problem is here

<?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>

thank you thank you thank you thank you thank you thank you thank you thank you thank you thank you

thank you thank you thank you thank you thank you thank you thank you thank you thank you thank you

Mathias G.
  • 4,093
  • 3
  • 34
  • 56

2 Answers2

1

Button sms = (Button) findViewById(R.id.sms); returns null

This means he can not find R.id.sms in your activity_main.xml layout.

Maybe a typo or copy paste error? Check if this button's ID in this file really is sms.

Also if you have multiple layouts for different screen sizes, etc. Check all of them.

Torge
  • 1,887
  • 1
  • 16
  • 28
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
Dale K
  • 16,372
  • 12
  • 37
  • 62
Kunal Parte
  • 151
  • 1
  • 9