【问题标题】:unable to send array to listview in android无法将数组发送到android中的listview
【发布时间】:2023-03-25 22:24:02
【问题描述】:

我正在尝试从服务器获取菜单项的 json 列表,对其进行解析,并将其显示在片段视图中。完整代码在这里:http://pastebin.com/8UEgcyfa

在添加获取 json 和解析的代码之前,该应用只是显示来自字符串资源的硬编码菜单项列表,如下所示:

String[] adobe_products = getResources().getStringArray(R.array.adobe_products);

// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.fragment_viewdishes, R.id.label, adobe_products));

这工作正常。在尝试实际打印解析后收到的菜单项时,我在 onPostExecute 方法中执行了此操作(请参阅完整代码),其中 menuNameArray,(我认为)正确保存了我实际需要在 ListView 上显示的菜单项数组:

this.setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.fragment_viewdishes, R.id.label, adobe_products));

IntelliJ IDEA 此时会抛出错误:Cannot resolve method setListAdapter。我认为它实际上是需要调用的 ViewDishes.setListAdapter,但它引发了另一个错误:Non static method cannot be referenced from a static content

请告诉我如何克服这个错误?

【问题讨论】:

  • 所以你想在listview上显示json数据?
  • 你能发布你的java文件吗?
  • @Apoorv 描述中提到了 java 文件。 [pastebin.com/8UEgcyfa]
  • @ZubairAhmadKhan 我想显示解析后的菜单项,而不是确切的 json,如果这就是你的要求的话。

标签: java android listview intellij-idea


【解决方案1】:

替换

this.setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.fragment_viewdishes, R.id.label, adobe_products));

通过

ViewDishes.this.setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.fragment_viewdishes, R.id.label, adobe_products));

setListAdapterListFragment 的方法,而不是Asynctask,因此您需要在onPostExecute 中使用ViewDishes.this 而不是this

【讨论】:

  • 谢谢。我试过了。代码编译成功。在模拟器中执行后,应用程序退出。这是 logcat 输出:pastebin.com/pUgr8QWU
  • 另外,我尝试用谷歌搜索这个错误,几乎到处都提到我应该有一个 android:id="@id/android:list" ,但以前是正确的。
【解决方案2】:

首先:改为ViewDishes.this.setListAdapter(....)

第二:您不能使用带有默认 ArrayAdapter 的自定义视图。您将 R.layout.fragment_viewdishes 传递给 ArrayAdapter。但是这个布局是你的自定义视图,默认的 ArrayAdapter 并不知道。因此,要么传递默认列表项布局(如 android.R.layout.simple_list_item_1 ),要么创建您的 CustomArrayAdapter 并覆盖 getView() 方法来扩展您的自定义布局。

【讨论】:

  • 在应用您的建议后,我收到了java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'。我猜这个错误是因为列表需要显示在片段视图中。这可能是一个原因吗?
  • 那是因为 ListFragment 期望 id 是那个。您可以更改 setContentView 布局中的 id。或者使用普通的 Fragment 并在其中使用您自己的 listView
猜你喜欢
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多