0

I have one activity page in which i have two fragments. In 1st fragment there is a listview with having Main category list with pulltorefresh feature.

When I click on a list item it will show the sub category of its on 2nd fragment.Thats all how it should work.

But my problem is when the activity loads the 1st fragment shows and also the message no internet connection shows in a Toast, but when i clicked on its list item nothing happend with the 2nd fragment

The codes are here

This one is the activity page which is having two fragment

public class ServiceActivity extends Activity {

CategoryDetails mainCategory;
SimpleSideDrawer slide_me;
public ImageButton imgBack;
static View fragmentsub;
static View fragmentmain;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_service);

    fragmentmain = findViewById(R.id.fragmentmain);
    fragmentsub = findViewById(R.id.fragmentsub);
    imgBack = (ImageButton)findViewById(R.id.imgBackBtn);
    imgBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_service, menu);
    return true;
}

1st Fragment

public class FreagmentMainCategory extends Fragment{

    private LinearLayout llLayoutmain;
    private FragmentActivity faActivitymain;
    private ListView lstCategoryList;
    private SelectCategoryTask mAuthTask = null;
    private View mServiceStatusView;
    CategoryDetails mainCategory;
    private categoryListAdapter adapterList;    
    static final int MENU_MANUAL_REFRESH = 0;
    static final int MENU_DISABLE_SCROLL = 1;
    static final int MENU_SET_MODE = 2;
    static final int MENU_DEMO = 3;
    private View lstListView;
    private PullToRefreshListView mPullRefreshListView;

    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        //faActivitymain  = (FragmentActivity)  super.getActivity();
         View view = inflater.inflate(R.layout.activity_fragment_main,container, false);

        this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        FontUtils.setCustomFont(getActivity().findViewById(R.id.mainView), getActivity().getAssets());

        lstListView= view.findViewById(R.id.lstCategoryView);
        mPullRefreshListView = (PullToRefreshListView)view.findViewById(R.id.lstCategory);
        // Set a listener to be invoked when the list should be refreshed.
        mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });
        mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {                   
            }
        }); 
        lstListView=(View)view.findViewById(R.id.lstCategoryView);

        lstCategoryList = ((PullToRefreshListView)view.findViewById(R.id.lstCategory)).getRefreshableView();            
        //lstCategoryList = (ListView) inflater.inflate(R.layout.activity_fragment_main, container, false);
        lstCategoryList = mPullRefreshListView.getRefreshableView();            
        registerForContextMenu(lstCategoryList);                        
        mServiceStatusView = view.findViewById(R.id.service_status);
        showProgress(true); 
        mAuthTask = new SelectCategoryTask();
        mAuthTask.execute((Void) null);
        lstCategoryList.setOnItemClickListener(new OnItemClickListener(){
                public void onItemClick(AdapterView<?> parent, View v, int position,long arg3) {    
                    Fragment fragment = new Fragment();
                    Bundle bundle = new Bundle();                                   
                    bundle.putString("MainCategoryName", mainCategory.masterinfo.get(position-1).maincatname);
                    fragment.setArguments(bundle);
            }
        });
        return view;
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getActivity().getMenuInflater().inflate(R.menu.activity_service, menu);
        return true;
    }       
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(
                    android.R.integer.config_shortAnimTime);
            mServiceStatusView.setVisibility(View.VISIBLE);
            mServiceStatusView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mServiceStatusView.setVisibility(show ? View.VISIBLE
                                    : View.GONE);
                        }
                    });
            lstListView.setVisibility(View.VISIBLE);
            lstListView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            lstCategoryList.setVisibility(show ? View.GONE
                                    : View.VISIBLE);
                        }
                    });         

        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mServiceStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            lstListView.setVisibility(show ? View.GONE : View.VISIBLE);                         
        }
    }       
    public class GetDataTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            // Simulates a background job.
            ServerAccess sa=new ServerAccess();
            mainCategory=sa.GetMainCategory();
            return true;
        }
        @Override
        protected void onPostExecute(Boolean result) {
            if(mainCategory==null){
                Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_check_network), Toast.LENGTH_LONG).show();
                lstCategoryList.setAdapter(null);
            }else if(mainCategory.code.equals("MOB01")){
                adapterList=new categoryListAdapter(getActivity().getApplicationContext(), mainCategory.masterinfo);
                lstCategoryList.setAdapter(null);
            }else if(mainCategory.code.equals("MOB02")){                    
                lstCategoryList.setAdapter(null);
            }else{
                Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_genric_error), Toast.LENGTH_LONG).show();
                lstCategoryList.setAdapter(null);
            }
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshListView.onRefreshComplete();

            super.onPostExecute(result);
        }
    }

    public class SelectCategoryTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {          
            ServerAccess sa=new ServerAccess();
            mainCategory=sa.GetMainCategory();          
            return true;
        }
        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if(mainCategory==null){
                Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_check_network), Toast.LENGTH_LONG).show();
                lstCategoryList.setAdapter(null);
            }else if(mainCategory.code.equals("MOB01")){
                adapterList=new categoryListAdapter(getActivity().getApplicationContext(), mainCategory.masterinfo);
                lstCategoryList.setAdapter(adapterList);
            }else if(mainCategory.code.equals("MOB02")){
                lstCategoryList.setAdapter(null);
            }else{
                Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_genric_error), Toast.LENGTH_LONG).show();
                lstCategoryList.setAdapter(null);
            }           
        }
        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
    class categoryListAdapter extends BaseAdapter {        
        List<Category> mainItems;
        Context myContext;
        public categoryListAdapter(Context context, List<Category> items) {
            myContext = context;
            mainItems = items;            
        }
        public int getCount() {           
            return mainItems.size();
        }
        public Object getItem(int index) {           
            return mainItems.get(index);
        }
        public long getItemId(int position) { 
            return position;
        }        
        @Override
        public View getView(int position, View convertView, ViewGroup parent    ) {
            // TODO Auto-generated method stub
            RelativeLayout layout = new RelativeLayout(myContext);          
            TextView tv = new TextView(myContext);
            tv.setText(mainItems.get(position).maincatname);
            tv.setGravity(Gravity.LEFT);
            tv.setTextSize(16);
            tv.setPadding(20, 20, 0, 20);
   tv.setTextColor(myContext.getResources().getColor(R.color.BlackColor));
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams
            (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            layout.addView(tv,lp);           
            return layout;
        }
    }

}

2nd fragment

public class FragmentSubCategory extends Fragment{
private View mSubCategoryStatusView;
private subCategoryListAdapter subAdapterList;
private SelectSubCategoryTask mSubAuthTask = null;
private ExpandableListView lstSubCategoryList;
String MainCategoryId="-1",MainCategoryName;
SubCategoryDetails mainSubCategory;
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    FontUtils.setCustomFont(getActivity().findViewById(R.id.subfragment), getActivity().getAssets());

    View view = inflater.inflate(R.layout.activity_fragment_sub,container, false);

    lstSubCategoryList = (ExpandableListView)view.findViewById(R.id.lstSubCategory);
    mSubCategoryStatusView = view.findViewById(R.id.sub_category_status);
    Bundle bundle = getArguments();
    try{        
        MainCategoryName = bundle.getString("MainCategoryName");
    }catch(Exception ex){
        MainCategoryName="";
    }   
    try{        
        MainCategoryId = bundle.getString("MainCategoryId");
    }catch(Exception ex){
        MainCategoryId="-1";
    }

    lstSubCategoryList.setOnChildClickListener(new OnChildClickListener() {  
        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
                Intent vendorListIntent=new Intent(getActivity().getApplication(),VendorListByCategoryActivity.class);
                vendorListIntent.putExtra("typeid", mainSubCategory.masterinfo.get(groupPosition).type.get(childPosition).typeid);
                vendorListIntent.putExtra("subCategoryId", mainSubCategory.masterinfo.get(groupPosition).subcatid);
                vendorListIntent.putExtra("mainCategoryId", MainCategoryId);
                startActivity(vendorListIntent);

            return false;
        }
    });
    showSubCategoryProgress(true);
    mSubAuthTask = new SelectSubCategoryTask();
    mSubAuthTask.execute((Void) null);
    return view;
}
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getActivity().getMenuInflater().inflate(R.menu.activity_sub_category, menu);
    return true;
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showSubCategoryProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(
                android.R.integer.config_shortAnimTime);

        mSubCategoryStatusView.setVisibility(View.VISIBLE);
        mSubCategoryStatusView.animate().setDuration(shortAnimTime)
                .alpha(show ? 1 : 0)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mSubCategoryStatusView.setVisibility(show ? View.VISIBLE
                                : View.GONE);
                    }
                });
        lstSubCategoryList.setVisibility(View.VISIBLE);
        lstSubCategoryList.animate().setDuration(shortAnimTime)
                .alpha(show ? 0 : 1)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        lstSubCategoryList.setVisibility(show ? View.GONE
                                : View.VISIBLE);
                    }
                });         
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mSubCategoryStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
        lstSubCategoryList.setVisibility(show ? View.GONE : View.VISIBLE);          
    }
}   
public class SelectSubCategoryTask extends AsyncTask<Void, Void, Boolean> {     
    @Override
    protected Boolean doInBackground(Void... params) {
        ServerAccess sa=new ServerAccess();
        mainSubCategory=sa.GetTypesMasters(Integer.parseInt(MainCategoryId));           
        return true;
    }
    @Override
    protected void onPostExecute(final Boolean success) {
        mSubAuthTask = null;            
        if(mainSubCategory==null){
            showSubCategoryProgress(false);
            Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_check_network), Toast.LENGTH_LONG).show();                
            //Message no category found.    
        }else if(mainSubCategory.code.equals("MOB02")){
            showSubCategoryProgress(false);
            Toast.makeText(getActivity().getApplicationContext(), mainSubCategory.msg, Toast.LENGTH_LONG).show();
        }else if(mainSubCategory.code.equals("MOB01")){
            showSubCategoryProgress(false);
            subAdapterList=new subCategoryListAdapter(getActivity().getApplicationContext(), mainSubCategory.masterinfo);
            lstSubCategoryList.setAdapter(subAdapterList);
            //set adapter
        }else{
            showSubCategoryProgress(false);
            Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.error_genric_error), Toast.LENGTH_LONG).show();
            //No Category message
        }
    }
    @Override
    protected void onCancelled() {
        mSubAuthTask = null;
        showSubCategoryProgress(false);
    }
}
public class subCategoryListAdapter extends BaseExpandableListAdapter {      
    private Context myContext;
    private List<SubCategory> _listDataHeader; // header titles
    // child data in format of header title, child title             
    public subCategoryListAdapter(Context context, List<SubCategory> listDataHeader) {
        this.myContext = context;
        this._listDataHeader = listDataHeader;          
    }    
    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataHeader.get(groupPosition).type.get(childPosititon).typename;
    }    
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }    
    @Override
    public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {   
        final String childText = (String) getChild(groupPosition, childPosition);               
        RelativeLayout layout = new RelativeLayout(myContext);  
        TextView txtListChild = new TextView(myContext);
        txtListChild.setText(childText);
        txtListChild.setGravity(Gravity.LEFT);
        txtListChild.setTextSize(16);           
        txtListChild.setPadding(60, 20, 0, 20);
        txtListChild.setTextColor(myContext.getResources().getColor(R.color.BlackColor));
        layout.addView(txtListChild);                 
        return layout;
    }    
    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataHeader.get(groupPosition).type.size();
    }    
    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition).subcatname;
    }    
    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }    
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }    
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);  
        int noOfType= getChildrenCount(groupPosition);
        RelativeLayout layout = new RelativeLayout(myContext);  
        TextView lblListHeader = new TextView(myContext);
        lblListHeader.setText(headerTitle.toUpperCase());
        lblListHeader.setGravity(Gravity.LEFT);         
        lblListHeader.setTextSize(18);
        lblListHeader.setPadding(50, 20, 0, 20);
        lblListHeader.setTextColor(myContext.getResources().getColor(R.color.BlackColor));
        layout.addView(lblListHeader);
        RelativeLayout.LayoutParams noOfTypesLp = new RelativeLayout.LayoutParams
        (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        noOfTypesLp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        TextView txtNoOfType = new TextView(myContext);
        txtNoOfType.setText(String.valueOf(noOfType));
        txtNoOfType.setTextSize(16);            
        txtNoOfType.setPadding(0, 20, 20, 20);
        txtNoOfType.setTextColor(myContext.getResources().getColor(R.color.BlackColor));
        layout.addView(txtNoOfType,noOfTypesLp);

        return layout;
    }
    @Override
    public boolean hasStableIds() {
        return false;
    }    
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

}

Sudhansu
  • 780
  • 1
  • 9
  • 28

2 Answers2

1

In your OnItemClickListener:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();                                   
bundle.putString("MainCategoryName", mainCategory.masterinfo.get(position-1).maincatname);
fragment.setArguments(bundle);

It would not be the right approach. What you need do is to transfer data to 2nd fragment not the "new Fragment".

I think you can do it like this: 1.transfer data to ServiceActivity; 2.replace 1st fragment with 2nd fragment and setArguments() to transfer data to 2nd fragment.

code:
1. create a callback like this:

public interface MainfragmentCallBack{
    public void showData(String data, int id);
}

2.ServiceActivity implements MainfragmentCallBack and over ride showData();

3, showData() in ServiceActivity:

@Override
public void showData(String data, int id){
    //use FragmentTransaction to replace 1st fragment with 2nd fragment
    //use setArgument to transfer data   
    // I do not konw your layout of ServiceActivity,so you can implement it on yourself 
}

4, instantiate MainFragmentCallBack in 1st fragment, use it in OnItemClickListener

suggestion:
Show data in another activity instead of ServiceActivity is a better choice in this case.

zhenghuiyan
  • 324
  • 4
  • 10
  • yes it make sense but can you please post the method here. – Sudhansu Oct 23 '15 at 10:08
  • When i send to another activity using intent i got an error on this line..getActivity().getApplication().startActivity(subCategoryIntent); in 1st fragment – Sudhansu Oct 23 '15 at 12:01
  • Can i use bundle to send data directly to another fragment not onclickistner but onCreate method? – Sudhansu Oct 29 '15 at 10:28
0

You should use callbacks. The Android team have a guide here: http://developer.android.com/training/basics/fragments/communicating.html

Eixx
  • 313
  • 2
  • 14