活动完成后重新加载片段

时间:2016-06-01 09:35:43

标签: android

当listitem点击新活动时,我正在使用列表视图的片段在更改后我回到fragmen以及如何重新加载片段值后,当前列表位置值开始。

public class ManageCms extends Fragment implements SearchView.OnQueryTextListener{
                int events;
                CommonSharedPref commonSharedPref;
                ListView list;
                ManageCmsAdapter manageCmsAdapter;
                List<ManageCmsModel> manageCmsModelList = new ArrayList<ManageCmsModel>();
                ArrayList<ManageCmsModel> arraylist = new ArrayList<ManageCmsModel>();
                int start=0;
                int totcheckCount;
                SearchView searchView;
                ProgressDialog pDialog;
                RequestQueue requestQueue;
                String Url="";
                public ManageCms() {

                }
                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                         Bundle savedInstanceState) {

                    View view = inflater.inflate(R.layout.fragment_manage_cms, container,
                            false);
                    commonSharedPref =new CommonSharedPref(getActivity());
                    ((MainActivity) getActivity())
                            .setActionBarTitle("Manage CMS");
                    getCMS();
                    FabSpeedDial fabSpeedDial=(FabSpeedDial)view.findViewById(R.id.cms_fab_speed_dial);
                    list = (ListView) view.findViewById(R.id.list_manageCms);
                    searchView=(SearchView)view.findViewById(R.id.searchView);
                    requestQueue= Volley.newRequestQueue(getActivity());

                    // Pass results to ListViewAdapter Class
                    manageCmsAdapter = new ManageCmsAdapter(getActivity(), R.layout.fragment_manage_cms_list_item,
                            manageCmsModelList);

                    // Binds the Adapter to the ListView
                    list.setAdapter(manageCmsAdapter);
                    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                    list.setTextFilterEnabled(true);
                    setupSearchView();
                    list.setOnTouchListener(new ListView.OnTouchListener() {
                        private long startClickTime;
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            int action = event.getAction();
                            switch (action) {
                                case MotionEvent.ACTION_DOWN:
                                    // Disallow ScrollView to intercept touch events.
                                    v.getParent().requestDisallowInterceptTouchEvent(true);
                                    events=1;
                                    break;

                                case MotionEvent.ACTION_UP:
                                    // Allow ScrollView to intercept touch events.
                                    v.getParent().requestDisallowInterceptTouchEvent(false);
                                    events=0;
                                    break;
                                /*case MotionEvent.ACTION_MOVE:
                                        long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                                        if (clickDuration >= MIN_CLICK_DURATION) {
                                            //Toast.makeText(getActivity(), "LONG PRESSED!",Toast.LENGTH_SHORT).show();
                                            events=1;
                                        }*//*
                                    break;*/

                            }

                            // Handle ListView touch events.
                            v.onTouchEvent(event);
                            return true;
                        }
                    });
                    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            int pos = adapterView.getPositionForView(view);
                            String cmsId=manageCmsModelList.get(pos).getCmsId();
                            String cmsDescription=manageCmsModelList.get(pos).getCmsDescription();
                            String cmsUrl=manageCmsModelList.get(pos).getCmsUrl();
                            String cmsTitle=manageCmsModelList.get(pos).getCmsTitle();
                            commonSharedPref.clearAll();
                            commonSharedPref.editCMS(cmsTitle,cmsUrl, cmsDescription, cmsId);
                            Intent intent=new Intent(getActivity(),EditCms.class);
                            startActivity(intent);

                        }
                    });

                    list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
                        @Override
                        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

                            if(list!=null){
                                // Capture total checked items
                               int checkedCount = list.getCheckedItemCount();
                                // Set the CAB title according to total checked items
                                /*((MainActivity) getActivity()).getSupportActionBar().hide();*/
                                mode.setTitle(checkedCount + " Selected");
                                manageCmsAdapter.toggleSelection(position);
                            }

                        }

                        @Override
                        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                            actionMode.getMenuInflater().inflate(R.menu.menu_cms_management, menu);
                            return true;
                        }

                        @Override
                        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {

                            return false;
                        }


                        @Override
                        public void onDestroyActionMode(ActionMode actionMode) {
                            manageCmsAdapter.removeSelection();
                        }
                    });
                    list.setOnScrollListener(new AbsListView.OnScrollListener() {
                        @Override
                        public void onScrollStateChanged(AbsListView absListView, int totalItemCount) {

                        }

                        @Override
                        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                            int test=list.getAdapter().getCount();
                            // TODO Auto-generated method stub
                            if(test!=0 && !absListView.equals("")){
                                if (list.getLastVisiblePosition() == list.getAdapter().getCount() -1 &&
                                        list.getChildAt(list.getChildCount() - 1).getBottom() <= list.getHeight())
                                {
                                    SparseBooleanArray selected = manageCmsAdapter
                                            .getSelectedIds();
                                    if(selected.size() == 0 && test!=totcheckCount){
                                        getCMS();
                                    }

                                }
                            }
                        }
                    });
                    fabSpeedDial.setMenuListener(new SimpleMenuListenerAdapter() {
                        @Override
                        public boolean onMenuItemSelected(MenuItem menuItem) {
                            switch (menuItem.getItemId()) {
                                case R.id.action_UnBlockAll:
                                    toggleUnblockAll();
                                    return true;
                                case R.id.action_BlockAll:
                                    toggleBlockAll();
                                    return true;
                                case R.id.action_DeleteAll:
                                    toggleDeleteAll();
                                    return true;
                                case R.id.action_SelectAll:
                                    toggleSelectAll();
                                    return true;
                                case R.id.action_DeSelectAll:
                                    toggleDeSelectAll();
                                    return true;
                                default:
                                    return false;
                            }
                        }
                    });

                    return view;
                }

                private void setupSearchView() {
                    searchView.setIconifiedByDefault(false);
                    searchView.setOnQueryTextListener(this);
                    searchView.setSubmitButtonEnabled(true);
                    searchView.setQueryHint("Search Here");
                }

                private void toggleDeSelectAll() {
                    int checkcounts=manageCmsModelList.size();
                    manageCmsAdapter.removeSelection();
                    for(int i=0;i<checkcounts;i++){
                        list.setItemChecked(i, false);
                    }
                }

                private void toggleSelectAll() {

                    int checkcount=manageCmsModelList.size();
                    manageCmsAdapter.removeSelection();
                    for(int i=0;i<checkcount;i++){
                        list.setItemChecked(i, true);
                    }

                }

                private void toggleDeleteAll() {
                    SparseBooleanArray selected = manageCmsAdapter
                            .getSelectedIds();
                    if(selected.size()!=0){
                        Url=ApiConstants.MULTI_DELETE;
                        manageDelete();
                    }else{
                        Toast.makeText(getActivity(), R.string.select_atleat_one,Toast.LENGTH_SHORT).show();
                    }

                }


                private void toggleBlockAll() {
                    SparseBooleanArray selected = manageCmsAdapter
                            .getSelectedIds();
                    if(selected.size()!=0){
                        Url=ApiConstants.MULTI_BLOCK;
                        manageAll();
                    }else{
                        Toast.makeText(getActivity(), R.string.select_atleat_one,Toast.LENGTH_SHORT).show();
                    }

                }

                private void toggleUnblockAll() {
                    SparseBooleanArray selected = manageCmsAdapter
                            .getSelectedIds();
                    if(selected.size()!=0){
                    Url=ApiConstants.MULTI_UNBLOCK;
                    manageAll();
                    }else{
                        Toast.makeText(getActivity(), R.string.select_atleat_one,Toast.LENGTH_SHORT).show();
                    }
                }

                private void getCMS() {
                    pDialog = new ProgressDialog(getActivity());
                    pDialog.setMessage("Loading Cms...");
                    pDialog.setCancelable(false);
                    showpDialog();
                    StringRequest stringRequest = new StringRequest(Request.Method.GET, ApiConstants.MANAGE_CMS+"?startLimit="+start,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    JSONArray user = null;
                                    JSONObject jo = null;
                                    try {
                                        hidepDialog();
                                        JSONObject users = new JSONObject(response);
                                        String status = users.getString("message");
                                        totcheckCount=Integer.valueOf(users.getString("totalRecord"));
                                        if (status.equals("Success")) {
                                            user = users.getJSONArray(ProjectConstants.JSON_ARRAY);
                                            if (user.length() == 0) {
                                            } else {
                                                for (int i = 0; i < user.length(); i++) {
                                                    ManageCmsModel manageCmsModel=new ManageCmsModel();
                                                    jo = user.getJSONObject(i);
                                                    start++;
                                                    manageCmsModel.setCmsId(jo.getString("cmsId"));
                                                    manageCmsModel.setCmsDescription(jo.getString("cmsDescription"));
                                                    manageCmsModel.setCmsTitle(jo.getString("cmsTitle"));
                                                    manageCmsModel.setCmsUrl(jo.getString("cmsUrl"));
                                                    manageCmsModel.setCmsStatus(jo.getString("cmsStatus"));
                                                    manageCmsModel.setSno(String.valueOf(start));
                                                    manageCmsModelList.add(manageCmsModel);
                                                    arraylist.add(manageCmsModel);
                                                    //mAdapter.getSubscriberList().add(subscriber);
                                                }
                                                hidepDialog();
                                                manageCmsAdapter = new ManageCmsAdapter(getActivity(), R.layout.fragment_feed_back_list_item,
                                                        arraylist);
                                                list.setAdapter(manageCmsAdapter);
                                                /*list.setAdapter(manageCmsAdapter);
                                                manageCmsAdapter.notifyDataSetChanged();*/
                                            }

                                        } else if(status.equals("Error")){
                                            String msg=users.getString("data");
                                            Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
                                        }else if(status.equals("Warning")){
                                            String msg=users.getString("data");
                                            Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
                                        }else if(status.equals("Server error")){
                                            toggleDeSelectAll();
                                            String msg=users.getString("data");
                                            Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
                                        }
                                        hidepDialog();
                                    } catch (Exception e) {
                                        hidepDialog();
                                        e.printStackTrace();
                                    }
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    hidepDialog();

                                }
                            }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<String, String>();
                            String startLimit = String.valueOf(start);
                            params.put("startLimit", startLimit);
                            return params;
                        }
                    };

                    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
                    stringRequest.setShouldCache(false);
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
                            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    requestQueue.add(stringRequest);
                }
               }

        public class EditCms extends AppCompatActivity {
            EditText edt_cmsTitle,edt_cmsUrl,edt_cmsDesc;
            String cmsId,cmsTitle,cmsUrl,cmsDescription,organizerId;
            // Progress dialog
            Button btn_editCms;
            ProgressDialog pDialog;
            RequestQueue requestQueue;
            CommonSharedPref commonSharedPref;
            private ArrayList<HashMap<String,String>> userData;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.fragment_edit_cms);
                commonSharedPref =new CommonSharedPref(getApplicationContext());
                DataBaseHandler dataBaseHandler=new DataBaseHandler(getApplicationContext());
                userData=dataBaseHandler.getUserDetail();
                organizerId=userData.get(0).get(ProjectConstants.KEY_ORGID);

                getSupportActionBar().setTitle("Edit cms");
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);

                edt_cmsTitle=(EditText)findViewById(R.id.edt_cmsTitle);
                edt_cmsUrl=(EditText)findViewById(R.id.edt_cmsUrl);
                edt_cmsDesc=(EditText)findViewById(R.id.edt_cmsDesc);
                SharedPreferences prefs = this.getSharedPreferences("user",
                        Context.MODE_PRIVATE);
                edt_cmsTitle.setText(prefs.getString("cmsTitle", ""));
                edt_cmsUrl.setText(prefs.getString("cmsUrl",""));
                edt_cmsDesc.setText(prefs.getString("cmsDescription",""));
                cmsId=prefs.getString("cmsId","");
                btn_editCms=(Button)findViewById(R.id.btn_editCms);
                btn_editCms.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cmsTitle=edt_cmsTitle.getText().toString();
                        cmsUrl=edt_cmsUrl.getText().toString();
                        cmsDescription=edt_cmsDesc.getText().toString();
                        if(cmsTitle.equals("")){
                            Toast.makeText(getApplicationContext(), R.string.cms_title,Toast.LENGTH_SHORT).show();
                        }else if(cmsUrl.equals("")){
                            Toast.makeText(getApplicationContext(), R.string.cms_url,Toast.LENGTH_SHORT).show();
                        }else if(!Patterns.WEB_URL.matcher(cmsUrl).matches()){
                            Toast.makeText(getApplicationContext(), R.string.invalid_url,Toast.LENGTH_SHORT).show();
                        }else if(cmsDescription.equals("")){
                            Toast.makeText(getApplicationContext(), R.string.cms_desc,Toast.LENGTH_SHORT).show();
                        }else if(cmsDescription.length()<50){
                            Toast.makeText(getApplicationContext(), R.string.cms_min_char,Toast.LENGTH_SHORT).show();
                        }else{
                            editCMS();

            }

        } }

                    }
                });
            }

            public void editCMS() {
                pDialog = new ProgressDialog(this);
                pDialog.setMessage("Updationg Cms...");
                pDialog.setCancelable(false);
                showpDialog();
                StringRequest stringRequest = new StringRequest(Request.Method.POST, ApiConstants.EDIT_CMS+cmsId,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                JSONArray user = null;
                                JSONObject jo=null;
                                JSONArray error = null;
                                try{
                                    hidepDialog();
                                    JSONObject users = new JSONObject(response);
                                    String status = users.getString("message");
                                    if(status.equals("Success")){
                                        String msg=users.getString("data");
                                        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
                                    }else if(status.equals("Error")){
                                        String msg=users.getString("data");
                                        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
                                    }else if(status.equals("warning")){
                                        String msg=users.getString("data");
                                        Toast.makeText(
            }

        }getApplicationContext(),msg,Toast.LENGTH_LONG).show();
                                    }else if(status.equals("Server error")){
                                        String msg=users.getString("data");
                                        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
                                    }
                                }catch (Exception e){
                                    hidepDialog();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                hidepDialog();
                                String errorMessage=error.getClass().getSimpleName();
                                Toast.makeText(getApplicationContext(),errorMessage,Toast.LENGTH_LONG).show();
                            }
                        }){
                    @Override
                    protected Map<String,String> getParams(){
                        Map<String,String> params = new HashMap<String, String>();
                        params.put("cmsTitle",cmsTitle);
                        params.put("cmsUrl",cmsUrl);
                        params.put("cmsDescription",cmsDescription);
                        params.put("organizerId",organizerId);
                        return params;
                    }
                };

            }

            public void showpDialog() {
                if (!pDialog.isShowing())
                    pDialog.show();
            }

            public void hidepDialog() {
                if (pDialog.isShowing())
                    pDialog.dismiss();
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {

                    // Respond to the action bar's Up/Home button
                    case android.R.id.home:
                        commonSharedPref.clearAll();
                        commonSharedPref.editCMS(cmsTitle,cmsUrl, cmsDescription, cmsId);
                        finish();
                        return true;
                }
                return super.onOptionsItemSelected(item);
            }
            @Override
            public void onBackPressed() {

                super.onBackPressed();

            }

        }

当listitem点击新活动时,我正在使用列表视图的片段在更改后我回到fragmen以及如何重新加载片段值后,当前列表位置值开始。

1 个答案:

答案 0 :(得分:0)

覆盖片段中的onResume并通知您的适配器

@Override
    protected void onResume() {
        super.onResume();
        manageCmsAdapter.notifyDataSetChanged();
    }

当你进入另一个活动onPause片段将调用,当回来onResume()将调用。所以你可以通知listview中的数据更改到适配器