我正在开发一款使用Jsoup的Android应用。在开发的早期,我“努力”必须实现任何类型的线程,因为我只想在解决线程之前完成大部分代码。我现在正在尝试使用AsyncTask,但我仍然收到NetworkOnMainThreadException错误。我已经在AsyncTask上阅读了大量的教程和SO帖子,但似乎仍然可以找出问题所在。当我添加StrictMode ...代码时,应用程序按照需要工作,除了使用Jsoup加载数据时的UI锁定。如果有人能告诉我与AsyncTask有关的错误,我将不胜感激。 (P.S.我知道有很多代码冗余需要清理,但我想让AsyncTask先运行)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/***This is the work around used***/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/******/
up = new TreeMap<Double, String[]>();
c1 = "example.com/1";
//instansiate textviews (6)
doc1 = doc;
c2 = "example.com/2";
//instansiate textviews (6)
doc2 = doc;
c3 = "example.com/3";
//instansiate textviews (6)
doc3 = doc;
// instansiate textviews(16)
new Download().execute(c1,c2,c3);
}
private class Download extends AsyncTask<String, Integer, String[][]> {
@Override
protected String[][] doInBackground(String... urls){
out = new String[7][3];
try {
doc = Jsoup.connect(urls[0]).data().get();
//days, times, and cs arrays created and filled
String[] out1arr = {days[0], times[0], cs[0]};
//...all 7
String[] out7arr = {days[6], times[6], cs[6]};
String[][] outarrs = {out1arr,out2arr,out3arr,out4arr,out5arr,out6arr,out7arr};
for (int i= 0; i < out.length; i++){
out[i] = outarrs[i];
}
} catch (IOException e1) {
e1.printStackTrace();
}
return (out);
}
@Override
protected void onProgressUpdate(Integer... progress){
}
@Override
protected void onPostExecute(String[][] result){
Do(/*textviews(6)*/, c1, a, outa, "example1"); //a is previously instantiated double array, outa is preiously instantiated string array
Do(/*textviews(6)*/, c2, b, outb, "example2");
Do(/*textviews(6)*/, c3, c, outc, "example3");
upc00.setText(getUpc()[0][0]);
//setText for all 16
upc32.setText(getUpc()[3][2]);
}
private void Do(TextView t, TextView u, TextView v, TextView w, TextView x, TextView y,String webpage, double[] darr, String[] sarr, String show){
t.setText(doInBackground(webpage)[0][0]);
//...all 6
y.setText(doInBackground(webpage)[1][2]);
for (int i =0; i < darr.length; i++){
darr[i] = tis[i];
up.put(darr[i], out[i]);
}
}
}
private ArrayList<String[]> getMap(){
//...
return s;
}
private String[][] getUpc(){
//...
return upc;
}
答案 0 :(得分:0)
框架调用doInBackground
你不应该自己调用它。您的代码从onPostExecute
进行调用,该调用由UI线程上的框架调用。因此,您的调用会在UI线程上有效运行。
将您的提取逻辑全部移动到doInBackgound
方法中。应使用onPostExecute
方法将结果传递给调用者。