在Android开发方面经验很少,我正试图直接从网站上提取HTML。我编写的代码在直接运行java时运行正常,但是当我尝试通过我的应用程序运行它时,我得到"android.os.NetworkOnMainThreadException"
。一些谷歌搜索告诉我,我必须把它放在一个单独的线程中,我相信我已经做了,但它没有帮助。这是我的两个不同的java类文件,第一个是MainActivity
,第二个是我应该处理从网站获取信息的线程。
这是MainActivity:
public class MainActivity extends AppCompatActivity {
public static TextView main = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
main = (TextView) findViewById(R.id.main);
WebsiteDealerino jbae = new WebsiteDealerino();
jbae.start();
}
}
这是我的帖子文件:
public class WebsiteDealerino extends Thread {
public void run(){
try{
WebsiteDealerino jbae = new WebsiteDealerino();
String[] stuff = jbae.getQuestion();
MainActivity.main.setText(stuff[0]);
}catch(Exception e){}
}
public String[] getQuestion() {
try {
return parseHTML(getHTML("http://jbae.po8.org"));
} catch (IOException error) {
return new String[]{"Ran into an error" };
}
}
public String getHTML(String websiteURL) {
String content = null;
URLConnection connection = null;
try {
connection = new URL(websiteURL).openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
} catch (Exception ex) {
ex.printStackTrace();
}
return content;
}
public String[] parseHTML(String rawHTML) throws IOException {
String parsed = "";
boolean relevant;
String[] lines = rawHTML.split(System.getProperty("line.separator"));
for(String line : lines) {
relevant = true;
for (char piece : line.toCharArray()) {
if (piece == '<')
relevant = false;
}
if (relevant)
parsed += "SPLIT" + line;
}
String old = parsed;
parsed = "";
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./,+ *!?|() :^~=";
for (int i = 1; i < old.length(); i++) {
int j = i - 1;
if ((old.toCharArray()[i] == ' ' && !characters.contains(old.toCharArray()[j] + "")))
parsed += "";
else
parsed += old.toCharArray()[i];
}
String fixed = "";
for (char Char : parsed.toCharArray()) {
if (characters.contains(Char + ""))
fixed += Char;
}
String[] parts = fixed.split("SPLIT");
int leng = parts.length;
int lengt = leng - 2;
String[] fixeds = new String[lengt];
int i = 0;
int empties = 0;
for (String part : parts) {
if (i + 2 < parts.length)
if (part.length() <= 1)
i++;
fixeds[i] = parts[i + 2];
empties++;
}
String[] finalized;
if (empties > 0) {
int len = fixeds.length;
finalized = new String[len - empties];
i = 0;
for (String fixe : fixeds) {
if (fixe.length() > 1) {
finalized[i] = fixe;
i++;
}
}
} else
finalized = fixeds;
i = 0;
for (String finale : finalized) {
if (finale.contains("Answer")) {
String answer = "";
String sensible = "0123456789.-";
for (char Char : finale.toCharArray()) {
if (sensible.contains(Char + ""))
answer += Char;
}
finalized[i] = answer;
}
i++;
}
return finalized;
}
}
非常感谢任何帮助。到目前为止尝试了很多东西,没有运气。希望我能跟踪我做得更好的事情,这样我就可以告诉你哪些方法没有做得更好,但无论如何它可能是显而易见的。
以下是我认为是logcat的相关部分:
07-20 21:56:59.919 21503-21503/com.bmassey.android.jbaeapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bmassey.android.jbaeapp, PID: 21503
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bmassey.android.jbaeapp/com.bmassey.android.jbaeapp.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.bmassey.android.jbaeapp.WebsiteDealerino.getHtml(WebsiteDealerino.java:53)
at com.bmassey.android.jbaeapp.MainActivity.onPostCreate(MainActivity.java:36)
at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1188)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2398)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
PS:这段代码的大部分内容都是我对HTML的尴尬解析,我知道大部分代码都没有用,但我想我也可以把它全部放在这里。