title: refresh the recyclerview after add and delete using asynctask in fragment
body: <p>I have implemented a fragment that have a recyclerview. After initialize the recyclerview and its adapter in fragments' <strong>OnCreateView</strong>, I update the recyclerview as below scenarios:</p>
  
  <p><strong>Adding item:</strong> First I call a custom <strong>AlertView</strong> that send a request to save an <strong>Store</strong> object in the server by using AsyncTask. I update the Adapter data in <strong>OnPostExecute</strong> </p>
  
  <p><strong>remove items:</strong> each view have a buttun to delete its relevant object. the OnclickListener is implemented in the adapter that call an asynctask to remove a Store object from the server.</p>
  
  <p><strong>My Problems:</strong> everything is ok BUT the recyclerview dont refresh after add and remove unless exit the fragment and reopen it again.
  Thank you in advance.</p>
  
  <p><strong>my fragment:</strong></p>
  
  <pre><code>    public class Main_ShopkeeperFragment extends Fragment{
      RecyclerView recListStores;
      StoresOfShopkeeperAdapter ta;
      LinearLayoutManager llm;
      List&lt;Store&gt; data = new ArrayList&lt;&gt;();
      private TextView tv_name,tv_nationalid,tv_address, tv_phone,tv_description;
      Button btn_exit,btn_edit,btn_expand_desc,btn_expand_store, 
      btn_add_store,btn_delete;
      private Prefs prefs;
      private MaterialSpinner sp_type,sp_state,sp_city;
  
      int typeid,stateid,cityid;
      String typeName,stateName,cityName, name,phone, address,description;
  
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
      }
  
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) {
          View rootView = inflater.inflate(R.layout.fragment_main__shopkeeper, container, false);
  
          tv_name = (TextView) rootView.findViewById(R.id.shopkeeper_name_spectext);
          tv_nationalid = (TextView) rootView.findViewById(R.id.shopkeeper_nationalid_spectext);
          tv_address = (TextView) rootView.findViewById(R.id.shopkeeper_address_spectext);
          tv_phone = (TextView) rootView.findViewById(R.id.shopkeeper_phone_spectext);
          tv_description = (TextView) rootView.findViewById(R.id.shopkeeper_description_spectext);
          btn_exit = (Button) rootView.findViewById(R.id.exit_spec);
          btn_expand_desc = (Button) rootView.findViewById(R.id.expand);
          btn_expand_store = (Button) rootView.findViewById(R.id.expand_store);
          btn_add_store = (Button) rootView.findViewById(R.id.add_store);
  
  
          recListStores = (RecyclerView) rootView.findViewById(R.id.shopkeeper_stores) ;
          //recListStores.setHasFixedSize(true);
          llm = new LinearLayoutManager(getContext());
          llm.setOrientation(LinearLayoutManager.VERTICAL);
          recListStores.setLayoutManager(llm);
          recListStores.setItemAnimator(new DefaultItemAnimator());
          ta = new StoresOfShopkeeperAdapter(getContext(), data);
          //ta.setHasStableIds(true);
          recListStores.setAdapter(ta);
          Check_Connection_Retrive();
  
          InitializeTextViews();
  
          btn_add_store.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  AddStore_AlertView();
              }
          });
  
  
          return rootView;
      }
  
  
      private void AddStore_AlertView() {
          final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          LayoutInflater inf = getActivity().getLayoutInflater();
          final View inflator = inf.inflate(R.layout.add_store_layout, null);
          final EditText et_name = (EditText) inflator.findViewById(R.id.store_name);
          final EditText et_phone = (EditText) inflator.findViewById(R.id.store_phone);
          final EditText et_address = (EditText) inflator.findViewById(R.id.store_address);
          final EditText et_description = (EditText) inflator.findViewById(R.id.store_description);
          sp_type = (MaterialSpinner) inflator.findViewById(R.id.store_type_Spinner);
          sp_state = (MaterialSpinner) inflator.findViewById(R.id.store_state_Spinner);
          sp_city = (MaterialSpinner) inflator.findViewById(R.id.store_city_Spinner);
          new FetchStates().execute();
          new FetchTypes().execute();
          dialog.setView(inflator)
                  .setNegativeButton("انصراف", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialoginterface, int i) {
                          dialoginterface.cancel();
                      }})
                  .setPositiveButton("ثبت", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialoginterface, int i) {
  
                      }
                  });
          final AlertDialog dial = dialog.create();
          dial.show();
          dial.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
          {
              @Override
              public void onClick(View v)
              {
                  Boolean wantToCloseDialog = false;
  
                  name = et_name.getText().toString();
                  phone = et_phone.getText().toString();
                  address = et_address.getText().toString();
                  description = et_description.getText().toString();
  
                  //Do stuff, possibly set wantToCloseDialog to true then...
                  if(wantToCloseDialog)
                      dial.dismiss();
                  View focusView = null;
                  Boolean cancel = false;
  
                  if (TextUtils.isEmpty(name)) {
                      et_name.setFocusable(true);
                      et_name.setError("نام و نام خانوادگی را وارد کنید");
                      et_name.requestFocus();
                      cancel = true;
                  }
                  if (TextUtils.isEmpty(address)) {
                      et_address.setError("آدرس را وارد کنید");
                      focusView = et_address;
                      cancel = true;
                  }
                  if (TextUtils.isEmpty(phone)) {
                      et_phone.setError("شماره تماس را وارد کنید");
                      focusView = et_phone;
                      cancel = true;
                  }
                  if (TextUtils.isEmpty(description)) {
                      et_description.setError("توضیحات را وارد کنید");
                      focusView = et_description;
                      cancel = true;
                  }
                  if (TextUtils.isEmpty(sp_state.getText().toString())) {
                      sp_state.setError("استان را انتخاب کنید");
                      focusView = sp_state;
                      cancel = true;
                  }
                  if (TextUtils.isEmpty(sp_city.getText().toString())) {
                      sp_city.setError("شهر را انتخاب کنید");
                      focusView = sp_city;
                      cancel = true;
                  }
                  if (TextUtils.isEmpty(sp_type.getText().toString())) {
                      sp_type.setError("نوع فروشگاه را انتخاب کنید");
                      focusView = sp_type;
                      cancel = true;
                  }
                  if(cancel)
                      focusView.requestFocus();
                  else {
                      new RegStoreRequest().execute();
                      dial.dismiss();
                  }
  
              }
          });
      public void Check_Connection_Retrive()
          {
              new FetchStores().execute();
          }
      public class FetchStores extends AsyncTask&lt;String, String, String&gt; {
  
          ProgressDialog pdLoading = new ProgressDialog(getContext());
          HttpURLConnection conn;
          URL url = null;
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
  
              pdLoading.setMessage("در حال بارگیری");
              pdLoading.setCancelable(false);
              //pdLoading.setProgress(10);
              pdLoading.show();
          }
  
          @Override
          protected String doInBackground(String... params) {
  
              try {
                  url = new URL("http://www/api/"+prefs.getShopkeeper().nationalid+"/storeshopkeeper");
  
              } catch (MalformedURLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  return "1";
              }
              try {
  
                  // Setup HttpURLConnection class to send and receive data from php and mysql
                  conn = (HttpURLConnection) url.openConnection();
                  conn.setReadTimeout(1000);
                  conn.setConnectTimeout(1000);
                  conn.setRequestMethod("GET");
  
              } catch (IOException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
                  return "2";
              }
  
              try {
  
                  int response_code = conn.getResponseCode();
  
                  // Check if successful connection made
                  if (response_code == HttpURLConnection.HTTP_OK) {
  
                      // Read data sent from server
                      InputStream input = conn.getInputStream();
                      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                      StringBuilder result = new StringBuilder();
                      String line;
  
                      while ((line = reader.readLine()) != null) {
                          result.append(line);
                      }
  
                      // Pass data to onPostExecute method
                      return (result.toString());
  
                  } else {
                      return "3";
                  }
  
              } catch (IOException e) {
                  e.printStackTrace();
                  return "4";
              } finally {
                  conn.disconnect();
              }
  
  
          }
  
          @Override
          protected void onPostExecute(String result) {
  
              pdLoading.dismiss();
              //this method will be running on UI thread
              switch(result) {
                  case "1":
                      //alertView1("خطا در انجام عملیات (1)",false);
                      Toast.makeText(getContext(), "خطا در انجام عملیات (1)", Toast.LENGTH_SHORT).show();
                      break;
                  case "2":
                      //alertView1("خطا در انجام عملیات (2)",false);
                      Toast.makeText(getContext(), "خطا در انجام عملیات (2)", Toast.LENGTH_SHORT).show();
                      break;
                  case "3":
                      //alertView1( "خطا در انجام عملیات (3)",false);
                      Toast.makeText(getContext(), "خطا در انجام عملیات (3)", Toast.LENGTH_SHORT).show();
                      break;
                  case "4":
                      //alertView1("شبکه اینترنت ضعیف است، لطفا دوباره تلاش کنید.",false);
                      Toast.makeText(getContext(), "شبکه اینترنت ضعیف است، لطفا دوباره تلاش کنید.", Toast.LENGTH_SHORT).show();
                      break;
                  default:
                      try {
                          recListStores.removeAllViews();
                          data.clear();
                          JSONArray jArray = new JSONArray(result);
                          // Extract data from json and store into ArrayList as class objects
                          for (int i = 0; i &lt; jArray.length(); i++) {
                              JSONObject json_data = jArray.getJSONObject(i);
                              Store store = new Store();
                              store.id = json_data.getInt("id");
                              store.name = json_data.getString("name");
                              store.address = json_data.getString("address");
                              store.phone = json_data.getString("phone");
                              store.description = json_data.getString("description");
                              store.Shopkeeper_id = json_data.getInt("shopkeeper_id");
                              store.type_id = json_data.getInt("type_id");
                              store.state_id = json_data.getInt("state_id");
                              store.city_id = json_data.getInt("city_id");
                              store.image1 = json_data.getString("image1");
                              store.like = json_data.getInt("like");
                              data.add(store);
                          }
  
                          ta.notifyDataSetChanged();
                      } catch (JSONException e) {
                          Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
                      }
              }
          }
      }
      public class RegStoreRequest extends AsyncTask&lt;String, String, String&gt; {
              HttpURLConnection conn;
              URL url = null;
              String data1 = "";
              ProgressDialog pdLoading;
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              pdLoading = new ProgressDialog(getContext());
              pdLoading.setCancelable(false);
              pdLoading.show();
              pdLoading.setTitle("در حال ارسال اطلاعات");
          }
  
          @Override
          protected String doInBackground(String... params) {
  
              try {
                  url = new URL("http://test.tiarafood.ir/api/registerstore");
                  data1 = URLEncoder.encode("nationalid", "UTF-8") + "=" + URLEncoder.encode(prefs.getShopkeeper().nationalid, "UTF-8");
                  data1 = data1 + "&amp;" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
                  data1 = data1+ "&amp;" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8");
                  data1 = data1+ "&amp;" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
                  data1 = data1+ "&amp;" + URLEncoder.encode("description", "UTF-8") + "=" + URLEncoder.encode(description, "UTF-8");
                  data1 = data1+ "&amp;" + URLEncoder.encode("type_id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(typeid), "UTF-8");
                  data1 = data1+ "&amp;" + URLEncoder.encode("state_id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(stateid), "UTF-8");
                  data1 = data1+ "&amp;" + URLEncoder.encode("city_id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(cityid), "UTF-8");
  
                  conn = (HttpURLConnection) url.openConnection();
                  conn.setReadTimeout(1000);
                  conn.setConnectTimeout(1000);
                  conn.setDoOutput(true);
                  conn.setRequestMethod("POST");
  
              } catch (Exception e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
                  return "ERROR";
              }
  
              try {
                  OutputStreamWriter ow = new OutputStreamWriter(conn.getOutputStream());
                  ow.write(data1);
                  ow.flush();
  
                  if(conn.getResponseCode()== HttpURLConnection.HTTP_OK){
                      InputStream input = conn.getInputStream();
                      BufferedReader reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));
                      StringBuilder result = new StringBuilder();
                      String line= null;
  
                      while ((line = reader.readLine()) != null) {
                          if(line=="false")
                              return "ERROR";
                          result.append(line);
                      }
  
                      // Pass data to onPostExecute method
                      reader.close();
                      return (result.toString());
                      //return String.valueOf(conn.getResponseCode());
                  }
                  else
                      return "ERROR";
  
              } catch (Exception e) {
                  e.printStackTrace();
                  return "ERROR";
              } finally {
                  conn.disconnect();
              }
          }
  
          @Override
          protected void onPostExecute(String result) {
  
              pdLoading.dismiss();
              if (result == "ERROR") {
                  Toast.makeText(getContext(), "خطا در ارسال اطلاعات",Toast.LENGTH_SHORT).show();
              } else if (result.equalsIgnoreCase("repeate")) {
                  Toast.makeText(getContext(),"نام فروشگاه تکراری است.",Toast.LENGTH_SHORT).show();
              } else {
                  try {
                      JSONArray jArray = new JSONArray(result);
                      JSONObject json_data = jArray.getJSONObject(0);
                      Store store = new Store();
                      store.id = json_data.getInt("id");
                      store.name = json_data.getString("name");
                      store.address = json_data.getString("address");
                      store.phone = json_data.getString("phone");
                      store.description = json_data.getString("description");
                      store.Shopkeeper_id = json_data.getInt("shopkeeper_id");
                      store.type_id = json_data.getInt("type_id");
                      store.state_id = json_data.getInt("state_id");
                      store.city_id = json_data.getInt("city_id");
                      store.image1 = json_data.getString("image1");
                      store.like = json_data.getInt("like");
                      data.add(store);
                      ta.notifyDataSetChanged();
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p><strong>my adapter:</strong></p>
  
  <pre><code>    public class StoresOfShopkeeperAdapter extends RecyclerView.Adapter&lt;StoresOfShopkeeperAdapter.MenuTypesViewHolder&gt; {
      protected int lastPosition = -1;
      private List&lt;Store&gt; menuTypesList;
      private Context context;
  
      public StoresOfShopkeeperAdapter(Context Context, List&lt;Store&gt; contactList) {
          this.menuTypesList = contactList;
          this.context = Context;
      }
  
  
      @Override
      public int getItemCount() {
          return menuTypesList.size();
      }
  
      @Override
      public void onBindViewHolder(final MenuTypesViewHolder menuTypesViewHolder, final int i) {
          final Store mt = menuTypesList.get(i);
          final int lcount = mt.like;
          menuTypesViewHolder.vName.setText(mt.name);
          Glide.with(context).load("http://test.tiarafood.ir/img/" + mt.image1)
                  .bitmapTransform(new RoundedCornersTransformation(context, 0, 0, RoundedCornersTransformation.CornerType.TOP))
                  .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                  .placeholder(R.drawable.ic_logo)
                  .override(500, 500).into(menuTypesViewHolder.vImage);
          if (mt.like &gt; 0)
              menuTypesViewHolder.likeButton.setLiked(true);
          else
              menuTypesViewHolder.likeButton.setLiked(false);
          menuTypesViewHolder.likeCount.setText(String.valueOf(mt.like));
          menuTypesViewHolder.btn_delete.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  new DeleteStoreTask().execute(String.valueOf(mt.id), String.valueOf(i));
              }
          });
          setFadeAnimation(menuTypesViewHolder, i);
          // menuTypesViewHolder.vImage.setImageBitmap(BitmapFactory.decodeByteArray(mt.image, 0, mt.image.length));
      }
  
      @Override
      public int getItemViewType(int position) {
          return super.getItemViewType(position);
      }
  
      @Override
      public MenuTypesViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
          final View itemView = LayoutInflater.
                  from(viewGroup.getContext()).
                  inflate(R.layout.stores_of_shopkeeper_recyclerview_fragment, viewGroup, false);
          final MenuTypesViewHolder holder = new MenuTypesViewHolder(itemView);
          return new MenuTypesViewHolder(itemView);
      }
  
      @Override
      public long getItemId(int position) {
          return position;
      }
  
  
      @Override
      public void onViewDetachedFromWindow(MenuTypesViewHolder holder) {
          ((MenuTypesViewHolder) holder).itemView.clearAnimation();
      }
  
  
      public class MenuTypesViewHolder extends RecyclerView.ViewHolder {
  
          protected TextView vName, likeCount;
          protected ImageView vImage;
          private Context context;
          protected LikeButton likeButton;
          protected Button btn_delete;
  
          public MenuTypesViewHolder(View v) {
              super(v);
              vName = (TextView) v.findViewById(R.id.myImageViewText);
              vImage = (ImageView) v.findViewById(R.id.myImageView);
              likeButton = (LikeButton) v.findViewById(R.id.like_button);
              likeCount = (TextView) v.findViewById(R.id.like_count);
              btn_delete = (Button) v.findViewById(R.id.btn_delete_store);
          }
      }
  
  
      private void setFadeAnimation(MenuTypesViewHolder view, int position) {
          if (position &gt; lastPosition) {
  
              AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
              anim.setDuration(1000);
              view.itemView.startAnimation(anim);
              lastPosition = position;
          }
      }
  
      public class DeleteStoreTask extends AsyncTask&lt;String, String, String&gt; {
  
          HttpURLConnection conn;
          URL url = null;
          String storeId, i;
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
  
          }
  
          @Override
          protected String doInBackground(String... params) {
  
              storeId = params[0];
              i = params[1];
  
              try {
                  url = new URL("http://www/api/" + storeId + "/deletestore");
  
              } catch (MalformedURLException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                  return "false";
              }
              try {
  
                  // Setup HttpURLConnection class to send and receive data from php and mysql
                  conn = (HttpURLConnection) url.openConnection();
                  conn.setReadTimeout(1000);
                  conn.setConnectTimeout(1000);
                  conn.setRequestMethod("POST");
  
              } catch (IOException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
                  return "false";
              }
  
              try {
  
                  int response_code = conn.getResponseCode();
  
                  // Check if successful connection made
                  if (response_code == HttpURLConnection.HTTP_OK) {
  
                      // Read data sent from server
                      InputStream input = conn.getInputStream();
                      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                      StringBuilder result = new StringBuilder();
                      String line;
  
                      while ((line = reader.readLine()) != null) {
                          result.append(line);
                      }
  
                      // Pass data to onPostExecute method
                      return (result.toString());
  
                  } else {
                      return "false";
                  }
  
              } catch (IOException e) {
                  e.printStackTrace();
                  return "false";
              } finally {
                  conn.disconnect();
              }
          }
  
          @Override
          protected void onPostExecute(String result) {
              if (result != "false") {
                  if (menuTypesList.size() == 1) {
                      menuTypesList.clear();
                      notifyItemRemoved(Integer.valueOf(i));
  
                  } else {
                      //Main_ShopkeeperFragment.data.remove(Integer.valueOf(i));
                      menuTypesList.remove(Integer.valueOf(i));
                      //Main_ShopkeeperFragment.ta.notifyDataSetChanged();
                      notifyItemRemoved(Integer.valueOf(i));
                      //notifyItemRangeChanged(0,getItemCount());
                  }
              }
          }
      }
  }
  </code></pre>