我有这个可运行的
Runnable serverChecksRunnable = new Runnable()
{
@Override
public void run()
{
if (connectedSuccess == true)
{
checkServer = Get(iptouse + "uploadstatus");
}
Handler h=new Handler(Looper.getMainLooper());
h.post(new Runnable()
{
@Override
public void run()
{
if (connectedSuccess)
{
if (checkServer != null)
{
String a = null;
try
{
a = new String(checkServer, "UTF-8");
textforthespeacch = a;
{
String varr = textforthespeacch.substring(17,3);
String varr1 = textforthespeacch.substring(0, 16);
String varr2 = textforthespeacch.substring(21);
textforthespeacch = varr1;
status1.setText("Upload completed" + " " + varr + "%");
timerValue.setText("00:00:" + varr2);
numberofuploadedfilescounter += 1;
uploadedfilescount.setText(("Uploaded Files: " + numberofuploadedfilescounter));
MainActivity.this.initTTS();
}
if (textforthespeacch.contains("uploading"))
{
String[] split = textforthespeacch.split(" ");
textforthespeacch = split[0];
status1.setText("Uploading" + " " + split[1] + "%");
servercheckCounter += 1;
if (servercheckCounter == 1)
{
MainActivity.this.initTTS();
}
}
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
}
});
customHandler.postDelayed(serverChecksRunnable,1000);
}
};
var textforthespeacch 是字符串,从 Web 服务器获取文本。 然后我检查它何时包含文本的一部分,将文本部分分配给三个变量:
if (textforthespeacch.contains("upload completed"))
{
String varr = textforthespeacch.substring(17,3);
String varr1 = textforthespeacch.substring(0, 16);
String varr2 = textforthespeacch.substring(21);
问题是程序在第一个子字符串(17,3)处崩溃
语音文本中的文本是:“上传完成 100 0”数字 100 表示百分比,并且始终为 100。数字 0 表示秒数,有时可以更改为 0,有时为 1,有时为 34.5
在 varr 中,我需要将 100 作为字符串“100” 在varr1中“上传完成” 在varr2“0”中
varr2 可能会更改为“0”或“1”或“45.5”,其他 varr 和 varr1 永远不会更改文本“100”和“上传完成”永远不会更改。
这是我收到的 logcat 中的异常消息:
09-15 18:45:45.435 5583-5583/com.test.webservertest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.test.webservertest, PID: 5583
java.lang.StringIndexOutOfBoundsException: length=22; regionStart=17; regionLength=-15
at java.lang.String.startEndAndLength(String.java:504)
at java.lang.String.substring(String.java:1333)
at com.adilipman.webservertest.MainActivity$2$1.run(MainActivity.java:235)
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:5274)
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:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
最佳答案
用这一行
String varr = textforthespeacch.substring(17,2);
substring
调用中的第一个值必须小于第二个值。这就是为什么您会得到 regionLength=-15
。
关于java - 如何使用 java 中的正则表达式或子字符串从字符串中提取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32590359/