简体   繁体   中英

Passing a variable from Activity to Fragment

My Activity implements an interface called MyInterface that has a method called getList. This method grabs a arrayList of objects and returns it at the end. I am trying to access the variable in another fragment and have been struggling to do so. I have looked into bundling, intents, parcelables and have been using the current interface route. How do I access the variable in my Fragment?

Below is my getList method which returns the object of arraylists called arrayListAndroidContacts

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

        //--< get all Contacts >--
        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)

        {
//----< has Contacts >----
//----< @Loop: all Contacts >----
            while (cursor_Android_Contacts.moveToNext()) {
//< init >
                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));
//</ init >

//----< set >----
                android_contact.android_contact_Name = contact_display_name;


//----< get phone number >----
                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));
//< set >
                        android_contact.android_contact_TelefonNr = phoneNumber;
//</ set >
                    }
                    phoneCursor.close();
                }

                arrayListAndroidContacts.add(android_contact);

            }


            Collections.reverse(arrayListAndroidContacts);

            Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayListAndroidContacts);

            ListView listView_Android_Contacts = (ListView) findViewById(R.id.listview_Android_Contacts);

            listView_Android_Contacts.setAdapter(adapter);

        }
        return arrayListAndroidContacts;
    }

This is my Fragment which currently contains my instance of the interface, my adapter for the listview and the a call to the value of arrayListAndroidContacts

public class Tab1Recents extends Fragment {
    MyInterface myInterface;

    public static final String MESSAGE_KEY = "message_key";

    public void onAttach(MainActivity activity) {
        super.onAttach(activity);
        try {
            myInterface = (MyInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onViewSelected");
        }
    }




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


        Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayListAndroidContacts);

        View rootView = inflater.inflate(R.layout.tab1_recent, container, false);

        ListView recentContacts = (ListView) rootView.findViewById(R.id.recent_Android_Contacts);

        recentContacts.setAdapter(adapter);

        return rootView;
    }

    public class Adapter_for_Android_Contacts extends BaseAdapter {

        Context mContext;
        List<MainActivity.Android_Contact> mList_Android_Contacts;

        //< constructor with ListArray >
        public Adapter_for_Android_Contacts(Context mContext, List<MainActivity.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;
        }
    }

}

First, you use ContentResolver to query, so getList() should be invoked in a non-UI thread(so, the creation of adapter and update for ListView must not be in this method.

Then you can start a async thread/task/service to invoke getList() from activity or fragment.

Once arrayListAndroidContacts comes, you can use View.post(Runnable) to post an UI operation(create adapter and update ListView), or use BroadcastReceiver , or use EventBus . Choose one that you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM