首页 > 解决方案 > 无法在片段 [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);
    }
}

问题是什么,我该如何解决?

标签: androidandroid-fragmentsandroid-fragmentactivity

解决方案


推荐阅读