Мой проект настроен так:
Внутри MainActivity У меня есть виджет для переключения между 4 фрагментами:
- Фрагмент, 2. Фрагмент , 3. Фрагмент и 4. Фрагмент.
Я делаю следующее внутри 2. Фрагмент:
- Инициализация утилита просмотра и адаптера.
- Запускает asynctask для получения json
- Запускает onJobFinishListener для добавления данных из асинхронной задачи в массив списков
![enter image description here](https://i.stack.imgur.com/VXOBR.png)
Что мне нужно сделать, это передать asList изнутри 2. Fragment в recyclerAdapter, чтобы я внутри onBindViewHolder мог установить заголовок относительно строк в массиве в 2. 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();
}
Это ИСКЛЮЧЕНИЕ:
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);
}