Sorting list in alphabetical order - android

Im working on an application where I create a list with the installed apps and let the user select one. I've got everything working except for one thing; ordering them in alphabetical order. Here's the code I'm using:
private List<App> loadInstalledApps(boolean includeSysApps) {
List<App> apps = new ArrayList<App>();
PackageManager packageManager = getPackageManager();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for(int i=0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
App app = new App();
app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
app.setPackageName(p.packageName);
app.setVersionName(p.versionName);
app.setVersionCode(p.versionCode);
CharSequence description = p.applicationInfo.loadDescription(packageManager);
app.setDescription(description != null ? description.toString() : "");
apps.add(app);
}
return apps;
}
Any help is appreciated!

Use Comparator to sort data ...
Collections.sort(apps, new Comparator<App>() {
#Override
public int compare(App lhs, App rhs) {
//here getTitle() method return app name...
return lhs.getTitle().compareTo(rhs.getTitle());
}
});

First: create comparator
Public class App implements Comparable {
// Lista de atributos y métodos
public int compareTo(Object o) {
// logic of comparation
return result; //must be integer
}
}
For example:
public int compareTo(Object o) {
Direccion dir = (Direccion)o;
if(this.name < app.getName())
return -1;
else if(this.name == app.getName())
return 0;
else
return 1;
}
And when you want to short, use Collections.short(list)

Simpliest solution
Collections.sort(familleList, (famille, t1) -> famille.compareTo(t1));

In Kotlin using lambda expression and comparator. you can easily sort your list alphabetically.
yourList.sortWith(Comparator { obj1, obj2 ->
obj1.name.compareTo(obj2?.name!!, ignoreCase = true)
})
Note: Here obj1 and obj2 is Model object of your list. e.g
val yourList: MutableList<Model> = ArrayList()

Related

How do I sort my listview items alphabetically?

I have a listview, which I would like to sort in an alphabetic order. How do I do that?
public class AppDrawer extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_drawer);
ListView userInstalledApps = (ListView) findViewById(R.id.installed_app_list);
List<AppList> installedApps = getInstalledApps();
AppAdapter installedAppAdapter = new AppAdapter(this, installedApps);
userInstalledApps.setAdapter(installedAppAdapter);
}
private List<AppList> getInstalledApps() {
List<AppList> res = new ArrayList<AppList>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((isSystemPackage(p) == false)) {
String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(new AppList(appName, icon));
}
}
return res;
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true : false;
}
You can use comparator for sorting your list. change your getInstalledApps() method as below.
private List<AppList> getInstalledApps() {
List<AppList> res = new ArrayList<AppList>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((isSystemPackage(p) == false)) {
String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(new AppList(appName, icon));
}
}
Collections.sort(res, new Comparator<AppList>() {
#Override
public int compare(AppList o1, AppList o2) {
return o1.getAppName().compareTo(o2.getAppName()); // use your getter for getting app name you are setting.
}
});
return res;
}
You can use Comparator for sorting a list.
List<AppList> installedApps = getInstalledApps();
Collections.sort(installedApps , new Comparator<AppList>() {
public int compare(AppList v1, AppList v2) {
return v1.getAppName().compareTo(v2.getAppName());
}
});
Or if you are using Java 8:
list.sort(String::compareToIgnoreCase);
sort method of List interface is mutable operation. Your list will be modified and order property of List will be corrupted better to use Streams of Java 8
List.stream().sorted().collect(Collectors.toList());
pass your Comparator in sorted method and get the list.

Android Comparator not working in lollipop & below versions

Am using following Camparator to sort the items in adapter binded to given listview;
public static Comparator<HashMap<String, String>> StringAscComparator = new Comparator<HashMap<String, String>>() {
//int index;
#Override
public int compare(HashMap<String, String> app1, HashMap<String, String> app2) {
Float stringName1 = Float.parseFloat(app1.get(KEY_RATE).trim());
Float stringName2 = Float.parseFloat(app2.get(KEY_RATE).trim());
//index++;
Log.d("comapare_tag","str1: "+stringName1+" str2: "+stringName2);
if ( stringName1 > stringName2 ) {
return 1;
} else if ( stringName1 < stringName2 ) {
return -1;
} else {
return 0;
}
//return Float.compare(stringName1,stringName2);
}
};
This how i invoked it:
Collections.sort(hotelList,StringAscComparator);
but the above code properly sorts(in descending order,highest first!) all the items in livestview in version 6.0, but below that, I have tested it on lollipop,kitkat & on jellybean; it's not working, what am doing wrong in above code, or is there any other conventional way of doing this, please help.
Thanx!

Sort two dependent string arrays

I Have two String arrays in my application, One containing Country names, and other containing corresponding extension code, But the issue is that the names of countries are not properly ordered in alphabetical order,
public static final String[] m_Countries = {
"---select---", "Andorra", ...., "Zimbabwe"};
public static final String[] m_Codes = {
"0", "376",...., "263"};
These are the arrays,
So my question is, is there any way to sort the first array such that the second array also changes to corresponding position without writing my own code?
If not, what's the best sort method i can use for these arrays?
Any kind of help will be greatly appreciated.
Form TreeMap from your array and all your data get sort. After that fill your respective array with Key and Values.
TreeMap<String, String> map = new TreeMap<>();
int length = m_Countries.length;
for(int i=0;i<length;i++){
map.put(m_Countries[i], m_Codes[i]);
}
String[] countries = map.keySet().toArray(new String[map.keySet().size()]);
System.out.println("Country:"+Arrays.toString(countries));
String[] codes = map.values().toArray(new String[map.values().size()]);
System.out.println("Codes:"+Arrays.toString(codes));
Result:
Country:[---select---, Afghanistan, ..., Zimbabwe]
Codes:[0, 93,.... , 263]
Method 1.
You can create a hashMap to store the original country to code.
private void handle(String[] m_Countries, String[] m_Codes, Map<String, String> map) {
if (m_Codes == null || m_Countries == null || map == null) {
return;
}
//
final int codeCount = m_Codes.length;
final int countryCount = m_Countries.length;
final int count = Math.min(codeCount, countryCount);
for (int i = 0; i < count; i++) {
map.put(m_Countries[i], m_Codes[i]);
}
// TODO sort
// get code by country name by map.get(country)
}
Method 2.
You can make a List of pairs which contains country and code. Then sort the list.
private List<Pair<String, String>> sortCountryWithCode(String[] m_Countries, String[] m_Codes) {
if (m_Codes == null || m_Countries == null) {
return null;
}
//
final int codeCount = m_Codes.length;
final int countryCount = m_Countries.length;
final int count = Math.min(codeCount, countryCount);
if (count == 0) {
return null;
}
// generate a list
List<Pair<String, String>> list = new ArrayList<>();
for (int i = 0; i < count; i++) {
list.add(new Pair<String, String>(m_Countries[i], m_Codes[i]));
}
// sort
Collections.sort(list, new Comparator<Pair<String, String>>() {
#Override
public int compare(Pair<String, String> lhs, Pair<String, String> rhs) {
return lhs.first.compareToIgnoreCase(rhs.first);
}
});
return list;
}
code with love. :)

Android ArrayList compare

Hi guys i got 2 ArrayList based on same class. I have to add from arraylist1 to arraylist2 non exist(s)ing rows. I tried to use contains but its always returning false. What i m doing wrong ? Ty
MyClass
public class HataKoduBean {
private String Oid;
private String Name;
private String Surname;
}
How i define Arraylists
Arraylist<MyClass> array1 = new Arraylist<>();
Arraylist<MyClass> array2 = new Arraylist<>();
How i tried to compare ?
for (int ii = 0; ii < array1.size(); ii++) {
if (!array2.contains(array1.get(ii)))
array2.add(array1.get(ii));
}
First you have to implement equals() and hashCode() in your custom class.
Consider to use Sets, so you can merge collections in one line with addAll().
First you have to implement equals() and hashCode() in your custom object
and create loop and compare between object by using equals method like this.
implement equals and hashCode:
`#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
HataKoduBean o = (HataKoduBean) o;
return Oid != null?Oid.equals(HataKoduBean.Oid):HataKoduBean.Oid== null;
}
#Override
public int hashCode() {
return Oid != null ? Oid.hashCode() : 0;
}`
compare Objects:
for (int ii = 0; ii < array1.size(); ii++) {
if (!array2.get(ii).equals(array1.get(ii)))
array2.add(array1.get(ii));
}

this is my code which show all install application

This is my source code below which shows all installed system applications. I want to show only selected applications like only 5 applications which name I provite not show all applications what do I do?? please help me
public class ListInstalledApps extends Activity implements OnItemClickListener {
/* whether or not to include system apps */
private static final boolean INCLUDE_SYSTEM_APPS = false;
private ListView mAppsList;
private AppListAdapter mAdapter;
private List<App> mApps;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAppsList = (ListView) findViewById(R.id.appslist);
mAppsList.setOnItemClickListener(this);
mApps = loadInstalledApps(INCLUDE_SYSTEM_APPS);
mAdapter = new AppListAdapter(getApplicationContext());
mAdapter.setListItems(mApps);
mAppsList.setAdapter(mAdapter);
new LoadIconsTask().execute(mApps.toArray(new App[]{}));
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final App app = (App) parent.getItemAtPosition(position);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String msg = app.getTitle() + "\n\n" +
"Version " + app.getVersionName() + " (" +
app.getVersionCode() + ")" +
(app.getDescription() != null ? ("\n\n" + app.getDescription()) : "");
builder.setMessage(msg)
.setCancelable(true)
.setTitle(app.getTitle())
.setIcon(mAdapter.getIcons().get(app.getPackageName()))
.setPositiveButton("Launch", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// start the app by invoking its launch intent
Intent i = getPackageManager().getLaunchIntentForPackage(app.getPackageName());
try {
if (i != null) {
startActivity(i);
} else {
i = new Intent(app.getPackageName());
startActivity(i);
}
} catch (ActivityNotFoundException err) {
Toast.makeText(ListInstalledApps.this, "Error launching app",
Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* Uses the package manager to query for all currently installed apps which are put
into beans and returned
* in form of a list.
*
* #param includeSysApps whether or not to include system applications
* #return a list containing an {#code App} bean for each installed application
*/
private List<App> loadInstalledApps(boolean includeSysApps) {
List<App> apps = new ArrayList<App>();
// the package manager contains the information about all installed apps
PackageManager packageManager = getPackageManager();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
//PackageManager.GET_META_DATA
for(int i=0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
ApplicationInfo a = p.applicationInfo;
// skip system apps if they shall not be included
if ((!includeSysApps) && ((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1)) {
continue;
}
App app = new App();
app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
app.setPackageName(p.packageName);
app.setVersionName(p.versionName);
app.setVersionCode(p.versionCode);
CharSequence description = p.applicationInfo.loadDescription(packageManager);
app.setDescription(description != null ? description.toString() : "");
apps.add(app);
}
return apps;
}
/**
* An asynchronous task to load the icons of the installed applications.
*/
private class LoadIconsTask extends AsyncTask<App, Void, Void> {
#Override
protected Void doInBackground(App... apps) {
Map<String, Drawable> icons = new HashMap<String, Drawable>();
PackageManager manager = getApplicationContext().getPackageManager();
for (App app : apps) {
String pkgName = app.getPackageName();
Drawable ico = null;
try {
Intent i = manager.getLaunchIntentForPackage(pkgName);
if (i != null) {
ico = manager.getActivityIcon(i);
}
} catch (NameNotFoundException e) {
Log.e("ERROR", "Unable to find icon for package '" + pkgName + "': " +
e.getMessage());
}
icons.put(app.getPackageName(), ico);
}
mAdapter.setIcons(icons);
return null;
}
#Override
protected void onPostExecute(Void result) {
mAdapter.notifyDataSetChanged();
}
}
}
try this -
provide the package_name of application you want to show
and compare it with package name present in device
//for browser application given package name as com.android.browser
for (int i = 0; i < packs.size(); i++) {
if ((p.packageName).equals("com.android.browser")) {
App app = new App();
app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
app.setPackageName(p.packageName);
app.setVersionName(p.versionName);
app.setVersionCode(p.versionCode);
CharSequence description = p.applicationInfo.loadDescription(packageManager);
app.setDescription(description != null ? description.toString() : "");
apps.add(app);
}
}
hope this will help you.
You need a screening process to see if the application is in the list of your mentioned applications store your entered app package name in array and see if the current app is in that list if it is there add it to the list and then display listView using this list
private List<App> loadInstalledApps(boolean includeSysApps) {
List<App> apps = new ArrayList<App>();
// the package manager contains the information about all installed apps
PackageManager packageManager = getPackageManager();
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
//PackageManager.GET_META_DATA
for(int i=0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
ApplicationInfo a = p.applicationInfo;
// skip system apps if they shall not be included
if ((!includeSysApps) && ((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1)) {
continue;
}
App app = new App();
app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
app.setPackageName(p.packageName);
app.setVersionName(p.versionName);
app.setVersionCode(p.versionCode);
CharSequence description = p.applicationInfo.loadDescription(packageManager);
app.setDescription(description != null ? description.toString() : "");
if( Arrays.asList(appliation1.packageName,appliation2.packageName,appliation3.packageName).contains(p.packageName) )
apps.add(app);
}
return apps;
}

Categories

Resources