我想知道为什么我的编码部分不起作用,并且程序在交换机上一直给我同样的错误;
(无法为1.7以下的源级别打开String类型的值。只允许使用可转换的int值或枚举变量)
我想读取我保存为txt文件的文件并将其显示在程序中。
例如:我在那里写了“电子邮件”作为案例,所以我写了我想要的内容并将其保存到txt文件中以便在此开关中读取。
任何人都可以帮我解决这个问题吗?深深感激。感谢。
这是我的代码:
private void ExecuteCommands(String filename) {
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, filename + ".txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] tmp = line.split(" ");
//this switch case giving me problem
switch(tmp[0]){
case "Email":
String subject = sbj.getText().toString();
String message = messageBody.getText().toString();
String to = destinationAddress.getText().toString();
Intent emailActivity = new Intent(Intent.ACTION_SEND);
//set up the recipient address
emailActivity.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
//set up the email subject
emailActivity.putExtra(Intent.EXTRA_SUBJECT, subject);
//you can specify cc addresses as well
// email.putExtra(Intent.EXTRA_CC, new String[]{ ...});
// email.putExtra(Intent.EXTRA_BCC, new String[]{ ... });
//set up the message body
emailActivity.putExtra(Intent.EXTRA_TEXT, message);
emailActivity.setType("message/rfc822");
startActivity(Intent.createChooser(emailActivity, "Select your Email Provider :"));
break;
case "SMS message":
String phoneNo = textPhoneNo.getText().toString();
String sms = textSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
break;
}
}
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
答案 0 :(得分:1)
如何在Java
版本7下的字符串中不能使用switch / case,考虑使用enum,但是你的switch case字符串如何包含空格,你无法通过{{1}检索枚举常量枚举方法,但你可以添加自己的方法来检索基于特定字符串的对应枚举。像这样。
valutOf
}
以及基于字符串值返回对应类型的公共静态方法。
enum Type {
EMAIL {
@Override
public boolean counterpart(String value) {
if (value.equals(EMAIL)) {
return true;
}
return false;
}
},
SMS {
@Override
public boolean counterpart(String value) {
if (value.equals(SMS_TAG)) {
return true;
}
return false;
}
};
private static final String EMAIL_TAG = "Email";
private static final String SMS_TAG = "SMS Message";
public abstract boolean counterpart(String value);
然后你应该有这样的开关
public static Type getType( String value ) {
for (Type t : Type.values()) {
if (t.counterpart(value )) {
return t;
}
}
return Type.EMAIL;
}