简体   繁体   中英

How to not repeat myself in this situation? java for android

I know this is an ugly code, but I don't know of a better way to do it. Can't exactly use a for loop since we're only taking one picture each time we click the button. How can I avoid the repeat here?

Repeat Number 1: (taking the picture)

         @Override
         public void onClick(View view) {

             Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

             //Getting the date, minues & seconds
             Date date = new Date();
             DateFormat df = new SimpleDateFormat("MM-dd-hh-mm-ss");

             if (picOne == null) {
                 picOne = "gsiDoc-" + df.format(date);
                 File photo = new File(getExternalFilesDir(null), picOne + ".jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
             } else if (picTwo == null) {
                 picTwo = "gsiDoc-" + df.format(date);
                 File photo = new File(getExternalFilesDir(null), picTwo + ".jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
             } else if (picThree == null) {
                 picThree = "gsiDoc-" + df.format(date);
                 File photo = new File(getExternalFilesDir(null), picThree + ".jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
             } else if (picFour == null) {
                 picFour = "gsiDoc-" + df.format(date);
                 File photo = new File(getExternalFilesDir(null), picFour + ".jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
             } else if (picFive == null) {
                 picFive = "gsiDoc-" + df.format(date);
                 File photo = new File(getExternalFilesDir(null), picFive + ".jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
             } else if (picSix == null) {
                 picSix = "gsiDoc-" + df.format(date);
                 File photo = new File(getExternalFilesDir(null), picSix + ".jpg");
                 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
                 btnCamera.setEnabled(false);
             }

             //Starting Activity
             startActivityForResult(intent, 19);
         }

Repeat Number 2: (Attaching each picture to the e-mail)

    private Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("josh@josh.com", "Josh Thompson"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
    message.setSubject(subject);

    //Message
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(messageBody);

    //Blending
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    if (picOne != null) {
        MimeBodyPart mbpc1 = new MimeBodyPart();
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + picOne + ".jpg");
        mbpc1.setDataHandler(new DataHandler(source));
        mbpc1.setFileName(picOne + ".jpg");
        mp.addBodyPart(mbpc1);
    }
    if (picTwo != null) {
        MimeBodyPart mbpc2 = new MimeBodyPart();
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + picTwo + ".jpg");
        mbpc2.setDataHandler(new DataHandler(source));
        mbpc2.setFileName(picTwo + ".jpg");
        mp.addBodyPart(mbpc2);
    }
    if (picThree != null) {
        MimeBodyPart mbpc3 = new MimeBodyPart();
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + picThree + ".jpg");
        mbpc3.setDataHandler(new DataHandler(source));
        mbpc3.setFileName(picThree + ".jpg");
        mp.addBodyPart(mbpc3);
    }
    if (picFour != null) {
        MimeBodyPart mbpc4 = new MimeBodyPart();
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + picFour + ".jpg");
        mbpc4.setDataHandler(new DataHandler(source));
        mbpc4.setFileName(picFour + ".jpg");
        mp.addBodyPart(mbpc4);
    }
    if (picFive != null) {
        MimeBodyPart mbpc5 = new MimeBodyPart();
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + picFive + ".jpg");
        mbpc5.setDataHandler(new DataHandler(source));
        mbpc5.setFileName(picFive + ".jpg");
        mp.addBodyPart(mbpc5);
    }
    if (picSix != null) {
        MimeBodyPart mbpc6 = new MimeBodyPart();
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + picSix + ".jpg");
        mbpc6.setDataHandler(new DataHandler(source));
        mbpc6.setFileName(picSix + ".jpg");
        mp.addBodyPart(mbpc6);
    }

    message.setContent(mp);
    return message;
}

As you can see, Repeat Number 2 is a bit tricky. For Repeat Number 1 we could use String pic[] = new String[7] and each time the button is pressed we could add +1 on a global int variable as it I tried below.

            n = n+1;

             pic[n] = "gsiDoc-" + df.format(date);
             File photo = new File(getExternalFilesDir(null), pic[n] + ".jpg");
             intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));

             if (n == 6) {
                 btnCamera.setEnabled(false);
             }

However, I tried using MimeBodyPart mbpc[] = new MimeBodyPart[7] with a for loop, like so:

        for (int i = 0; i < 6; i++) {
        FileDataSource source = new FileDataSource(getExternalFilesDir(null) + "/" + pic[i] + ".jpg");
        mbpc[i].setDataHandler(new DataHandler(source));
        mbpc[i].setFileName(pic[i] + ".jpg");
        mp.addBodyPart(mbpc[i]);
        }

If I try and run the code above the app crashes and I get the following error:

        12-27 05:04:26.586  17771-17771/gsi.againmail E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: gsi.againmail, PID: 17771
       java.lang.NullPointerException: Attempt to invoke virtual method 'void javax.mail.internet.MimeBodyPart.setDataHandler(javax.activation.DataHandler)' on a null object reference
        at gsi.againmail.MainActivity.createMessage(MainActivity.java:183)
        at gsi.againmail.MainActivity.sendMail(MainActivity.java:146)
        at gsi.againmail.MainActivity.access$300(MainActivity.java:39)
        at gsi.againmail.MainActivity$1.onClick(MainActivity.java:75)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19749)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        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:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Another problem is that the pic[i] was coming up null:

        12-27 05:07:51.748  18591-18774/gsi.againmail W/System.err﹕ java.io.FileNotFoundException: /storage/emulated/0/Android/data/gsi.againmail/files/null.jpg: open failed: ENOENT (No such file or directory)
        12-27 05:07:51.748  18591-18774/gsi.againmail W/System.err﹕ at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:676)

Here's one example;

if (picOne == null) {
    picOne = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), picOne + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
} else if (picTwo == null) {
    picTwo = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), picTwo + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
} else if (picThree == null) {
    picThree = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), picThree + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
} else if (picFour == null) {
    picFour = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), picFour + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
} else if (picFive == null) {
    picFive = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), picFive + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
} else if (picSix == null) {
    picSix = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), picSix + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    btnCamera.setEnabled(false);
}

could use a simple method like loadPhoto

private String loadPhoto() {
    Date date = new Date();
    DateFormat df = new SimpleDateFormat("MM-dd-hh-mm-ss");
    String str = "gsiDoc-" + df.format(date);
    File photo = new File(getExternalFilesDir(null), str + ".jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    return str;
}

and then

if (picOne == null) {
    picOne = loadPhoto();
} else if (picTwo == null) {
    picTwo = loadPhoto();
} else if (picThree == null) {
    picThree = loadPhoto();
} else if (picFour == null) {
    picFour = loadPhoto();
} else if (picFive == null) {
    picFive = loadPhoto();
} else if (picSix == null) {
    picSix = loadPhoto();
    btnCamera.setEnabled(false);
}

Then if you had your pic (s) in an array you could use something like

String[] arr = { picOne, picTwo, picThree, picFour, picFive, picSix };
for (int i = 0; i < arr.length; i++) {
  if (arr[i] == null) {
    arr[i] = loadPhoto();
    if (i == arr.length - 1) {
      btnCamera.setEnabled(false);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM