将Arraylist从Fragment传递到RecyclerAdapter(Android)

时间:2018-10-29 13:48:42

标签: android android-fragments android-recyclerview

我的项目设置如下:

在MainActivity内部,我有一个viewpager可以在4个片段之间进行切换:

  1. 片段, 2。片段,3。片段和4.片段。

我在2.片段中进行以下操作:

  • 初始化recyclerview和适配器。
  • 运行asynctask来获取json
  • 运行onJobFinishListener将数据从asynctask添加到数组列表

enter image description here

我需要做的是将asList从2. Fragment内部传递给recyclerAdapter,以便我在onBindViewHolder内部可以相对于2. Fragment中的arraylist中的字符串设置标题。

片段2:

public class CardViewTabelFragment extends Fragment implements jsonAsynctask.DataTabelFragment {

private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;

RecyclerAdapter adapter2;

List<String> asList;

jsonAsynctask jsonasynctask;

public CardViewTabelFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate( R.layout.card_list, container, false );

    recyclerView = (RecyclerView) view.findViewById( R.id.recycler_view );

    adapter = new RecyclerAdapter( );

    recyclerView.setAdapter( adapter );

    final RecyclerView.LayoutManager layoutManager = new LinearLayoutManager( getActivity() );

    ((LinearLayoutManager) layoutManager).setOrientation( LinearLayoutManager.VERTICAL );

    recyclerView.setLayoutManager( layoutManager );

    return view;

}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint( isVisibleToUser );

    if (isVisibleToUser) {
        jsonasynctask = new jsonAsynctask( this );
        jsonasynctask.execute();
    }
}

@Override
public void onJobFinishListener(List<String> allId) {

    asList = new ArrayList<String>( jsonasynctask.uniqueStrings );

    asList.add( 0, "ALLE SENSORER" );
    asList.add( "NÆSTE SENSORER" );

    System.out.println( "MEGET VIGTIGT DU KIGGER HER: " + asList );

    adapter2.addList(asList);
    adapter2.notifyDataSetChanged();

 }
}

RecyclerAdapter:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {

List<String> data = new ArrayList<String>();

public RecyclerAdapter( List<String> linkedDevice ) {

    this.data = linkedDevice;

}

@Override
public void onBindViewHolder(RecyclerViewHolder recyclerViewHolder, int position) {

    recyclerViewHolder.mTitle.setText( data.get( position ) );
    recyclerViewHolder.mBeskrivelse.setText( OurData.beskrivelse[position] );
    //recyclerViewHolder.mTitle.setText( OurData.title[position] );
    recyclerViewHolder.cardView.setCardBackgroundColor( Color.parseColor( OurData.colors[position] ) );

}

@Override
public int getItemCount() {
    return this.data.size();
}

这是例外:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yusuf.cxweb, PID: 13337
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)

* JSON ASYNCTASK *

public class jsonAsynctask extends AsyncTask<Void, Void, Void> {

JSONObject deviceArray;
JSONArray json2;

String username = "xxx";
String password = "xxx";
String credentials = username + ":" + password;
String xxxURL = "https://" + credentials + "@xxx.com/fetch.php?";

String basicAuth, line, json_string, json, device;

String data = "";

List<String> asList;

LinkedHashSet<String> uniqueStrings = new LinkedHashSet<String>();

List<String> allDevice = new ArrayList<String>();

Gson gson;

HttpURLConnection connection;
BufferedReader bufferedReader;

URL url;

private DataTabelFragment dataTabelFragment;

public jsonAsynctask(jsonAsynctask.DataTabelFragment dataTabelFragment) {

    this.dataTabelFragment = dataTabelFragment;

}

public void inBackground() {

    try {

        url = new URL( xxxURL );

        connection = (HttpsURLConnection) url.openConnection();

        basicAuth = "Basic " + new String( encodeBase64URLSafeString( credentials.getBytes() ) );

        connection.setRequestProperty( "Authorization", basicAuth );
        connection.setRequestMethod( "GET" );
        connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
        connection.setRequestProperty( "Content-Language", "en-US" );
        connection.setUseCaches( true );
        connection.setDoInput( true );
        connection.setDoOutput( true );
        connection.connect();

        InputStream stream = connection.getInputStream();

        bufferedReader = new BufferedReader( new InputStreamReader( stream ) );

        line = "";

        while (line != null) {
            line = bufferedReader.readLine();
            data = data + line;
        }

        json2 = new JSONArray( data );

        for (int i = 0; i < json2.length(); i++) {

            deviceArray = json2.getJSONObject( i );

            device = deviceArray.getString( "device" );

            uniqueStrings.add( device );

            allDevice.add( device );

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private static String encodeBase64URLSafeString(byte[] binaryData) {

    return android.util.Base64.encodeToString( binaryData, android.util.Base64.URL_SAFE );

}

@Override
protected Void doInBackground(Void... voids) {

    inBackground();

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute( aVoid );

    dataTabelFragment.onJobFinishListener( allDevice );

    gson = new Gson();

    json = gson.toJson( data );

    json_string = data;

}

public interface DataTabelFragment {

    void onJobFinishListener(List<String> allId);

}

2 个答案:

答案 0 :(得分:1)

您正在使用一些静态数组来获取数据,这似乎是错误的。

您可以做的是将数据保存在适配器中并更改onBindViewHolder()(使用静态数据的适配器的其他方法也是如此)

List<String> data = new ArrayList<String>;

@Override
public void onBindViewHolder(RecyclerViewHolder recyclerViewHolder, int position) {
    recyclerViewHolder.mBeskrivelse.setText(data[position]);
}

@Override
public int getItemCount() {
    return data.size();
}

在片段中:

RecyclerAdapter adapter;

@Override
public void onJobFinishListener(List<String> allId) {

    asList = new ArrayList<String>( jsonasynctask.uniqueStrings );
    asList.add( 0, "ALLE SENSORER" );
    asList.add( "NÆSTE SENSORER" );

    System.out.println( "MEGET VIGTIGT DU KIGGER HER: " + asList );
    adapter.setData(asList);
    adapter.notifyDataSetChanged();
} 

答案 1 :(得分:1)

添加一种在Recycler Adapter内接受新列表的方法

public void addList(List<String> linkedDevice){ this.linkedDevice = linkedDevice; notifyDataSetChanged(); }

也将getItemCount()替换为-

@Override public int getItemCount() { return this.linkedDevice.size(); }