gpt4 book ai didi

java - 看不懂android asyncTask

转载 作者:行者123 更新时间:2023-11-29 21:15:01 25 4
gpt4 key购买 nike

我有一个应该获得 JSON 响应的方法。在这里:

public  HttpResponse getJson() {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://mysite.com/android/showJson.php"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

showJson.php 返回:["item 1","item 2"]

我面临的问题是我无法在 onCreate 中调用 getJson,因为它会抛出错误:android.os.NetworkOnMainThreadException

我注意到我的方法应该在一个单独的类中,以便在 onCreate 中调用它,但我无法管理它。真的要哭了,我看不懂asyncTask的语法!我知道我遗漏了一些小东西,但作为初学者我无法发现它。

这是 onCreate 方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_jokes);

getJson();
String[] myStringArray = {"a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c"};

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myStringArray);

ListView listView = (ListView) findViewById(R.id.topJokesList);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});

}

我正在用一些测试值填充一个数组并将它们传递给 listView,但现在我需要用 getJson 的项目填充它。

最佳答案

你需要一个 AsyncTask ,您可以在 doInBackground 方法中执行请求。
收到响应后,您需要使用 onPostExecute 方法通知您的主线程 (ui)。

private class JsonTaskTask extends AsyncTask<Void, Void, Void> {
private HttpResponse response;
protected Long doInBackground(Void... params) {
reponse = getJson();
return null;
}

protected void onPostExecute(Void params) {
//Show Your Listview
}

public HttpResponse getJson() {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://mysite.com/android/showJson.php"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}

通过

调用你的AsyncTask
new JsonTaskTask().execute(void, void, void);


要通知您的 UI 并更新您的 ListView,您可以使用监听器界面。例如就像我在 this 中展示的那样回答。

关于java - 看不懂android asyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com