NVA
NVA

Reputation: 1692

Android passing data while using Activity, Fragment, Listview and Tabs

In my MainActivity I derive an arrayList of data. The trick here is that I am trying to rearrange this data Collection in a listview in different ways according to the tab that is selected for example (alphabetically, chronologically etc) I have the code that does that.

Below is my main activity.

public class MainActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;
    private FloatingActionButton fab;
    private final int PICK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fp_get_Android_Contacts();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                // calling OnActivityResult with intenet And Some conatct for Identifie
                startActivityForResult(intent, PICK);
            }
        });
    }

    public class Android_Contact {
        public String android_contact_Name = "";
        public String android_contact_TelefonNr = "";
        public int android_contact_ID = 0;
    }

    public void fp_get_Android_Contacts() {
        ArrayList<Android_Contact> arrayListAndroidContacts = new ArrayList<Android_Contact>();

        Cursor cursor_Android_Contacts = null;
        ContentResolver contentResolver = getContentResolver();
        try {
            cursor_Android_Contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        } catch (
                Exception ex
                )

        {
            Log.e("Error on contact", ex.getMessage());
        }
        if (cursor_Android_Contacts.getCount() > 0)

        {

            while (cursor_Android_Contacts.moveToNext()) {

                Android_Contact android_contact = new Android_Contact();
                String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
                String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                android_contact.android_contact_Name = contact_display_name;

                int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {

                    Cursor phoneCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                            , null
                            , ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
                            , new String[]{contact_id}
                            , null);

                    while (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        android_contact.android_contact_TelefonNr = phoneNumber;

                    }
                    phoneCursor.close();
                }

                arrayListAndroidContacts.add(android_contact);

            }
            Collections.reverse(arrayListAndroidContacts);
            ListView listView_Android_Contacts = (ListView) findViewById(R.id.listview_Android_Contacts);

            Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayListAndroidContacts);

            listView_Android_Contacts.setAdapter(adapter);
        }
    }

    public class Adapter_for_Android_Contacts extends BaseAdapter {

        Context mContext;
        List<Android_Contact> mList_Android_Contacts;

        public Adapter_for_Android_Contacts(Context mContext, List<Android_Contact> mContact) {
            this.mContext = mContext;
            this.mList_Android_Contacts = mContact;
        }

        public int getCount() {
            return mList_Android_Contacts.size();
        }

        public Object getItem(int position) {
            return mList_Android_Contacts.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(mContext, R.layout.contactlist_android_items, null);
            TextView textview_contact_Name = (TextView) view.findViewById(R.id.textview_android_contact_name);
            textview_contact_Name.setText(mList_Android_Contacts.get(position).android_contact_Name);
            view.setTag(mList_Android_Contacts.get(position).android_contact_Name);
            return view;
        }

    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:

                    Tab2AZ tab2 = new Tab2AZ();
                    return tab2;
                case 1:
                    Tab1Recents tab1 = new Tab1Recents();
                    return tab1;
                case 2:
                    Tab3Location tab3 = new Tab3Location();
                    return tab3;
                case 3:
                    Tab4Groups tab4 = new Tab4Groups();
                    return tab4;
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "A-Z";
                case 1:
                    return "RECENT";
                case 2:
                    return "LOCATION";
                case 3:
                    return "TAGS";
            }
            return null;
        }
    }
}

To save you time the fp_get_Android_Contacts() method grabs the arraylist, then uses the adapter to put the content in the listview that is in the main activity xml. The result is that all the tabs visually display the same view. (Because the MainActivity's Listview is covering the fragment's listviews) I'm really just trying to get the content retrieved from the fp_get_Android_Contacts() method to display on one fragment at a time. Ive looked into using bundles, parcelables, intents and recently interfaces however successful implementation has been tough to achieve given my experience level perhaps. Would appreciate a specific approach instead of a reference to read something as I have done a lot of research and tried many things already.

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.tab1_recent, container, false);
        return rootView;
    }
}

Upvotes: 0

Views: 524

Answers (2)

Ravi
Ravi

Reputation: 181

Create Interface

public interface FragmentListener {
  void setArrayListAndroidContacts(List<Android_Contact> contacts);
  List<Android_Contact> getArrayListAndroidContacts();
}

Let your MainActivity implement this interface

public class MainActivity extends AppCompatActivity implements FragmentListener {
//global field
private List<Android_Contact> arrayListAndroidContacts;
...
//your code
...
//override methods of interface
@Override
void setArrayListAndroidContacts(List<Android_Contact> contacts){
this.arrayListAndroidContacts = contacts;
}

@Override
List<Android_Contact> getArrayListAndroidContacts(){
return this.arrayListAndroidContacts;
}

Your fragment

public class YourFragment extends Fragment{

private FragmentListener mListener;

...
//in onCreateView
//this will give you list 
mListener.getArrayListAndroidContacts();
....

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof FragmentListener) {
            mListener = (FragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement FragmentListener");
        }
    }
}

Another method is just create public getter setter of arrayListAndroidContacts in MainActivity and in your fragment use (MainActivity getActivity()).getArrayListAndroidContacts() to get the list. I would prefer interface method because of reusability.

Also why create viewpager, fragments if you want to rearrange data by a filter selection(sort by alpha,chrono) without any view changes.

Just add filter menu actions in floatingmenu/toolbarsidemenu, recyclerview(any list view) and customadapter for it in Mainactivity. Depending on the filter selection reorder your contacts list and notifydatasetchanged will do all your work.

Go for tabs if you want to have category of contacts like favorites, business etc.. to be displayed in single screen.

Suggestion:- Kindly separate your custom BaseAdapter code from MainActivity for better source code maintenance .

Upvotes: 2

sohaib karim
sohaib karim

Reputation: 281

You should be having multiple tabs and corresponding Fragments for those tabs. Right ? I can not find that in your code. For every fragment generate a separate .xml file and create separate listview in each fragment and pass the data in each fragment accordingly. And you are done.

e.g., for alphabetically : Create fragment AlphabetSortFragment and for the same create a .xml file and a listview or recycler view in it.

Upvotes: 1

Related Questions