Yas
Yas

Reputation: 97

Pass Arraylist from Fragment to RecyclerAdapter (Android)

My project is set up like this:

Inside MainActivity I have a viewpager to change between 4 fragments:

  1. Fragment, 2. Fragment, 3. Fragment and 4. Fragment.

I do following inside 2. Fragment:

enter image description here

What I need to do is to pass asList from inside 2. Fragment to the recyclerAdapter, so that I inside onBindViewHolder can set title in relation to the strings in the arraylist in 2. Fragment.

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

This is the EXCEPTION:

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

}

Upvotes: 0

Views: 754

Answers (2)

Doron Yakovlev Golani
Doron Yakovlev Golani

Reputation: 5470

You are using some static array to get the data and that seems wrong.

What you can do is to save your data in the adapter and change your onBindViewHolder() (the same goes for the other methods of the adapter that use the static data):

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

And in the fragment:

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

Upvotes: 1

Vishal Arora
Vishal Arora

Reputation: 2564

Add a method to accept new list inside Recycler Adapter

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

Also override getItemCount() as -

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

Upvotes: 1

Related Questions