从Activity发送ArrayList到Fragment?

4
我是一名有用的助手,可以为您翻译文本。
我是新手Android开发者,尝试使用bundle和parcelable从数据库发送数据到片段(fragment)以显示recyclerview和layouttab。使用虚拟数据时,我可以在2个选项卡中显示recyclerview。但是当我尝试使用从活动(activity)中获取的来自数据库的数据时,我遇到了一些麻烦,无法将获取到的数据发送到片段(fragment)。
我尝试了许多与此类似的帖子中提供的解决方案。但是到目前为止,我仍然无法找到正确的解决方案。
这是我的MainActivity.java文件。
public class MainActivity extends AppCompatActivity {

private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private static final String URL = "http://myweb.com/api/getID.php?id=1";
private String[] ar_id, ar_stat;
private int arr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tabLayout = (TabLayout) findViewById(R.id.tablayout_id);
    viewPager = (ViewPager) findViewById(R.id.viewpager_id);
    adapter = new ViewPagerAdapter(getSupportFragmentManager());

    //Add Fragment
    adapter.AddFragment(new FragmentActive(), "Active");
    adapter.AddFragment(new FragmentHistory(), "History");

    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

    getDataOrder();

}

private void getDataOrder(){
    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray list = response.getJSONArray("result");
                ArrayList<Active> arrayList = new ArrayList<Active>();
                arr = list.length();
                ar_id = new String[arr];
                ar_stat = new String[arr];
                for (int i = 0; i < arr; i++) {
                    JSONObject data = list.getJSONObject(i);
                    ar_id[i] = data.getString("id");
                    ar_stat[i] = data.getString("status");
                    arrayList.add(new Active(ar_id[i], ar_stat[i]));
                }

                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("ac_array", arrayList);
                bundle.putString("test", "123");
                FragmentActive fragmentActive = new FragmentActive();
                fragmentActive.setArguments(bundle);
            } catch (JSONException e) {

            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Fetching ERROR", "ERROR");
        }
    }
    );
    Volley.newRequestQueue(this).add(jsonObjectRequest);
}

}

此外,这是对象类,Active.java
public class Active implements Parcelable {
private String status;

public Active(){

}

public Active(Parcel in){
    super();
    readFromParcel(in);
}

public Active(String id, String status) {
    this.id = id;
    this.status = status;
}

public static final Parcelable.Creator<Active> CREATOR = new Parcelable.Creator<Active>() {
    public Active createFromParcel(Parcel in) {
        return new Active(in);
    }

    public Active[] newArray(int size) {

        return new Active[size];
    }

};

public void readFromParcel(Parcel in){
    id = in.readString();
    status = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(id);
    dest.writeString(status);
}

public String getId() {
    return id;
}

public String getStatus() {
    return status;
}

public void setId(String id) {
    this.id = id;
}

public void setStatus(String status) {
    this.status = status;
}

}

这是碎片类,FragmentActive.java

public class FragmentActive extends Fragment {

View v;
private RecyclerView myrecyclerview;
private ArrayList<Active> lstActive;
//private ArrayList<Active> getArray;

public FragmentActive() {
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ArrayList<Active> activeArrayList = new ArrayList<Active>();
    if (getArguments()!=null) {
        activeArrayList = getArguments().getParcelableArrayList("ac_array");
        String test = getArguments().getString("test");
        Log.d("List", test);
    }else{
        Log.d("List", "Null?");
    }
    v = inflater.inflate(R.layout.active_fragment, container, false);
    myrecyclerview = (RecyclerView) v.findViewById(R.id.active_recyclerview);
    RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), ***activeArrayList***);
    myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
    myrecyclerview.setAdapter(recyclerAdapter);
    return v;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Dummy Data
    lstActive = new ArrayList<>();
    lstActive.add(new Active("1", "1"));
    lstActive.add(new Active("2", "0"));
    lstActive.add(new Active("3", "1"));
}

}

当我运行应用程序时,没有任何错误,只是RecyclerView没有显示出来,但是当我在FragmentActive.onCreateView中将activeArrayList更改为虚拟数组列表时,虚拟数据就会显示出来。
然后,我尝试打印从数据库获取的数据,它显示出来了。但是当我尝试从MainActivity打印ArrayList时,这就是我从运行调试文本中得到的:
D/Debug List: [com.xxx.xxx.app.Active@79e903c, com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a] I/System.out: [com.xxx.xxx.app.Active@79e903c, com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a]
它们是来自数据库的3行吗?因为我选择的数据库显示了3行。我该如何获取、发送和显示数据呢?

你得到了你的答案吗? - Man
4个回答

1
你创建了一个Fragment,但没有将其添加到任何地方,你必须在有数据后才能填充ViewPagerAdapter:
            FragmentActive fragmentActive = new FragmentActive();
            fragmentActive.setArguments(bundle);
            adapter.addFragment(fragmentActive//

您添加到ViewPager中的另一个实例为空,如果您不使用相同的实例,则将为空。

1

您需要在片段中编写一个方法来更新ArrayList<Active>数据,该方法将会更新回收视图的适配器数据。

例如:
在片段中:

public void updateListData(ArrayList<Active> list){
recyclerAdapter.updateData(list);
}

在您的Recycler适配器中有一个名为updateData的方法,例如:

public void updateData(ArrayList<Active> list){
//assign list to your data in adapter
this.lists = list;
notifyDataSetChanged();
}

在收到响应后,在 FragmentActive 上调用 updateListData。将 FragmentActive 作为类级别变量。

我尝试过这个,但是在RecyclerViewAdapter上出现了非静态方法错误,如果我将该方法更改为静态方法,则FragmentActive的一个方法会出错。 - Teletubbies
你在尝试什么? - Man
1
在片段中,还要将recyclerview适配器类作为级别变量。 - Man

1

D/Debug List: [com.xxx.xxx.app.Active@79e903c, com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a] 这是您的activeArrayList。 其中的值是列表中的对象。 您应该制作一个自定义的RecyclerView适配器。 您使用的适配器是用于字符串数组列表的。 因此,制作一个RecyclerView适配器,并使其能够显示所需的数据。


1
我通常处理这种应用程序的方法是在活动中填充一个ArrayList(从数据库中),然后使用接口(或将Fragment的getActivity()转换为主活动类)使Fragment从活动中提取数据,在片段变得可见时执行此操作(请参见setUserVisibleHint())。
关于您的代码:
1) 我看到您使用FragmentActive和FragmentHistory初始化了viewpager,但此时它们没有参数。
2) 在getDataOder()中,您为FragmentActive创建了参数,并创建了一个新的片段实例,但似乎它已丢失,因为没有其他操作。

3) 同时,请记住 ViewPager 管理您添加到其中的 Fragments 的生命周期,因此如果您为在 ViewPager 中使用的片段设置参数,则可能会发生奇怪的事情,因为最有可能的是您创建并设置参数的实例在某个时候将被删除,并替换为缺少参数的新实例。 (我应该测试一下,但我认为会发生这种情况)。


我还是新手安卓开发者,正在努力理解这个问题,不知怎么的,我已经有了大致的理解,你有好的教程参考或者类似于我的示例应用程序吗?到目前为止,我找到的教程仍然没有给出最佳解决方案。 - Teletubbies

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接