所以我想从字符串中提取几个字符然后在Textview上显示它,如下所示:
Uri uri = Uri.parse("content://sms/inbox");
Cursor crsr = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(crsr);
String[] columns = new String[] { "address", "person", "date", "body",
"type" };
String address = "";
String msg = "";
ArrayList<String> conversations = new ArrayList<String>();
if (crsr.getCount() > 0) {
while (crsr.moveToNext()) {
address = crsr.getString(crsr.getColumnIndex(columns[0]));
msg = crsr.getString(crsr.getColumnIndex(columns[3]));
msg = msg.substring(1, 30) + "..."; // THIS CAUSES FATAL ERROR
conversations.add(address + "\n\n" + msg);
}
}
使用substring
非常简单,但我无法理解为什么它会给出错误并显示致命错误,这里是跟踪:
E/AndroidRuntime(14023): FATAL EXCEPTION: main
E/AndroidRuntime(14023): java.lang.RuntimeException: Unable to start activity......
E/AndroidRuntime(14023): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2313)
E/AndroidRuntime(14023): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
E/AndroidRuntime(14023): at android.app.ActivityThread.access$600(ActivityThread.java:156)
E/AndroidRuntime(14023): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
E/AndroidRuntime(14023): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(14023): at android.os.Looper.loop(Looper.java:153)
E/AndroidRuntime(14023): at android.app.ActivityThread.main(ActivityThread.java:5336)
E/AndroidRuntime(14023): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(14023): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(14023): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
E/AndroidRuntime(14023): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
E/AndroidRuntime(14023): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:112)
E/AndroidRuntime(14023): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(14023): Caused by: java.lang.StringIndexOutOfBoundsException: length=8; regionStart=1; regionLength=29
E/AndroidRuntime(14023): at java.lang.String.startEndAndLength(String.java:583)
E/AndroidRuntime(14023): at java.lang.String.substring(String.java:1464)
E/AndroidRuntime(14023): at com.sarfraznawaz.cleansms.MainActivity.onCreate(MainActivity.java:41)
E/AndroidRuntime(14023): at android.app.Activity.performCreate(Activity.java:5122)
E/AndroidRuntime(14023): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
E/AndroidRuntime(14023): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
有人能说出这条线有什么问题吗?
msg = msg.substring(1, 30) + "...";
由于
答案 0 :(得分:3)
您的消息msg
不是那么长(少于30个字符长)。这就是问题所在。
答案 1 :(得分:3)
从日志中明确提到,您的字符串长度不是30 。
因此,在使用subString之前,请检查其长度。
if(msg.length()>=30)
msg = msg.substring(1, 30) + "...";
else
msg = msg.substring(1, msg.length()) + "..."; // Also check here string length is more than 1