0

I have a button that takes a users selected image and then sets it up in an imageView (NOTE: it displays the selected image in a view and then when the user clicks the button, it sets it up in another image view) I did this in the same activity for the background and it worked fine and after looking at my code, I'm not sure what is coming through NULL and how to fix it. Here is the error:

11-14 15:56:07.387: E/AndroidRuntime(25894): FATAL EXCEPTION: main
11-14 15:56:07.387: E/AndroidRuntime(25894): java.lang.NullPointerException
11-14 15:56:07.387: E/AndroidRuntime(25894):    at com.example.awesomefilebuilderwidget.Personalize.scaleDownBitmapForIcon(Personalize.java:127)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at com.example.awesomefilebuilderwidget.Personalize.setIconImageInWidget(Personalize.java:98)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at com.example.awesomefilebuilderwidget.Personalize.onClick(Personalize.java:87)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at android.view.View.performClick(View.java:2532)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at android.view.View$PerformClick.run(View.java:9308)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at android.os.Handler.handleCallback(Handler.java:587)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at android.os.Looper.loop(Looper.java:150)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at android.app.ActivityThread.main(ActivityThread.java:4333)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at java.lang.reflect.Method.invokeNative(Native Method)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at java.lang.reflect.Method.invoke(Method.java:507)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-14 15:56:07.387: E/AndroidRuntime(25894):    at dalvik.system.NativeStart.main(Native Method)

Here is my Personalize.java:

public class Personalize extends Activity implements View.OnClickListener
{
    Button button;
    ImageView image;
    ImageView image2;
    Button btnChangeImage;
    Button btnChangeImageForIcon;
    Button btnSetBackground;
    private static final int SELECT_PICTURE = 1;
    private static final int SELECT_PICTURE_2 = 2;
    private String selectedImagePath;
    Bitmap background;
    Bitmap b2;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personalize);
        Log.d("Personalize", "OnCreate called");

        image = (ImageView) findViewById(R.id.imageView1);
        image2 = (ImageView) findViewById(R.id.imageView2Icon);

        Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);
        btnChangeImage.setOnClickListener(this);

        Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon);
        btnChangeImageForIcon.setOnClickListener(this);

        Button btnSetBackground = (Button) findViewById(R.id.btnSetBackground);
        btnSetBackground.setOnClickListener(this);

        Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);

        Button btnSetIcon = (Button) findViewById(R.id.btnSetIcon);
        btnSetIcon.setOnClickListener(this);

        // Link to Feedback Screen
        btnLinkToFeedback.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view)
            {
                Intent i = new Intent(getApplicationContext(), Feedback.class);
                startActivity(i);
                Log.d("Personalize", "LinkToFeedBack called");
                finish();
            }
        });

    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId()) {
            case R.id.btnChangeImage:
                launchImageChooser();
                break;
            case R.id.btnChangeImageForIcon:
                launchImageChooser2();
                break;
            case R.id.btnSetBackground:
                setBackgroundImageInDragAndDrop();
                break;
            case R.id.btnSetIcon:
                setIconImageInWidget();
                break;
        }
    }

    private void setIconImageInWidget()
    {
        // TODO Auto-generated method stub
        Log.d("Personalize", "setIconImageInWidget() called");
        Intent i = getIntent();
        // Convert bitmap to byte array to send back to activity
        // See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
        scaleDownBitmapForIcon(b2, 500, this.getBaseContext());
        Log.d("Personalize", "Scale Bitmap Chosen For Icon");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        b2.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        i.putExtra("myIconBitmap", byteArray);
        setResult(RESULT_OK, i);
        finish();
    }

    public static Bitmap scaleDownBitmap(Bitmap background, int newHeight, Context c)
    {

        final float densityMultiplier = c.getResources().getDisplayMetrics().density;

        int h = (int) (500 * densityMultiplier);
        int w = (int) (h * background.getWidth() / ((double) background.getHeight()));

        background = Bitmap.createScaledBitmap(background, w, h, true);
        // TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-
        // other-activity-getting-message-on-logcat-failed-binder-transac
        return background;
    }

    public static Bitmap scaleDownBitmapForIcon(Bitmap b2, int newHeight, Context c)
    {

        final float densityMultiplier = c.getResources().getDisplayMetrics().density;

        int h = (int) (500 * densityMultiplier);
        int w = (int) (h * b2.getWidth() / ((double) b2.getHeight()));

        b2 = Bitmap.createScaledBitmap(b2, w, h, true);
        // TO SOLVE LOOK AT
        // HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
        return b2;
    }

    private void setBackgroundImageInDragAndDrop()
    {
        Log.d("Personalize", "setBackgroundImageInDragAndDrop() called");
        Intent i = getIntent();
        // Convert bitmap to byte array to send back to activity
        // See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
        scaleDownBitmap(background, 500, this.getBaseContext());
        Log.d("Personalize", "Scale Bitmap Chosen");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        background.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        i.putExtra("myBackgroundBitmap", byteArray);
        setResult(RESULT_OK, i);
        finish();
    }

    private void launchImageChooser()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PICTURE);
        Log.d("Personalize", "launchImageChooser called");
    }

    private void launchImageChooser2()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PICTURE_2);
        Log.d("Personalize", "launchImageChooser2 called");
    }

    public String getPath(Uri uri)
    {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String imagePath = cursor.getString(column_index);
        if (cursor != null) {
            cursor.close();
        }
        return imagePath;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {

        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                background = getAndDecodeImage(selectedImagePath);
                if (background != null) {
                    image.setImageBitmap(background);
                }
            } else if (requestCode == SELECT_PICTURE_2) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                Bitmap b2 = getAndDecodeImage(selectedImagePath);
                if (b2 != null) {
                    image2.setImageBitmap(b2);
                }
            }
        }
    }

    private Bitmap getAndDecodeImage(String selectedImagePath)
    {
        try {
            Log.d("Personalize", "selectedImagePath: " + selectedImagePath);
            FileInputStream fileis = new FileInputStream(selectedImagePath);
            BufferedInputStream bufferedstream = new BufferedInputStream(fileis);
            byte[] bMapArray = new byte[bufferedstream.available()];
            bufferedstream.read(bMapArray);
            Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);

            if (fileis != null) {
                fileis.close();
            }
            if (bufferedstream != null) {
                bufferedstream.close();
            }
            return bMap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean saveImageToInternalStorage(Bitmap image)
    {
        try {
            FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
            image.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}

Thanks!

NEW NPE:

11-14 16:47:54.498: E/AndroidRuntime(27568): FATAL EXCEPTION: main
11-14 16:47:54.498: E/AndroidRuntime(27568): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=10, result=-1, data=Intent { cmp=com.example.awesomefilebuilderwidget/.Personalize (has extras) }} to activity {com.example.awesomefilebuilderwidget/com.example.awesomefilebuilderwidget.Drag_and_Drop_App}: java.lang.NullPointerException
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2974)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3026)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.ActivityThread.access$2000(ActivityThread.java:135)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1071)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.os.Looper.loop(Looper.java:150)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.ActivityThread.main(ActivityThread.java:4333)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at java.lang.reflect.Method.invokeNative(Native Method)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at java.lang.reflect.Method.invoke(Method.java:507)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at dalvik.system.NativeStart.main(Native Method)
11-14 16:47:54.498: E/AndroidRuntime(27568): Caused by: java.lang.NullPointerException
11-14 16:47:54.498: E/AndroidRuntime(27568):    at com.example.awesomefilebuilderwidget.Drag_and_Drop_App.onActivityResult(Drag_and_Drop_App.java:180)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.Activity.dispatchActivityResult(Activity.java:4053)
11-14 16:47:54.498: E/AndroidRuntime(27568):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2970)
11-14 16:47:54.498: E/AndroidRuntime(27568):    ... 11 more

onActivityResult (as stated in error):

     @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     Log.i("Drag_and_Drop_App", "requestCode: " + requestCode + ", resultCode: " + resultCode); 
     if(requestCode == SET_BACKGROUND && resultCode == RESULT_OK){ 
     byte[] byteArray = data.getByteArrayExtra("myBackgroundBitmap"); 
     Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 
     setBackgroundImage(myBackground); 
     } 
     else if(requestCode == SET_ICON && resultCode == RESULT_OK){
         byte[] byteArray = data.getByteArrayExtra("myIconBitmap"); 
         Bitmap myIcon = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 
         setBackgroundImageForIcon(myIcon); 
     }
     } 
user2909006
  • 253
  • 6
  • 22

1 Answers1

1

b2 is null because here

 int w = (int) (h * b2.getWidth() / ((double) b2.getHeight()));

 b2 = Bitmap.createScaledBitmap(b2, w, h, true);

In the first line you try to call a method on it, getHeight(), but you don't initialize it until the second line so when you try to initialize w then b2 is still null.

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • I kind of understand what you mean. I'm confused when you said "...don't initialize it until the second line so when you try to initialize `w` then `b2` is still `null`" in that I thought I was defining `w` before I was using it in the second line. Maybe I'm just misunderstanding. – user2909006 Nov 14 '13 at 23:37
  • What you are doing with `w` is fine. But at that point `b2` is still `null` because you haven't given it a value yet. So when you call a method on `b2` ( a null object) you get a `NPE`. You need a different way to do it because the initialization of each variable depends on the other. – codeMagic Nov 14 '13 at 23:39
  • Ok I see what you mean, yeah that makes sense. Actually, after looking over my coding again, I found that on this line `Bitmap b2 = getAndDecodeImage...` that I had the extra Bitmap declaration there so I deleted that and it fixed the `NPE` I was getting, but now I am getting a new one saying that it is failing to deliver my results. Would this still be caused by the `b2` returning null as you stated above? – user2909006 Nov 14 '13 at 23:53
  • Possibly but I don't know what this means or where its coming from, "is failing to deliver my results" – codeMagic Nov 14 '13 at 23:58
  • Please look at the NEW NPE section I added to the question where I put the error...I'll add my OnResult section too (as stated in the error) – user2909006 Nov 14 '13 at 23:59
  • Line 180 is `Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); ` but I think it is returning the wrong request code and trying to set it up as a background...I'm not sure though. – user2909006 Nov 15 '13 at 00:02
  • So it looks like `byteArray` is `null` there. Debug and check that out. Check the request code when it returns and see what you are sending. We can't check that – codeMagic Nov 15 '13 at 00:03
  • It sounds like you have a good idea of *how* to check for what might be wrong so you need to do that – codeMagic Nov 15 '13 at 00:04
  • Ok so after looking around, I see where I am sending the seperate request codes and why it is choosing one over the other (because I only send the one request code in, not the one that I want for the icon). Can you help me to figure out where to send my request code for my icon so that it doesn't interfer with my request code for setting the background? I'll explain more in a chat if you're willing to help. :) – user2909006 Nov 15 '13 at 00:11
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/41228/discussion-between-user2909006-and-codemagic) – user2909006 Nov 15 '13 at 00:11
  • @user2909006 did we get it taken care of? – codeMagic Nov 15 '13 at 01:05