无法从Web服务解析数据并在android中的listview中打印

时间:2015-03-26 04:34:59

标签: android

我正在尝试从网络服务解析数据以在ListView中打印。我能够获取数据并绑定列表,但我在行NullPointerException的{​​{1}} AsyncTask方法中收到onPostExcute(),但我不知道#39;不明白为什么。这是堆栈跟踪和代码:

fruitlist.setadapter(list)

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

如果你要尝试Android开发,你应该投入一些时间和精力来阅读谷歌提供的文档。在本例中为AsyncTask

审核您的代码: -

class download extends AsyncTask<Void, Void, Void>

java类名称应以大写字母开头,例如下载不下载。

您的AsyncTask定义如下: -

Params = Void: the type of the parameters sent to the task upon execution.
Progress = Void: the type of the progress units published during the background computation.
Result = Void: the type of the result of the background computation.

这是错的!您的代码“返回”一个列表,尽管您的实现使用名为list的类变量执行此操作。如果您要使用AsyncTask检索数据,请按照设计的方式使用AsyncTask,例如使用doInbackground()方法返回结果。您应该按如下方式定义AsyncTask

class Download extends AsyncTask<Void, Void, List<DataModel>>

您还应该在doInBackground方法中检查isCancelled()并在protected void onPostExecute(List<DataModel> result) {中使用防御性编码来检测何时收到空结果。

当AsyncTask任务调用活动停止时,您将需要取消AsyncTask,否则将发生异常。您无法控制何时停止活动,您可以控制的是停止活动时的操作。例如当您的活动暂停或停止时,您需要调用AsyncTask cancel(boolean)方法。

仅仅因为您在其他地方使用了相同的代码并且返回数据并不能使此代码正确无误。仅仅因为代码没有失败也不会使代码正确。