使用片段中的asynctask进行添加和删除后刷新recyclelerview

时间:2017-08-13 18:00:18

标签: android-fragments android-asynctask android-recyclerview notifydatasetchanged

我已经实现了一个具有recyclerview的片段。在片段' OnCreateView 中初始化recyclerview及其适配器后,我将如下所示更新recyclerview:

添加项目:首先,我调用自定义 AlertView ,通过使用AsyncTask发送请求以在服务器中保存 Store 对象。我在 OnPostExecute

中更新了适配器数据

删除项目:每个视图都有一个buttun删除其相关对象。 OnclickListener在调用asynctask的适配器中实现,以从服务器中删除Store对象。

我的问题:一切正常但是在添加和删除后,recyclerview不会刷新,除非退出片段并重新打开它。 提前谢谢。

我的片段:

RemoteRegistry

我的适配器:

    public class Main_ShopkeeperFragment extends Fragment{
    RecyclerView recListStores;
    StoresOfShopkeeperAdapter ta;
    LinearLayoutManager llm;
    List<Store> data = new ArrayList<>();
    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<String, String, String> {

        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 < 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<String, String, String> {
            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 + "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
                data1 = data1+ "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8");
                data1 = data1+ "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
                data1 = data1+ "&" + URLEncoder.encode("description", "UTF-8") + "=" + URLEncoder.encode(description, "UTF-8");
                data1 = data1+ "&" + URLEncoder.encode("type_id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(typeid), "UTF-8");
                data1 = data1+ "&" + URLEncoder.encode("state_id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(stateid), "UTF-8");
                data1 = data1+ "&" + 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();
                }
            }
        }
    }
}

0 个答案:

没有答案