简体   繁体   中英

How to send the arraylist<Model> to Fragment adapter

I want to pass the arraylist to the fragment adapter. However, I really not understand how to use Bundle to pass the arraylist from main activity to the fragment adapter, anyone can help? Thanks. I tried to implements parcelable in my model. But it cannot get Bundle extra = getIntent().getExtras(); . Any ideas to fix my problem, since I am trying to get the arraylist object and set them in the fragment adapter

package com.example.myapplication;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import java.util.ArrayList;


public class FragmentAdapter extends FragmentStatePagerAdapter{
    private ArrayList<EssayElement> essayList;


    public FragmentAdapter(FragmentManager fm, ArrayList<EssayElement> mList) {
        super(fm);
        this.essayList = mList;
    }

    @Override
    public Fragment getItem(int position) {
        SwipeFragment swipeFragment= new SwipeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("titleString", essayList.get(position).getTitle());
        bundle.putString("essayString", essayList.get(position).getEssay());
        bundle.putString("dateString", essayList.get(position).getDate());
        bundle.putString("timeString", essayList.get(position).getTime());
        swipeFragment.setArguments(bundle);
        return swipeFragment;
    }

    @Override
    public int getCount() {
        return essayList.size();
    }


}

This is the Main activity

package com.example.myapplication;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity{
    private ListView listView;
    private ArrayList<EssayElement> essayList = new ArrayList<>();
    private ArrayList<String> titleList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("essayList",essayList);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        getJSON("http://10.0.2.2:8081/getAll");
    }
    public void getJSON(final String urlWebService) {
        class GetJSON extends AsyncTask<Void, Void, String> {
            @Override
            protected void onPostExecute(String s) {
                try {
                    parseJSON(s);
                    loadIntoListView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                        try {
                            URL url = new URL(urlWebService);
                            HttpURLConnection con = (HttpURLConnection) url.openConnection();
                            con.setRequestMethod("GET");
                            StringBuilder sb = new StringBuilder();
                            InputStream input = con.getInputStream();
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
                            String json;
                            while ((json = bufferedReader.readLine()) != null) {
                                sb.append(json + "\n");
                            }
                            return sb.toString().trim();
                        } catch (Exception e) {
                            return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON(
        );
        getJSON.execute();
    }

    private void parseJSON(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<EssayElement>>(){}.getType();
        essayList = gson.fromJson(json, type);
        for (EssayElement essayElement : essayList){
        Log.i("Message: " + "", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
        }
    }


    private void loadIntoListView(String json) throws JSONException {
        Gson gson = new Gson();
        Type type = new TypeToken<List<EssayElement>>(){}.getType();
        essayList = gson.fromJson(json, type);
        for(EssayElement essayElement : essayList){
           titleList.add(essayElement.title);
        }

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , titleList);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                Intent newActivity = new Intent(MainActivity.this,Essay.class);
                newActivity.putExtra("TITLE", essayList.get(i).title);
                newActivity.putExtra("ESSAY", essayList.get(i).essay);
                newActivity.putExtra("DATE", essayList.get(i).date);
                newActivity.putExtra("TIME", essayList.get(i).time);
                newActivity.putExtra("ID", essayList.get(i).id);
                startActivity(newActivity);
            }
        });
    }


}
getIntent() or Bundle

works for passing data between Activities and fragments not with FragmentStatePagerAdapter. you can simply pass any data to an adapter in it's constructor.

您可以使用静态ArrayList,如果您更改了静态arraylist,则它将在片段适配器中自动更改。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM