1

I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.

Below is my code.

UserListFragment.java

public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment UsersListFragment.
 */
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
    UsersListFragment fragment = new UsersListFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    progressBar = new ProgressDialog(getActivity());
    progressBar.setCancelable(false);
    progressBar.setMessage("Loading...");
    progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressBar.setProgress(0);
    Log.i(TAG, "UsersListFragment onCreate");
    users = new ArrayList<>();
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    SharedPreferences  preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);

    preferenceEditor = preferenceSettings.edit();
    preferenceEditor.putString("refresh","userlistview");
    preferenceEditor.commit();
    FirebaseUtil uts = new FirebaseUtil(getContext());
    uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
        @Override
        public void onCallback(Map<String, Object> response, String Success) {
            Log.i(TAG, Success);
            setHasOptionsMenu(true);
            String partnerKey = (String) response.get("key");
            if (partnerKey != null) {

                Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
                String type = (String) typeCheck.get("type");

                if (type.equals("chat")) {

                    String key1 = Global.getInstance().ownerId;
                    String key2 = partnerKey;
                    partnerKeyValue = partnerKey;

                    if (key2 != null) {

                        String currentPartner = Global.getInstance().partnerId;
                        if (currentPartner.length() > 0) {

                            if (currentPartner.equals(partnerKey)) {

                            } else {
                                Global.getInstance().unreadMessageUsers.add(partnerKey);
                            }
                        Global.getInstance().unreadMessageUsers.add(partnerKey);
                        } else {


                        }
                    }
                }
            }
        }
    });

}

@Override
public void onStart() {
    super.onStart();
    Log.i(TAG, "UsersListFragment onStart");
}

@Override
public void onResume() {
    super.onResume();
    Log.i(TAG, "UsersListFragment onResume");
}

@Override
public void onPause() {
    super.onPause();
    Log.i(TAG, "UsersListFragment onStart");
}

@Override
public void onStop() {
    super.onStop();
    Log.i(TAG, "UsersListFragment onStop");
}

@Override
public void onDestroyView() {
    super.onDestroyView();
}

@Override
public void onDestroy() {
    super.onDestroy();
    FirebaseUtil util = new FirebaseUtil(getContext());
    util.updateUserStatus(Global.getInstance().ownerId, "4");
    Log.i(TAG, "UsersListFragment onDestroy");
}


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

    actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
    if(actionBar!=null) {
        actionBar.setDisplayUseLogoEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setLogo(R.drawable.ic_logo);
        ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
        actionBar.setBackgroundDrawable(colorDrawable);
    }
    Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
    int vd  = users.size();
    view = inflater.inflate(R.layout.fragment_userslist, container, false);
    listView = (ListView) view.findViewById(R.id.userdisplay);

    adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
    listView.setAdapter(adapter);
    if (users.size()==0){
        usersList();
    }else {
        adapter.notifyDataSetChanged();
    }
   listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           UserData data = users.get(position);
           Global.getInstance().someData = data.getId();
           Global.getInstance().partnerId = data.getId();
           int i = 0;
           for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
               String element = iter.next();
               if (element.equals(data.getId().toString())) {
                   iter.remove();
               }
           }
           data.setUnreadMessageCount(0);
           users.remove(position);
           users.add(position, data);
                   Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
                   Fragment fragmentOne = new ChatFragment();
                   android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
           Bundle args = new Bundle();
           args.putString(ChatFragment.DATA_RECEIVE, data.getName());
           fragmentOne .setArguments(args);
                   ft.addToBackStack(null);
                   ft.replace(R.id.framecontainerMain, fragmentOne).commit();
               }
   });
    // Inflate the layout for this fragment
    return view;
}

public  void usersList () {
   SharedPreferences  preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);

   preferenceEditor = preferenceSettings.edit();
   //get the data from userlist api
   final String URL = "url";
   String token = preferenceSettings.getString("authToken","");
   final String userId = preferenceSettings.getString("userId","");

   HashMap<String, String> params = new HashMap<String, String>();

   params.put("user_id",userId);
   params.put("auth_token",token);
   progressBar.show();
   JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {

                   Log.i(TAG, "onResponse:" +response);

                   String success = null;
                   try {
                       success = response.getString("success");
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
                   if(success == "true") {

                       JSONArray Array = null;
                       try {
                           //get the users


                               } else {
                                   users.add(data);
                               }

                           }
                           Log.i(TAG, "arraylist");
                           adapter.notifyDataSetChanged();
                           onlineUsers();
                           myTimer = new Timer();
                           myTimer.schedule(new TimerTask() {
                               @Override
                               public void run() {
                                   TimerMethod();
                               }

                           }, 0, 5000);
                           progressBar.dismiss();


                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                       JSONObject Obj;

                   } else {

                   }


               }
           }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
           progressBar.dismiss();
           VolleyLog.e("Error: ", error.getMessage());
           Log.i(TAG, "onErrorResponse:" +error.networkResponse);
       }
   });

   ApplicationController.getInstance().addToRequestQueue(myRequest);

   myRequest.setRetryPolicy(new DefaultRetryPolicy(
           5000,
           DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
           DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

}

public void sortingArray(){
  if (users.size()>0) {
        synchronized (this) {
            if (Global.getInstance().unreadMessageUsers.size() > 0) {
                System.out.println("\nExample 3 - Count all with Map");
                Map<String, Integer> map = new HashMap<String, Integer>();

                for (String temp : Global.getInstance().unreadMessageUsers) {
                    Integer count = map.get(temp);
                    map.put(temp, (count == null) ? 1 : count + 1);
                }


                System.out.println("\nSorted Map");
                Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);

           for (String key : unreadCount.keySet()) {

                    int count_unread = unreadCount.get(key);

                    int i = 0;
                    for (UserData obj : users) {
                        UserData user = obj;

                        if (user.getId().equals(key)) {
                            user.setUnreadMessageCount(count_unread);
                            users.remove(i);
                            users.add(i, user);

                            break;
                        }
                        i++;
                    }
                }
            }
            synchronized (this) {
                if (Global.getInstance().userStatus.size() > 0) {
                    try {

                        for (Object dict : Global.getInstance().userStatus) {
                            Map<String, Object> val = (Map<String, Object>) dict;
                            String key = val.keySet().iterator().next();
                             val.get(key).toString().trim();
                            int statusValue;
                            if (val.get(key).toString().equals("")) {
                                statusValue = 4;
                            } else {
                                statusValue = Integer.valueOf(val.get(key).toString());
                            }

                            int i = 0;
                            for (UserData obj : users) {
                                UserData user = obj;

                                if (user.getId().equals(key)) {
                                    user.setOnlineStatus(statusValue);
                                    users.remove(i);
                                    users.add(i, user);
                                    break;
                                }
                                i++;
                            }

                        }

                    }catch (ConcurrentModificationException e){
                        e.printStackTrace();
                    }
                }
            }
             Log.i(TAG, users.get(0).getName());
            if (users.size() > 0) {
                Collections.sort(users, new Comparator<UserData>() {
                    @Override
                    public int compare(UserData o1, UserData o2) {

                        if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
                            return 1;
                        } else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
                            return -1;
                        } else {
                            return 0;
                        }

                    }

                });
            }

            if (users.size() > 0) {
                Collections.sort(users, new Comparator<UserData>() {
                    @Override
                    public int compare(UserData o1, UserData o2) {

                        if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
                            return -1;
                        } else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
                            return 1;
                        } else {
                            return 0;
                        }

                    }

                });
                Global.getInstance().userStatus.clear();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
                        adapter.notifyDataSetChanged();
                    }
                });

            }
        }

    }
}

 public void TimerMethod() {

            synchronized(this) {
                SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
                String checkView = preferenceSettings.getString("refresh", "");
                if (checkView.equals("userlistview")) {
                    if (Global.getInstance().userStatus.size() > 0) {
                        sortingArray();

                    }

                } else {

                    preferenceEditor = preferenceSettings.edit();
                    preferenceEditor.putString("refresh", "userlistview");
                    preferenceEditor.commit();

                    if (Global.getInstance().unreadMessageUsers.size() > 0){
                        sortingArray();

                    }
                }
            }
   }

public void onlineUsers (){
    String  value;
    for (UserData data : users) {
        value = data.getId();

        FirebaseUtil online = new FirebaseUtil(getContext());
        online.onlineUsers(value, new CallBack() {
            @Override
            public void onCallback(Map<String, Object> response, String Success) {

                if (response == null) {

                } else {
                Global.getInstance().userStatus.add(response);

                }
            }
        });

    }
}


@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {

    inflater.inflate(R.menu.menu_userlist,menu);
    MenuItem item = menu.findItem(R.id.menuSearch);
    SearchView searchView = (SearchView)item.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            return false;
        }
    });

    super.onCreateOptionsMenu(menu,inflater);
}


private void logoutUser(){
    Intent I = new Intent(getActivity(), LoginActivity.class);
    startActivity(I);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.menuSearch :
            return true;

        case R.id.menuLogout :
            logoutUser();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }

}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        String val = "'";
        mListener.onFragmentInteraction(val);
    }
}

public void initlizeval(Context context) {

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

@Override
public void onDetach() {
    super.onDetach();
    myTimer.cancel();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(String val);
}
}

menu_userlist.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item android:id="@+id/menuSearch"
    android:title="@string/search"
    android:icon="@drawable/ic_search"
    app:actionViewClass="android.widget.SearchView"
    app:showAsAction="always">
</item>

<item android:id="@+id/menuLogout"
    android:title="@string/logout"
    android:icon="@drawable/ic_logout"
    android:tint="@android:color/white"
    app:showAsAction="always">
</item>
</menu>

CustomAdapter.java

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;

public class CustomAdapter extends ArrayAdapter<UserData> {

    private Activity activity;
    private List<UserData> messages;

    public CustomAdapter(Activity context, int resource, List<UserData> objects) {
        super(context, resource, objects);
        this.activity = context;
        this.messages = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       packagename.CustomAdapter.ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        int layoutResource = 0; // determined by view type
        UserData data = getItem(position);
        int viewType = getItemViewType(position);

            layoutResource = R.layout.program_list;

        if (convertView != null) {
            holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
        } else {
            convertView = inflater.inflate(layoutResource, parent, false);
            holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
            convertView.setTag(holder);
        }

        //set message content
        holder.msg.setText(data.getName());
        holder.id = data.geId();
        holder.roleMsg.setText(data.getRole());


        return convertView;
    }

    @Override
    public int getViewTypeCount() {
        // return the total number of view types. this value should never change
        // at runtime
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        // return a value between 0 and (getViewTypeCount - 1)
        return position % 2;
    }

    private class ViewHolder {
        private TextView msg;
        private String id;
        private TextView roleMsg;

        public ViewHolder(View v) {
            msg = (TextView) v.findViewById(R.id.textView1);
            roleMsg = (TextView) v.findViewById(R.id.textView2);

        }
    }
}

HomeActivity.java

public class HomeActivity extends AppCompatActivity implements    UsersListFragment.OnFragmentInteractionListener {

private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;

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

    VideoFragment fragmentTwo ;



        LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
        layout1.setVisibility(View.VISIBLE);


        LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
        layout2.setVisibility(View.VISIBLE);



        mItemsFragment = new UsersListFragment();
        mItemsFragment.initlizeval(this);

        android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();

        fts.add(R.id.framecontainer, mItemsFragment).commit();

        //Instantiate some stuff here like view components
        Fragment fragmentOne = new ChatFragment();
        android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();


        ft.add(R.id.framecontainerTab, fragmentOne).commit();
    }else{
        LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
        layout1.setVisibility(View.GONE);
        LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
        layout2.setVisibility(View.GONE);
        layout2.removeAllViews();


        mItemsFragment = new UsersListFragment();
        mItemsFragment.initlizeval(this);
        setFragment(mItemsFragment);
    }

}

public void setFragment(Fragment frag)
{
    android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

}

public void attemptLogin1() {
    String test = "one";
    String tested = "fail";
}



@Override
public void onFragmentInteraction(String uri) {
    LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
    layout1.setVisibility(View.GONE);
    LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
    layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
      Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();

}

@Override
protected void onPause() {
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
        Fragment fragmentOne = new ChatFragment();
        LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
        layout1.setVisibility(View.VISIBLE);
        LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
        layout2.setVisibility(View.VISIBLE);

}

@Override
protected void onStart() {
    super.onStart();
    getDelegate().onStart();


}
}

I have written setHasOptionsMenu(true); in onCreate of UserFragment.java The logout functionality works fine but the search isn't working.

I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(

Any help is appreciated. Thanks in advance.

Saloni
  • 172
  • 2
  • 15

2 Answers2

0

Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.

K P
  • 112
  • 9
0

Remove this line and it will work

case R.id.menuSearch:
    return true;
Fruchtzwerg
  • 9,895
  • 12
  • 39
  • 45
Umar Ata
  • 3,889
  • 3
  • 22
  • 34
  • also post the code of your adapter and are you getting adapter reference in oncreateOptionsMenu – Umar Ata Jan 19 '17 at 08:10
  • Removing that line didn't worked for me. Also I added the adapter code. – Saloni Jan 19 '17 at 08:57
  • ok, where is the getfilter method, and may be your activity serachview overlaps the fragment searchview – Umar Ata Jan 19 '17 at 08:58
  • I haven't written any searchview in Activity class.And can you please tell where should I use getFilter method and what should I write in it. – Saloni Jan 19 '17 at 09:01
  • you written "When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview." so where is the logic of filter – Umar Ata Jan 19 '17 at 09:03
  • Okay. May be my question is misleading you. I tried writing searchview in activity file with the code. It worked fine. But when I am writing it in fragmet of that activity removing the code from activity. It doesn't work. Let me clear you more. I have an activity which contains two fragments. I want searchview in first fragment but not in the second fragment. – Saloni Jan 19 '17 at 09:15
  • Yes its appearing, but when I search something, It doesn't display the searched text in listview. – Saloni Jan 19 '17 at 09:26
  • okay , you called this adapter.getFilter().filter(newText); where is the code of this method – Umar Ata Jan 19 '17 at 09:30
  • Actually same code I wrote for activity class and it was working. So,I haven't written any code for that method. Can you tell me what can I do. – Saloni Jan 19 '17 at 09:33
  • I have used adapter to add my listview content. private CustomAdapter adapter; I used adapter.getFilter().filter(newText); to filter the contents in listview which was totally working fine in activity class. – Saloni Jan 19 '17 at 09:56
  • okay are you using the same adapter in fragment, because the adpter you posted doesnot contain any filter logic – Umar Ata Jan 19 '17 at 10:03
  • This adapter I am using in fragment only, not in any activity or other fragment. – Saloni Jan 19 '17 at 10:11
  • compare both adapter of activity and fragment you will find the filter code – Umar Ata Jan 19 '17 at 10:14
  • I haven't used any adapter in my activity. Can you help me please. Still I am stuck with this problem. – Saloni Feb 01 '17 at 05:55