abhimanyuaryan
abhimanyuaryan

Reputation: 4044

Application crashed on Button click saying attempt to invoke virtual method 'void android.widget.Button.setOnClickListener'

This code gives me error while I click on Upload Photo Button of activity_home.xml. This Application was working fine until I didn't added Upload Activity. Upload Activity is all about pushing a picture to ftp server. The Upload Activity works fine as a standalone apk. This error shows when I joined these two separate apks with created an intent b/w the two separate views.

I am not sure does the application crash on button click.

Log Exception

Process: com.muchmore.www.chasquido, PID: 9571
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.muchmore.www.chasquido/com.muchmore.www.chasquido.Upload}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2434)
            at android.app.ActivityThread.access$800(ActivityThread.java:162)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5424)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at com.muchmore.www.chasquido.Upload.onCreate(Upload.java:30)
            at android.app.Activity.performCreate(Activity.java:6093)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2434)
            at android.app.ActivityThread.access$800(ActivityThread.java:162)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5424)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)

Home.java

package com.muchmore.www.chasquido;

import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.ImageView;
import android.content.pm.PackageInfo;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.widget.ImageButton;
import android.view.View;

// new imports
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;


public class Home extends AppCompatActivity {

    static final int REQUEST_IMAGE_CAPTURE = 1;
    ImageView imageView;

    Button btnShowLocation;

    GPSTracker gps;


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


        //          Media Player
        Runnable backgroundSound = new Runnable() {
            @Override
            public void run() {
                MediaPlayer mediaPlayer1= MediaPlayer.create(Home.this, R.raw.welcome_message);
                mediaPlayer1.start();
                MediaPlayer mediaPlayer2= MediaPlayer.create(Home.this, R.raw.welcome_tone);
                mediaPlayer2.start();
            }
        };

        Thread media = new Thread(backgroundSound);
        media.start();
        //          Media Player

        //          Font
        final TextView userMessage = (TextView) findViewById(R.id.welcome_tag);

        Typeface customWelcomeMessage = (Typeface)Typeface.createFromAsset(getAssets(), "PoiretOne-Regular.ttf");
        userMessage.setTypeface(customWelcomeMessage);
        //          Font

        //          Intent Import and show top Text
        Bundle achieve = getIntent().getExtras();
        Boolean anonymousUser = false;

        if(achieve == null){
            anonymousUser = true;
            return;
        }
        String userName= achieve.getString("Username");
        if(anonymousUser == false) {
            userMessage.setText("Welcome " + userName + ", You can now take a snap, edit it and upload it to the Server.");
        }
        if(anonymousUser == true){
            userMessage.setText("Welcome Annoymous User, You can't do anything here. Buzz off!!");
        }
        //          Intent Import and show top Text

        // GPS

        Runnable r = new Runnable() {
            @Override
            public void run() {
                btnShowLocation = (Button)findViewById(R.id.show_location);

                btnShowLocation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        gps = new GPSTracker(Home.this);

                        if(gps.canGetLocation()) {
                            double latitude = gps.getLatitude();
                            double longitude = gps.getLongitude();

                            Toast.makeText(
                                    getApplicationContext(),
                                    "Your Location is -\nLat: " + latitude + "\nLong: "
                                            + longitude, Toast.LENGTH_LONG).show();
                        } else {
                            gps.showSettingsAlert();
                        }
                    }
                });
            }
        };


        Thread th = new Thread(r);
        th.start();
        // GPS

        //          CAMERA BUTTON IMPLEMENTATION
        ImageButton cameraButton = (ImageButton)findViewById(R.id.imageButton);
        imageView = (ImageView)findViewById(R.id.imageView);

                    /* Disable the button if the user doesn't have camera */

        if(!hasCamera())
            cameraButton.setEnabled(false);
        //          CAMERA BUTTON IMPLEMENTATION


    }


    // Upload View Load
    public void loadUpload(View view){
        Log.d("MyMessage", "On Upload Button Click");
        Intent intent = new Intent(Home.this, Upload.class);
        startActivity(intent);
        Log.d("MyMessage", "Starting Intent");
    }
    //



    // Check if the user has a camera

    private boolean hasCamera(){
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
    }

    // Launching the camera
    public void launchCamera(View view){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Take a picture and pass results along to onActivityResult
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }


    // If you want to return the image taken
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
            //Get the photo
            Bundle extras = data.getExtras();
            Bitmap photo = (Bitmap) extras.get("data");
            imageView.setImageBitmap(photo);
        }
    }

activity_home.xml

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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.muchmore.www.chasquido.Home"
    android:background="@drawable/home_background"
    android:id="@+id/home_activity"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome User!!!"
        android:id="@+id/welcome_tag"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#000"
        />

    <ImageButton
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id="@+id/imageButton"
        android:background="@drawable/camera_button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="launchCamera"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:minHeight="300dp"
        android:minWidth="300dp"
        android:layout_above="@+id/imageButton"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Location"
        android:id="@+id/show_location"
        android:layout_above="@+id/imageView"
        android:layout_toRightOf="@+id/imageButton"
        android:layout_toEndOf="@+id/imageButton" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload Photo"
        android:id="@+id/upload"
        android:layout_above="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView"
        android:onClick="loadUpload" />

</RelativeLayout>

Upload.java

package com.muchmore.www.chasquido;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Upload extends Activity {

    private static final int MY_INTENT_CLICK=302;
    private TextView txta;
    private Button btn_selectImage;
    String myGlobalImagePath = "";
    Runnable r;

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

        txta = (TextView) findViewById(R.id.textView1);
        btn_selectImage = (Button) findViewById(R.id.btn_selectImage);

        btn_selectImage.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setType("*/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select File"),MY_INTENT_CLICK);
            }
        });

        r = new Runnable() {
            @Override
            public void run() {
                Ftp obj = new Ftp();
                obj.ftpConnect("cp.mdurtk.in", "cp.mdurtk.in|cp", "cp@123", 21);
                //obj.ftpUpload(myGlobalImagePath,"file.jpg", "/vikas");

                obj.ftpMyUpload(myGlobalImagePath);
            }
        };
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_OK)
        {
            if (requestCode == MY_INTENT_CLICK)
            {
                if (null == data) return;

                String selectedImagePath;
                Uri selectedImageUri = data.getData();

                //MEDIA GALLERY
                selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
                myGlobalImagePath = selectedImagePath;
                Log.i("Image File Path", ""+selectedImagePath);
                txta.setText("File Path : \n"+selectedImagePath);           }
        }
        Thread t = new Thread(r);
        t.start();
    }

}

activity_upload.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Howdy Buddy! Select an image from your device and the image will be automatically uploaded to the server. You need not to do anything. Isn't that cool? Well yaa cool app for cool buddies."
        android:textSize="14sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_selectImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:text="Select Image" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="14sp"
        android:textStyle="bold" />

</LinearLayout>

Upvotes: 0

Views: 1005

Answers (2)

hata
hata

Reputation: 12483

You are setting wrong layout.xml as the content View of Upload Activity.

You should do

setContentView(R.layout.activity_upload);

instead of doing

setContentView(R.layout.activity_main);

Upvotes: 3

Marcelo
Marcelo

Reputation: 4608

You are attempting to call a method on a null object on your Upload.java, line 30.

Upvotes: 0

Related Questions