您好我正在使用phonegap进行应用,需要多个附件,但我无法拥有多个附件。任何解决方案。我的代码如下:
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="emailcomposer.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", deviceready, true);
function deviceready() {
console.log("Device ready");
}
function composeText(){
var attachPath;
var attachFile= new Array();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory("RepairMyCar", {
create: true
}, function(directory) {
console.log("Final 63" + directory.fullPath);
attachPaths = directory.fullPath;
var attachPath=attachPaths.slice(7,attachPaths.length);
var directoryReader = directory.createReader();
directoryReader.readEntries(function(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
attachFile[i] ='"' + attachPath + "/" + entries[i].name + '"';
}
}, function (error) {
alert(error.code);
});
});
}, function(error) {
alert("can't even get the file system: " + error.code);
});
//var vehiclemake = document.getElementById("vehiclemake");
//var strUser = vehiclemake.options[vehiclemake.selectedIndex].value;
var vehiclemileage = document.getElementById('vehiclemileage').value;
var vehiclemodel = document.getElementById('vehiclemodel').value;
var message1 = document.getElementById('message_body').value;
console.log(message1);
console.log("Composer" + attachFile);
var newAttachment = attachFile.toString();
console.log(newattachment);
window.plugins.emailComposer.showEmailComposer(
"Get an Estimate",
"Model of Vehicle " + " " + vehiclemodel + "Mileage of Vehicle " + " " + vehiclemileage + message1,
["sth@sth.com"],
[],
[],
true,
[newAttachment]
);
//exit the app after clicking this button
//navigator.app.exitApp();
// navigator.camera.cleanup(onSuccess,fail);
// function onSuccess(){
// }
// function fail(){
// }
}
function onFail(message) {
alert('Failed because: ' + message);
}
/***********************************************
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield){
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
dayfield.options[i]=new Option(i, i+1)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=today.getFullYear()
for (var y=0; y<25; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear-=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
</head>
<body>
<div class="wrapper">
<h1>Get a Repair Estimate</h1>
<div class="main-content">
<p>
Please Enter the Year, Make, Model and Mileage of Your Vehicle and any other information we should know.
</p>
<form class="vehicle-detail-form">
<ul>
<li>
<label>Year of Vehicle: </label>
<form action="" name="someform">
<select id="daydropdown">
</select>
<select id="monthdropdown">
</select>
<select id="yeardropdown">
</select>
</form>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
</li>
<!-- Vehicle Year Selection -->
<li><label>Make of Vehicle:</label>
<!-- Model of Vehicle Selection -->
</li>
<li><label>Model of Vehicle:</label>
<input type="text" name="pnum" id = "vehiclemodel">
</li>
<li><label>Mileage of Vehicle:</label>
<input type="number" name="pnum" id = "vehiclemileage"></li>
<li>
<textarea name="message_body" id = 'message_body' placeholder="Add Notes here(if any)"></textarea>
</li>
</form>
<div style="clear:both;"></div>
<div class="large-button-wrapper">
<button onclick="composeText();">Get Your Estimate</button>
</div>
</div>
</div>
</body>
</html>
我正在使用EmailComposer.java,如下所示
/**
*
* Phonegap Email composer plugin for Android with multiple attachments handling
*
* Version 1.0
*
* Guido Sabatini 2012
*
*/
package org.apache.cordova.plugin;
import java.io.File;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
public class EmailComposer extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("showEmailComposer".equals(action)) {
try {
JSONObject parameters = args.getJSONObject(0);
if (parameters != null) {
sendEmail(parameters);
}
} catch (Exception e) {
}
callbackContext.success();
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
private void sendEmail(JSONObject parameters) {
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
//String callback = parameters.getString("callback");
boolean isHTML = false;
try {
isHTML = parameters.getBoolean("bIsHTML");
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling isHTML param: " + e.toString());
}
if (isHTML) {
emailIntent.setType("text/html");
} else {
emailIntent.setType("text/plain");
}
// setting subject
try {
String subject = parameters.getString("subject");
if (subject != null && subject.length() > 0) {
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling subject param: " + e.toString());
}
// setting body
try {
String body = parameters.getString("body");
if (body != null && body.length() > 0) {
if (isHTML) {
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body));
} else {
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
}
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling body param: " + e.toString());
}
// setting TO recipients
try {
JSONArray toRecipients = parameters.getJSONArray("toRecipients");
if (toRecipients != null && toRecipients.length() > 0) {
String[] to = new String[toRecipients.length()];
for (int i=0; i<toRecipients.length(); i++) {
to[i] = toRecipients.getString(i);
}
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, to);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling toRecipients param: " + e.toString());
}
// setting CC recipients
try {
JSONArray ccRecipients = parameters.getJSONArray("ccRecipients");
if (ccRecipients != null && ccRecipients.length() > 0) {
String[] cc = new String[ccRecipients.length()];
for (int i=0; i<ccRecipients.length(); i++) {
cc[i] = ccRecipients.getString(i);
}
emailIntent.putExtra(android.content.Intent.EXTRA_CC, cc);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling ccRecipients param: " + e.toString());
}
// setting BCC recipients
try {
JSONArray bccRecipients = parameters.getJSONArray("bccRecipients");
if (bccRecipients != null && bccRecipients.length() > 0) {
String[] bcc = new String[bccRecipients.length()];
for (int i=0; i<bccRecipients.length(); i++) {
bcc[i] = bccRecipients.getString(i);
}
emailIntent.putExtra(android.content.Intent.EXTRA_BCC, bcc);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling bccRecipients param: " + e.toString());
}
// setting attachments
try {
JSONArray attachments = parameters.getJSONArray("attachments");
if (attachments != null && attachments.length() > 0) {
ArrayList<Uri> uris = new ArrayList<Uri>();
//convert from paths to Android friendly Parcelable Uri's
for (int i=0; i<attachments.length(); i++) {
try {
File file = new File(attachments.getString(i));
if (file.exists()) {
Uri uri = Uri.fromFile(file);
uris.add(uri);
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error adding an attachment: " + e.toString());
}
}
if (uris.size() > 0) {
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
}
}
} catch (Exception e) {
LOG.e("EmailComposer", "Error handling attachments param: " + e.toString());
}
this.cordova.startActivityForResult(this, emailIntent, 0);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// TODO handle callback
super.onActivityResult(requestCode, resultCode, intent);
LOG.e("EmailComposer", "ResultCode: " + resultCode);
// IT DOESN'T SEEM TO HANDLE RESULT CODES
}
}
我的错误堆栈跟踪是
10-01 14:03:16.129: W/Bundle(7685): Key android.intent.extra.TEXT expected ArrayList<CharSequence> but value was a android.text.SpannableStringBuilder. The default value <null> was returned.
10-01 14:03:16.149: W/Bundle(7685): Attempt to cast generated internal exception:
10-01 14:03:16.149: W/Bundle(7685): java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to java.util.ArrayList
10-01 14:03:16.149: W/Bundle(7685): at android.os.Bundle.getCharSequenceArrayList(Bundle.java:1326)
10-01 14:03:16.149: W/Bundle(7685): at android.content.Intent.getCharSequenceArrayListExtra(Intent.java:4571)
10-01 14:03:16.149: W/Bundle(7685): at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7066)
10-01 14:03:16.149: W/Bundle(7685): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1425)
10-01 14:03:16.149: W/Bundle(7685): at android.app.Activity.startActivityForResult(Activity.java:3446)
10-01 14:03:16.149: W/Bundle(7685): at android.app.Activity.startActivityForResult(Activity.java:3407)
10-01 14:03:16.149: W/Bundle(7685): at org.apache.cordova.CordovaActivity.startActivityForResult(CordovaActivity.java:825)
10-01 14:03:16.149: W/Bundle(7685): at org.apache.cordova.plugin.EmailComposer.sendEmail(EmailComposer.java:158)
10-01 14:03:16.149: W/Bundle(7685): at org.apache.cordova.plugin.EmailComposer.execute(EmailComposer.java:37)
10-01 14:03:16.149: W/Bundle(7685): at org.apache.cordova.api.CordovaPlugin.execute(CordovaPlugin.java:66)
10-01 14:03:16.149: W/Bundle(7685): at org.apache.cordova.api.PluginManager.exec(PluginManager.java:215)
10-01 14:03:16.149: W/Bundle(7685): at org.apache.cordova.ExposedJsApi.exec(ExposedJsApi.java:51)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewCore.nativeMouseClick(Native Method)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewCore.nativeMouseClick(Native Method)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewCore.access$14000(WebViewCore.java:72)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewCore$EventHub.dispatchWebKitEvent(WebViewCore.java:2996)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewInputDispatcher.dispatchWebKitEvent(WebViewInputDispatcher.java:914)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewInputDispatcher.dispatchWebKitEvents(WebViewInputDispatcher.java:813)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewInputDispatcher.access$900(WebViewInputDispatcher.java:78)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewInputDispatcher$WebKitHandler.handleMessage(WebViewInputDispatcher.java:1433)
10-01 14:03:16.149: W/Bundle(7685): at android.os.Handler.dispatchMessage(Handler.java:99)
10-01 14:03:16.149: W/Bundle(7685): at android.os.Looper.loop(Looper.java:137)
10-01 14:03:16.149: W/Bundle(7685): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:1069)
10-01 14:03:16.149: W/Bundle(7685): at java.lang.Thread.run(Thread.java:856)
答案 0 :(得分:2)
错误在行
中emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body));
问题是HTML.fromHtml(body)返回一个android.text.SpannableStringBuilder,它不能被转换为java.util.ArrayList。 尝试用
替换那行代码emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body).toString());
或
ArrayList<String> list = new ArrayList<String>();
list.add(Html.fromHtml(body).toString());
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, list);
答案 1 :(得分:0)
好吧,根据google搜索时的链接,我没有必要进行任何编辑。我只是犯了一些拼写错误和路径错误。
我的代码如下:
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="emailcomposer.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", deviceready, true);
function deviceready() {
console.log("Device ready");
}
function composeText(){
var attachPath;
var attachFile= new Array();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory("MyAppFolder", {
create: true
},
function(directory) {
console.log("Final 63" + directory.fullPath);
attachPaths = directory.fullPath;
var attachPath=attachPaths.slice(7,attachPaths.length);
var directoryReader = directory.createReader();
directoryReader.readEntries(function(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
attachFile[i] =attachPath + "/" + entries[i].name;
}
console.log(attachFile);
},
function (error) {
alert(error.code);
});
});
}, function(error) {
alert("can't even get the file system: " + error.code);
});
var dated, fnamed, phoned, emailed;
if(typeof(Storage)!=="undefined")
{
dated = localStorage.date;
fnamed = localStorage.fname;
phoned = localStorage.phone;
emailed= localStorage.email;
}
var vehiclemileage = document.getElementById('vehiclemileage').value;
var vehiclemodel = document.getElementById('vehiclemodel').value;
var message1 = document.getElementById('message_body').value;
var vechicleyear = document.getElementById("yeardropdown");
var strUser = vechicleyear.options[vechicleyear.selectedIndex].value;
var vehiclemake = document.getElementById("vehiclemake");
var makevehicle = vehiclemake.options[vehiclemake.selectedIndex].value;
console.log(attachFile);
var newattachment = attachFile.toString();
window.plugins.emailComposer.showEmailComposerWithCallback(null,
"Get an Estimate",
"Date" + dated + "First Name " + fnamed + "Phone Number" + phoned + "Email Address" + emailed + "Year of Vehicle" + strUser + "Make of Vehicle" + makevehicle + "Model of Vehicle " + " " + vehiclemodel +
"Mileage of Vehicle " + " " + vehiclemileage + message1,
["sth@sth.com"],
[],
[],
true,
attachFile
);
//Clear LoccalStorage
localStorage.clear();
//exit the app after clicking this button
//navigator.app.exitApp();
// navigator.camera.cleanup(onSuccess,fail);
// function onSuccess(){
// }
// function fail(){
// }
}
function onFail(message) {
alert('Failed because: ' + message);
}
/***********************************************
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
function populatedropdown(yearfield){
var today=new Date()
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++)
//Select Year
var thisyear=today.getFullYear()
for (var y=0; y<25; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear-=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
</head>
<body>
<div class="wrapper">
<h1>Get a Repair Estimate</h1>
<div class="main-content">
<p>Please Enter the Year, Make, Model and Mileage of Your Vehicle and any other information we should know.
</p>
<form class="vehicle-detail-form">
<ul>
<li>
<label>Year of Vehicle: </label>
<form action="" name="someform">
<select id="yeardropdown">
</select>
</form>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("yeardropdown")
}
</script>
</li>
<!-- Vehicle Year Selection -->
<li><label>Make of Vehicle:</label>
<!-- Model of Vehicle Selection -->
</li>
<li><label>Model of Vehicle:</label>
<input type="text" name="vehiclemodel" id = "vehiclemodel">
</li>
<li><label>Mileage of Vehicle:</label>
<input type="number" name="vehiclemileage" id = "vehiclemileage"></li>
<li>
<textarea name="message_body" id = 'message_body' placeholder="Add Notes here(if any)"></textarea>
</li>
</form>
<div style="clear:both;"></div>
<div class="large-button-wrapper">
<button onclick="composeText();">Get Your Estimate</button>
</div>
</div>
</div>
</body>
</html>
<!-- -->