android - 无法在片段 [Android] 中将项目添加到我的 ListView
问题描述
我是一个新手 android 开发人员。我正在构建一个应用程序,它接受来自通过 API 访问的 JSONArray 的数据,并将 JSONArray 的内容放入 ListView。下面给出了将项目添加到列表的代码。
public void AddToList(JSONArray array)
{
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<array.length();i++)
{
try
{
JSONObject state= array.getJSONObject(i);
String item1=state.getString("item1"), item2=state.getString("item2");
list.add("Item1: "+item1+"\n"+"Item2: "+item2);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}
这些项目被添加到列表中,因为相同的代码与不在片段内的 listView 一起使用。但是,现在它只显示一个空白页。
布局代码如下:
<!-- state_frag.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
这里也给出了选项卡之间切换的代码,以防万一。
private BottomNavigationView.OnNavigationItemSelectedListener listener = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
fragment = null;
switch (menuItem.getItemId())
{
case R.id.nav_home:
{
fragment = new HomeFragment();
break;
}
case R.id.nav_states:
{
fragment = new StatesFragment();
break;
}
case R.id.nav_about:
{
fragment = new AboutFragment();
break;
}
}
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, fragment).commit();
CallToAPI call=new CallToAPI();
call.execute("API URL");
return true;
}
};
编辑:片段代码如下:
// StatesFragment.java
public class StatesFragment extends Fragment
{
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.states_frag, container, false);
}
}
问题是什么,我该如何解决?
解决方案
推荐阅读
- python - 当数组中元素的 len 大于 2 时,“解包的值太多(预期为 2)”
- c# - 如何使用 SignalR 向 C# 中的特定用户发送数据?
- python - ValueError:连接轴的所有输入数组维度必须完全匹配,但沿维度 1,
- javascript - 如何自动检索电子邮件文本并进一步抓取它们?
- linux - 如何启用对辅助驱动器的增量热备份?
- python - 通过给定的单个值列表定位数据框中的所有行
- google-sheets - 谷歌表格中的 Sumifs #ref 错误 - 无法解释
- php - HTML + PHP 验证中的日期输入
- jenkins - 使用 jenkins 共享库将工件上传到 S3
- pandas - 如何连续更新数据框列中的每个 NaN 值