添加新联系人后如何更新RecyclerView(包含联系人列表)?

时间:2019-06-03 09:43:59

标签: android android-recyclerview contacts

我的问题是:

我有4个课程:

  • MainActivity.java
  • RecyclerViewAdapter.java
  • ContactFragment.java
  • NewContactActivity.java

现在是我的故事:

  • MainActivity中,我单击AddButton转到NewContactActivity
  • NewContactActivity中,键入信息联系人,然后单击SaveButton将信息保存到ContactList,然后返回到MainActivity
  • 在MainActivity中,现在RecyclerView已使用我刚刚添加的新数据进行了更新

我的文件: MainActivity.java:

public class MainActivity extends AppCompatActivity {
    public static final int REQUEST_CODE_SPEECH_INPUT=1000;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;
    private Toolbar toolbar;

    private SearchView sv;
    private FloatingActionButton fab;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initializing vars
        tabLayout = (TabLayout) findViewById(R.id.tablayout_id);
        viewPager = (ViewPager) findViewById(R.id.viewpager_id);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        sv = (SearchView) toolbar.findViewById(R.id.searchview);
        fab =(FloatingActionButton)findViewById(R.id.fab);
        ImageView img_voice_search = (ImageView) toolbar.findViewById(R.id.ic_voice);

        adapter = new ViewPagerAdapter(getSupportFragmentManager());

        //Set to toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false); //Remove Title of Toolbar

        //Add Fragment here
        adapter.addFragment(new CallFragment(),"GẦN ĐÂY");
        adapter.addFragment(new ContactFragment(), "DANH BẠ");
        viewPager.setAdapter(adapter);

        //Custom tablayout
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabTextColors(getResources().getColor(R.color.colorHintTextLight), getResources().getColor(R.color.colorTextLight));


        //Speech to Text
        img_voice_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Auto focus to searchview when click image voice
                sv.setIconified(false);
                sv.requestFocus();
                speak();
            }
        });

        //fab on click event
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,NewContactActivity.class);
                startActivityForResult(intent, 2);
            }
        });
    }


    public void speak(){
        Intent mIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL
                , RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        mIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi speak something");
        try {
            startActivityForResult(mIntent, REQUEST_CODE_SPEECH_INPUT);
        } catch (Exception ex){
            Toast.makeText(this, "" + ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //receive and handle it
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_CODE_SPEECH_INPUT:{
                if(resultCode == RESULT_OK && null != data){
                    //get text array from voice intent
                    ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    //set to search view
                    sv.setQuery(result.get(0), true);
                }
                break;
            }
            case 2:{
                String message=data.getStringExtra("MESSAGE");
                Toast.makeText(getApplicationContext(), "Đã thêm danh bạ: " + message, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar, menu);
        return true;
    }
}

RecyclerViewAdapter.java:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
    Context mContext;
    List<Contact> mData;
    Dialog mDialog;
    private TextView dialog_tvName, dialog_tvPhone, dialog_Fname;

    public RecyclerViewAdapter(Context mContext, List<Contact> mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v;
        v = LayoutInflater.from(mContext).inflate(R.layout.item_contact, viewGroup, false);
        final MyViewHolder viewHolder = new MyViewHolder(v);
        //Initializing my dialog
        mDialog = new Dialog(mContext);
        mDialog.setContentView(R.layout.dialog_contact);
        mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        viewHolder.items_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_tvName = (TextView)mDialog.findViewById(R.id.dialog_tvName);
                dialog_tvPhone = (TextView)mDialog.findViewById(R.id.dialog_tvPhone);
                dialog_Fname = (TextView)mDialog.findViewById(R.id.dialog_Fname);
//                ImageView dialog_contact_img = (ImageView) mDialog.findViewById(R.id.dialog_img);
                dialog_tvName.setText(mData.get(viewHolder.getAdapterPosition()).getName());
                dialog_tvPhone.setText(mData.get(viewHolder.getAdapterPosition()).getPhone());
                dialog_Fname.setText(mData.get(viewHolder.getAdapterPosition()).getFname());
//                dialog_contact_img.setImageResource(mData.get(viewHolder.getAdapterPosition()).getPhoto());
//                Toast.makeText(mContext, "Test Click " + String.valueOf(viewHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
                mDialog.show();

                //Sự kiện click vào icon gọi để chuyển hướng cuộc gọi đến sđt đc chọn
                ImageView call_button = (ImageView)mDialog.findViewById(R.id.call_button);
                ImageView chat_button = (ImageView)mDialog.findViewById(R.id.chat_button);
                call_button.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
//                        Intent i1 = new Intent (mContext, MainActivity.class);
                        mContext.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mData.get(viewHolder.getAdapterPosition()).getPhone())));
                    }
                });
                //click vào icon sms để vào ô chat với sđt đó
                chat_button.setOnClickListener(new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        mContext.startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+ mData.get(viewHolder.getAdapterPosition()).getPhone())));
                    }
                });
            }
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int position) {
        myViewHolder.tvName.setText(mData.get(position).getName());
        myViewHolder.tvFname.setText(mData.get(position).getFname());
//        myViewHolder.img.setImageResource(mData.get(position).getPhoto());
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{
        private LinearLayout items_contact;
        private TextView tvName;
        private TextView tvFname;
        private ImageView img;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            items_contact = (LinearLayout) itemView.findViewById(R.id.contact_items_id);
            tvName = (TextView)itemView.findViewById(R.id.tvName);
            tvFname = (TextView)itemView.findViewById(R.id.tvFname);
            img = (ImageView)itemView.findViewById(R.id.img_contact);
        }
    }
}

ContactFragment.java:

public class ContactFragment extends Fragment {

    View v;
    private RecyclerView recyclerView;
    private List<Contact> lstContact;
    public ContactFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.contact_fragment, container, false);
        recyclerView = (RecyclerView)v.findViewById(R.id.contact_recyclerview);
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), lstContact);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        return v;
    }
    public void loadContacList(){
        //Accessing to contact list and get info
        ContentResolver resolver = getActivity().getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()){
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            List<String> lstPhoneNumber = new ArrayList<>();
            List<String> lstEmail = new ArrayList<>();

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

            while (phoneCursor.moveToNext() && phoneCursor != null){
                String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                lstPhoneNumber.add(phoneNumber);
            }
            phoneCursor.close();

            //Email
            Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI
                    , null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?"
                    , new String[]{id}, null);
            while (emailCursor.moveToNext() && emailCursor != null){
                String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                lstEmail.add(email);
            }
            emailCursor.close();
            lstContact.add(new Contact(id, name, name.substring(0, 1).toUpperCase()
                    , lstPhoneNumber.size() == 0 ? "" : lstPhoneNumber.get(0)
                    , lstEmail.size()== 0 ? "" : lstEmail.get(0)));
        }
        cursor.close();
        Collections.sort(lstContact, new CustomComparaterLetterContact());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lstContact = new ArrayList<>();
        loadContacList();
    }
    //Class to Compare lstContact for letters
    private class CustomComparaterLetterContact implements Comparator<Contact> {
        @Override
        public int compare(Contact o1, Contact o2) {
            return o1.getName().compareToIgnoreCase(o2.getName());
        }
    }
}

NewContactActivity.java:

public class NewContactActivity extends AppCompatActivity {
    private EditText edtName;
    private EditText edtPhone;
    private EditText edtEmail;
    private ImageButton btnBack;
    private TextView edtAdd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact);


        btnBack = (ImageButton) findViewById(R.id.btnBack);
        edtAdd = (TextView) findViewById(R.id.edtAdd);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
//        LinearLayout llExtraFields = findViewById(R.id.admin);
//        if (llExtraFields.getVisibility() == View.VISIBLE) {
//            llExtraFields.setVisibility(View.GONE);
//        } else {
//            llExtraFields.setVisibility(View.VISIBLE);
//        }
        edtAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edtName = (EditText) findViewById(R.id.edtName);
                edtPhone = (EditText) findViewById(R.id.edtPhone);
                edtEmail = (EditText)findViewById(R.id.edtEmail);

                String name = edtName.getText().toString();
                String phone = edtPhone.getText().toString();
                String email = edtEmail.getText().toString();

                ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();

                ops.add(ContentProviderOperation.newInsert(
                        ContactsContract.RawContacts.CONTENT_URI)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                        .build());
                if (name != null) {
                    ops.add(ContentProviderOperation.newInsert(
                            ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                            .withValue(
                                    ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                    name).build());
                }

                if (phone != null) {
                    ops.add(ContentProviderOperation.
                            newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
                            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                            .build());
                }

                if (email != null) {
                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
                            .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                            .build());
                }

                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                    Toast.makeText(getApplicationContext(), "Thêm thành công danh bạ: " + name, Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Thêm thành công danh bạ: " + name, Toast.LENGTH_SHORT).show();
                }

                Intent intent=new Intent();
                intent.putExtra("MESSAGE",name);
                setResult(2,intent);
                finish();
            }
        });
    }
}

我为此花了4天,但找不到解决方案。 非常感谢

3 个答案:

答案 0 :(得分:1)

请尝试在ContactFragment类中添加此代码,然后尝试。

     if(!Object.prototype.hasOwnProperty.call(this.clickHandlers, index)) 
   {
    this.clickHandlers[index] = () =>  
    this.props.btnCheckOutAction(this.props.currentState.isModelOpen);
    }
    return this.clickHandlers[index];


handleItemClick(key) {
        debugger
        console.log("index::::::::::::::::::::::", key);

        if (!Object.prototype.hasOwnProperty.call(this.clickHandlers, index)) {
            this.clickHandlers[index] = () => this.props.btnCheckOutAction(this.props.currentState.isModelOpen);
        }
        return this.clickHandlers[index];

    }

答案 1 :(得分:0)

'在向您的recyclerview添加新元素后添加'

notifyItemInserted(position);
notifyDatasetChanged();

'在您的适配器中。'

答案 2 :(得分:0)

您在setResult的{​​{1}}方法中放入了错误参数,这就是为什么NewContactActivity中的Toast不显示的原因。

如下修改您的MainActivity

setResult

MainActivity

setResult(Activity.RESULT_OK,intent);