why this function is not removing the duplicate strings from the list?
Because you're not dealing with String
s, you're dealing with AndroidAppProcess
and if you see the structure of this class:
public class AndroidAppProcess extends AndroidProcess {
private static final boolean SYS_SUPPORTS_SCHEDGROUPS = new File("/dev/cpuctl/tasks").exists();
/** {@code true} if the process is in the foreground */
public final boolean foreground;
/** The user id of this process. */
public final int uid;
...
you can see that each android process is assigned a unique id. Now the possibilities are that all the processes in your list are unique. So when you convert them to Set
there is no duplicate and so nothing is removed.
However, if you would have been dealing with pure String
's, then definitely the duplicates would be removed, as mentioned in this answer.
Method 1
As mentioned in this answer, A HashSet
uses a Map
implementation, which in turn, uses hashCode()
and equals()
to avoid duplicate elements.
One way to solve the issue is to override hashCode()
and equals()
in the AndroidAppProcess
Class, so that it represents your equals()
criteria
For Example:
public class AndroidAppProcess extends AndroidProcess {
...
...
@Override
public boolean equals(Object o) {
//return <write a logic that compare this AndroidAppProcess with another AndroidAppProcess.
}
@Override
public int hashCode() {
//return <this androidProcess name>.hashCode();
}
}
Method 2
You can use a TreeSet
instead of HashSet
with a custom Comparator that compares the String arrays for equality.
private void detectApps() {
//TODO: here set the running apps list to the Adapter
m_processesList =AndroidProcesses.getRunningAppProcesses();
//use TreeSet instead of HashSet
Set<AndroidAppProcess> set= new TreeSet<>(new Comparator<AndroidAppProcess>() {
@Override
public int compare(AndroidAppProcess o1, AndroidAppProcess o2) {
return /* Write a code that compares two AndroidAppProcess
For example you can write:
return o1.getPackageName() == o2.getPackageName();
P.S.: I'm not sure as what's the method to get the correct name,
but you get the idea so you can search the library to get the correct name.
*/
}
});
set.addAll(m_processesList);
m_processesList.clear();
m_processesList.addAll(set);
runningAppsAdapter=new AppsAdapter(RunningAppsActivity.this,R.layout.list_item,m_processesList);
m_listView.setAdapter(runningAppsAdapter);
runningAppsAdapter.notifyDataSetChanged();
}