片段返回时不会刷新自定义列表视图

时间:2017-01-30 14:35:45

标签: java android android-fragments android-viewpager android-custom-view

我有一个自定义列表视图适配器加载联系人列表。当我打开应用程序时,联系人正在加载完美,但是一旦我滚动到Preference Fragment后回来,listview是空的。虽然通过调用Inner类LoadContact收集数据但在listview中没有任何内容。有三个片段。请指导。 片段代码(tab1)。如果你看到我在oncreatview中添加了适配器初始化,否则在后面的选项卡上我得到Null点异常。我在这里做对了吗?

public class Requestor extends Fragment {

    EditText targetdevice;
    ListView recentlist;
    List<String> recentlistarray = new ArrayList<>();
    ArrayAdapter arrayAdapter;
    Dialog dialog;
    String targetmobile, requesttype;
    private TextView tex1, remotelocation;
    int deviceid;
    LinearLayout contactlayout;
    RadioButton radiorecent, radiocontact;

   ArrayList<ContactListSelectUser> contactListSelectUsers;
    List<ContactListSelectUser> temp;
    // Contact List
    ListView listView;

    // Cursor to load contacts list
    Cursor phones, email;

    // Pop up
    ContentResolver resolver;
    SearchView search;
    ContactListAdapter adapter;


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LoadContact loadContact = new LoadContact();
        loadContact.execute();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) throws NullPointerException{
        View view = inflater.inflate(R.layout.autolocationrequester, container, false);

        targetdevice = (EditText) view.findViewById(R.id.targetdevice);
        recentlist = (ListView) view.findViewById(R.id.targetlist);
        remotelocation = (TextView) view.findViewById(R.id.remotelocationreq);
        tex1 = (TextView) view.findViewById(R.id.tex1);
        requesttype = "Location";
        radiorecent = (RadioButton) view.findViewById(R.id.radiorecent);
        radiocontact = (RadioButton) view.findViewById(R.id.radiocontact);
        contactlayout = (LinearLayout) view.findViewById(R.id.contactlayout);
        tex1 = (TextView) view.findViewById(R.id.tex1);
        recentlist.setVisibility(View.GONE);
        contactlayout.setVisibility(View.GONE);
        tex1.setVisibility(View.GONE);

        contactListSelectUsers = new ArrayList<ContactListSelectUser>();
        resolver = getActivity().getApplicationContext().getContentResolver();
        listView = (ListView) view.findViewById(R.id.contacts_list);
       adapter = new ContactListAdapter(contactListSelectUsers, getActivity().getApplicationContext());
        phones = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");


        LoadContact loadContact = new LoadContact();
        loadContact.execute();

        search = (SearchView) view.findViewById(R.id.searchView);

        //*** setOnQueryTextListener ***
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO Auto-generated method stub

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // TODO Auto-generated method stub
                adapter.filter(newText);
                return false;
            }

        });
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
        deviceid = Integer.parseInt(sharedPreferences.getString("deviceid", ""));

        remotelocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                arrayAdapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, recentlistarray);
                recentlist.setAdapter(arrayAdapter);
                targetmobile = targetdevice.getText().toString();
                new sendreqloc().execute();
                targetdevice.setText("");

                // Popup.smallpopup("hi", getApplicationContext());
            }
        });

        radiorecent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recentlist.setVisibility(View.VISIBLE);
                tex1.setVisibility(View.VISIBLE);
                contactlayout.setVisibility(View.GONE);
                targetdevice.setText("");
            }
        });


        radiocontact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recentlist.setVisibility(View.GONE);
                contactlayout.setVisibility(View.VISIBLE);
                tex1.setVisibility(View.GONE);
                targetdevice.setText("");
                LoadContact loadContact = new LoadContact();
                loadContact.execute();

            }
        });

        return view;
    }


    public class LoadContact extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {

            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... voids) {
            // Get Contact list from Phone

            if (phones != null) {
                Log.e("count", "" + phones.getCount());
                if (phones.getCount() == 0) {
                    //       Toast.makeText(Requestor.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
                }

                while (phones.moveToNext()) {
                  Log.d("Contact Class Called","");
                    Bitmap bit_thumb = null;
                    String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //    String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
                    String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                    try {
                        if (image_thumb != null) {
                            bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
                        } else {
                            Log.e("No Image Thumb", "--------------");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ContactListSelectUser contactListSelectUser = new ContactListSelectUser();
                    contactListSelectUser.setThumb(bit_thumb);
                    contactListSelectUser.setName(name);
                    contactListSelectUser.setPhone(phoneNumber);
                    contactListSelectUser.setEmail(id);
                    // contactListSelectUser.setCheckedBox(false);
                    // if (!contactListSelectUsers.contains(contactListSelectUser.getPhone())) {
                    contactListSelectUsers.add(contactListSelectUser);
                    //}

                }
            } else {
                Log.e("Cursor close 1", "----------------");
            }
            //phones.close();
            //System.out.println(contactListSelectUsers.size());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            adapter = new ContactListAdapter(contactListSelectUsers, getActivity());
            listView.setAdapter(adapter);

            // Select item on listclick
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    Log.e("search", "here---------------- listener");

                    ContactListSelectUser data = contactListSelectUsers.get(i);
                    targetdevice.setText(data.getPhone());
                }
            });

            listView.setFastScrollEnabled(true);
        }
    }

   /* @Override
    protected void onStop() {
        super.onStop();
        phones.close();
    }*/
}

自定义适配器类代码:

    public class ContactListAdapter extends BaseAdapter implements Filterable {

        public List<ContactListSelectUser> _data;


 private ArrayList<ContactListSelectUser> arraylist;
    Context _c;
    ViewHolder v;
    RoundImage roundedImage;
    private Filter filter = new CustomFilter();

    public ContactListAdapter(List<ContactListSelectUser> contactListSelectUsers, Context context) {
        _data = contactListSelectUsers;
        _c = context;
        this.arraylist = new ArrayList<ContactListSelectUser>();
        this.arraylist.addAll(_data);
    }

    @Override
    public int getCount() {
        return _data.size();
    }

    @Override
    public Object getItem(int i) {
        return _data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        View view = convertView;
        if (view == null) {
            LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.contact_info, null);
            Log.e("Inside", "here--------------------------- In view1");
        } else {
            view = convertView;
            Log.e("Inside", "here--------------------------- In view2");
        }

        v = new ViewHolder();

        v.title = (TextView) view.findViewById(R.id.name);
        //   v.check = (CheckBox) view.findViewById(R.id.check);
        v.phone = (TextView) view.findViewById(R.id.no);
        v.imageView = (ImageView) view.findViewById(R.id.pic);

        final ContactListSelectUser data = (ContactListSelectUser) _data.get(i);
        v.title.setText(data.getName());
        //    v.check.setChecked(data.getCheckedBox());
        v.phone.setText(data.getPhone());

        // Set image if exists
        try {

            if (data.getThumb() != null) {
                v.imageView.setImageBitmap(data.getThumb());
            } else {
                v.imageView.setImageResource(R.mipmap.ic_launcher);
            }
            // Seting round image
            Bitmap bm = BitmapFactory.decodeResource(view.getResources(), R.mipmap.ic_launcher); // Load default image
            roundedImage = new RoundImage(bm);
            v.imageView.setImageDrawable(roundedImage);
        } catch (OutOfMemoryError e) {
            // Add default picture
            v.imageView.setImageDrawable(this._c.getDrawable(R.mipmap.ic_launcher));
            e.printStackTrace();
        }

        Log.e("Image Thumb", "--------------" + data.getThumb());

        /*// Set check box listener android
        v.check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    data.setCheckedBox(true);
                  } else {
                    data.setCheckedBox(false);
                }
            }
        });*/

        view.setTag(data);
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        _data.clear();
        if (charText.length() == 0) {
            _data.addAll(arraylist);
        } else {
            for (ContactListSelectUser wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    _data.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public Filter getFilter() {
        return filter;
    }

    static class ViewHolder {
        ImageView imageView;
        TextView title, phone;
        CheckBox check;
    }

    private class CustomFilter extends Filter {


        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            _data.clear();

            FilterResults filterResults = new FilterResults();
            filterResults.values = _data;
            filterResults.count = _data.size();
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            if (filterResults.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

下面是logcat,当我选择返回片段但未设置为listview时,你可以看到获取数据。

E/Inside: here--------------------------- In view1
E/Image Thumb: --------------null
E/Inside: here--------------------------- In view1
E/Image Thumb: --------------null
I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
E/count: 2
E/No Image Thumb: --------------
E/No Image Thumb: --------------
E/count: 2
E/count: 2

2 个答案:

答案 0 :(得分:0)

在BaseAdapter中实现Filterable

public class ContactListAdapter extends BaseAdapter implements Filterable

并添加值:

private Filter filter = new CustomFilter();

并在baseAdapter中创建类:

private class CustomFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
          _data.clear();

        if (arraylist != null && constraint != null) {
            for (int i = 0; i < arraylist.size(); i++) {
                if (arraylist.get(i).toString().toLowerCase().contains(constraint)) {
                    _data.add(arraylist.get(i));
                }
            }
        }

    FilterResults results = new FilterResults();
            results.values = _data;
            results.count = _data.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

添加你的baseAdapter类:

@Override
public Filter getFilter() {
    return filter;
}

我的适配器例如:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CustomArrayAdapter extends BaseAdapter implements Filterable{
    private LayoutInflater mInflater;
    private final Context context;
    private List<String> mItems;
    private Filter filter = new CustomFilter();
    private ArrayList<String>mItemsSuggestion = new ArrayList<String>();

    public CustomArrayAdapter(Context context, String[] values) {
        this.context = context;
        mItems = Arrays.asList(values);
    }

    @Override
    public int getCount() {
        return mItemsSuggestion.size();
    }

    @Override
    public Object getItem(int position) {
        return mItemsSuggestion.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View oneView = mInflater.inflate(R.layout.towar_list, parent, false);
        TextView text = (TextView)oneView.findViewById(R.id.towaryAllList);
        text.setText(mItemsSuggestion.get(position).toString());
        return oneView;
    }


    @Override
    public Filter getFilter() {
        return filter;
    }

    private class CustomFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            mItemsSuggestion.clear();

            if (mItems != null && constraint != null) {
                for (int i = 0; i < mItems.size(); i++) {
                    if (mItems.get(i).toString().toLowerCase().contains(constraint)) {
                        mItemsSuggestion.add(mItems.get(i));
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = mItemsSuggestion;
            results.count = mItemsSuggestion.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

答案 1 :(得分:0)

我现在解决了。问题只是将搜索视图代码放置在单击侦听器的radiocontact中,而不是直接放在createview方法中。