我有四類:如果Android中有多個類,應該在哪裏實現AsyncTask類的方法?
MainActivity extends AppCompactActivity
MainAsyncTask extends AsyncTask<String, String, List>
Intermediate
延伸MainAsyncTask和具有雙重功能。 (FuncA,FuncB)Leaf extends Intermediate
和實施doInBackground()
和onPostExecute()
。
當我運行該應用程序會提示:
無法實例活動ComponentInfo {}:android.os.NetworkonMainThreadException。
我該如何擺脫錯誤。據我瞭解,doInBackground()
和onPostExecute()
應該在MainAsyncTask
類中實現嗎?
類是: MianActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Leaf object = new Leaf();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fab = (Button) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
object.execute();
}
});
}
}
MainAsyncTask.java
import android.os.AsyncTask;
public class MainAsync extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(String... text) {
}
}
Intermediate.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class Intermediate extends MainAsync{
public Document FunA(){
System.out.println("Printed FunA()");
String url = "http://blogs.tribune.com.pk/story/37034/zakir-naik-has-a-large-following-in-pakistan-should-we-be-alarmed/";
Document doc = null;
try {
doc = Jsoup.connect(url).timeout(10 * 1000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
public void FunB(){ System.out.println("Printed FunB()");}
}
}
Leaf.java
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Leaf extends Intermediate{
Document HTM = FunA();
public void FunC() {
String heading = "";
System.out.println("Printed FunC()");
Elements seep = HTM.select("h1");
for (Element foo : seep) {
heading = foo.text();
System.out.println(heading);
break;
}
}
public void FunD() {
System.out.println("Printed FunD()");
}
public void FunE() {
System.out.println("Printed FunE()");
}
@Override
protected String doInBackground(String... params) {
FunB();FunC();FunD();FunE();
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(String... text) {
}
}
這樣做的目的是在Leaf
類中的一個類中添加和FuncB
以及AsyncTask
方法。
錯誤是說你正在嘗試在主線程上運行網絡操作。您沒有發佈代碼,因此無法確定您的錯誤所在。 – Kuffs
@Kuffs更新。 – waqas
由於沒有網絡操作,您的發佈代碼拋出此異常是不可能的。 – Kuffs