I am populating a recycler view from a remote database.
The recyclerview is inside a fragment.
The first time the fragment is loaded, the recyclerview shows all items.
When the user clicks on an item, another fragment is loaded.
Then, if the user clicks on the back button, the recyclerview shows all items but now two times. After the last item all items are shown again.
I have included this two lines on the function that loads the data from the remote database:
marcas.clear();// public List<Marca> marcas;
adapter.notifyDataSetChanged();// private MarcaAdapter adapter;
But am I doing wrong?
EDIT
In OnCreate
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
marcas.clear();
adapter.notifyDataSetChanged();
}
});
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
marcas = new ArrayList<>();
gridLayout = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(gridLayout);
adapter = new MarcaAdapter(getActivity(), marcas);
recyclerView.setAdapter(adapter);
// marcas.clear();
getDirectoriosFromDB(0);//LLAMADA 1
To load the data:
private void getDirectoriosFromDB(int id) {
marcas.clear();
adapter.notifyDataSetChanged();
AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... addressesIds) {
// Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://...marcas_todas.php")
.build();
try {
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA:cargando datos en getdirectorios INICIO ARRAY" );
okhttp3.Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA:cargando datos en getdirectorios " +array);
Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
Marca marca = new Marca(object.getInt("id_car_make"),
object.getString("name")
);
marcas.add(marca);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
};
asyncTask.execute(id);
}