【问题标题】:Sending ArrayList from Activity to Fragment?将 ArrayList 从 Activity 发送到 Fragment?
【发布时间】:2018-08-13 19:18:47
【问题描述】:

我是 Android 新手,我正在尝试使用 bundle 和 parcelable 从数据库发送一些数据到片段以显示 recyclerview 和 layouttab。使用虚拟数据,我可以在 2 个选项卡中显示 recyclerview。但是当我尝试使用从活动中获取的数据库中的数据时,我遇到了一些麻烦,无法将我得到的数据发送到片段。

我在帖子中尝试了许多相似的解决方案。但直到这次我还不能完全找到正确的解决方案。

这是我的 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到 dummy ArrayList,虚拟数据出现。

然后,我尝试打印从数据库中获取的数据,它显示。但是当我尝试从 MainActivity 打印 arrayList 时,这是我从运行调试文本中得到的

D/调试列表:[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 行。我应该怎么做才能获取、发送和显示数据?

【问题讨论】:

  • 你得到答案了吗?

标签: java android android-fragments arraylist


【解决方案1】:

D/Debug List: [com.xxx.xxx.app.Active@79e903c, com.xxx.xxx.app.Active@8dde1c5, com.xxx.xxx.app.Active@4a1571a] 这是你的activeArrayList。 里面的值是列表中的对象。 您可能应该制作一个自定义回收器视图适配器。 您使用的是字符串数组列表。 因此,制作一个 recyclerviewadapter 并以您可以显示所需数据的方式制作它。

【讨论】:

    【解决方案2】:

    您创建了一个 Fragment 但没有在任何地方添加它,您必须仅在获得数据后填充您的 ViewPagerAdapter:

                FragmentActive fragmentActive = new FragmentActive();
                fragmentActive.setArguments(bundle);
                adapter.addFragment(fragmentActive//
    

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

    【讨论】:

      【解决方案3】:

      您需要在片段中有一个方法来更新ArrayList&lt;Active&gt; 数据,这将 更新回收站视图的适配器数据。

      可能是这样的
      在片段中:

      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();
      }
      

      在 onResponse 中获取数据后,在 FragmentActive 上调用 updateListData
      将 FragmentActive 作为类级变量。

      【讨论】:

      • 我试过这个,但我得到了 RecyclerViewAdapter 上的非静态方法错误,如果我将方法更改为静态,FragmentActive 的错误。
      • 你怎么样了??
      • 在片段中也使recyclerview适配器类级别变量。
      【解决方案4】:

      我通常采用这种应用程序的方法是在活动中填充一个ArrayList(来自数据库),然后让Fragment使用接口从活动中提取数据(或强制转换@987654323 @ 的 Fragment 到你的主要活动的类)当片段变得可见时(参见 setUserVisibleHint() )。

      关于您的代码:

      1) 我看到您使用 FragmentActiveFragmentHistory 初始化了 viewpager,但此时它们没有参数。

      2) 在getDataOder() 中,您为FragmentActive 创建了参数并创建了片段的新实例,但它似乎丢失了,因为它没有做任何其他事情。

      3) 另外,请记住 ViewPager 管理您添加到其中的 Fragments 的生命周期,所以我认为如果您将参数设置为 ViewPager 中使用的片段,可能会发生关联的事情,因为最有可能的是,您创建并设置参数的实例在某些时候将被删除,并替换为缺少参数的新实例。 (我应该对此进行测试,但我相信它会发生)。

      【讨论】:

      • 我还是 android 新手,我正在尝试理解这一点,不知怎的,我明白了它的要点,你有很好的教程参考或与我有相似之处的示例应用程序吗?到目前为止我找到的教程仍然没有给我最好的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多