【发布时间】:2015-03-11 13:58:26
【问题描述】:
当我编写这段代码时,它给出了NetworkOnMainThreadException,所以我想使用AsyncTask 来实现它,尽管我已经看到了很多关于这个错误的问题和答案,但无法编写它。我想将一个参数传递给Asynctask 类,并想将返回的数据分配给当前类中的一个变量。请帮助我。这是我的代码
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
int tem = 1940+position;
String temp = ""+tem;
String ReceivedData ="<";
GettingInternetData something = new GettingInternetData(temp);
try {
ReceivedData = something.getMoviesData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GettingInternetData.java
public class GettingInternetData {
String y = null;
public GettingInternetData(String year) {
// TODO Auto-generated constructor stub
y = year;
}
public String getMoviesData() throws Exception
{
BufferedReader toRead = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI url = new URI("URL goes here which requires an argument temp");
HttpGet getting = new HttpGet();
getting.setURI(url);
HttpResponse resp = client.execute(getting);
toRead = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
StringBuffer alldata = new StringBuffer();
String l ="";
String nl = System.getProperty("line.Separator");
while((l = toRead.readLine()) !=null)
{
alldata.append(l + nl);
}
toRead.close();
data = alldata.toString();
return data;
}
finally{
if (toRead != null){
try{
toRead.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
提前致谢
【问题讨论】:
-
可怕的问题,许多其他类似问题的重复,但这次你说“我知道我必须使用 AsyncTask”但你没有展示你在使用它时尝试了什么,这是更糟糕...
标签: android android-asynctask networkonmainthread