【问题标题】:How to populate a listview inside a fragment with data from another fragment?如何使用来自另一个片段的数据填充片段内的列表视图?
【发布时间】:2017-03-06 18:32:03
【问题描述】:

我正在尝试使用来自另一个片段的数据填充我的 Listview。

我能够从另一个片段中获取数据,但是当我尝试创建我的 listview 对象时,它返回 null。

因此,应用程序崩溃了。

我从一个片段中获取用户的数据,然后从另一个片段调用方法来传递数据。我正在第二种方法的 poplist() 方法中制作我的 listview 对象和数组适配器。但是,由于空指针异常,应用程序正在崩溃。 请帮忙。

public class WishListFragment extends Fragment {
   ArrayList<String> wishListTitles = new ArrayList<String>();
   View rootView;
   ListView wishListView;

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
      Context context = getActivity();
      rootView = inflater.inflate(R.layout.fragment_wish_list, container, false);
      return rootView;
   }

   // Another fragment gets the data from user as strings and calls this method
public void popList(String str1, String str2, String str3, Context context) 
{
 // LibModel is a pojo, I am using its constructor to set the values.

 LibModel lm = new LibModel(str1,str2,str3);

    Log.w("Title:",lm.getTitle());
    Log.w("Author:",lm.getAuthor());
    Log.w("Language:",lm.getLang());

        wishListTitles.add(lm.getTitle());

        // I get this on the log, so the ArrayList is made correctly
        Log.w("ArrayList:",wishListTitles.get(0));

        // The listView gives Null Pointer exception and crashes the app
        wishListView = (ListView) rootView.findViewById(R.id.wl_lv);
        ArrayAdapter<String> wishListAdapter = new ArrayAdapter<String>(context,
            android.R.layout.simple_list_item_1,wishListTitles);

        wishListView.setAdapter(wishListAdapter);
    }
}

我尝试了以下方法,但它不起作用

  1. 在制作 Listview 时使用 getView 方法而不是 rootView。
  2. 试图在 onCreateView() 方法中创建列表视图,但列表视图对象为空,我得到空指针。

当它返回 Null 时,我无法找到一种方法来设置列表视图的适配器。

【问题讨论】:

  • 将数据从 FragmentOne 通过 bunlde 传递到 Fragmenttwo,在 Fragmenttwo 获取并填充到适配器/Listview/recyclerview。

标签: android listview android-fragments


【解决方案1】:

我建议在带有数据的片段中使用接口回调。还要在包含片段的活动中保留列表视图的引用。 回调后,接口函数将被执行,您可以从那里更新列表视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多