Android Comparator not working in lollipop & below versions - android

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!

Related

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. :)

Custom Alphabetical sorted listview with sections

I want to make a Custom ListView with sorted alphabetical apps using section Indexer. Since Section Indexer only treat with ArrayList<String> so how do I write custom adapter that have section indexing functionality. Same like this:
Please suggest some solution.
Thats My code
class MyAZAdapter extends ArrayAdapter implements SectionIndexer {
ArrayList myElements;
HashMap azIndexer;
String[] sections;
List apps;
public MyAZAdapter(Context context, int textViewResourceId, List<T> objects, List<ApplicationInfo> apps) {
super(context, textViewResourceId, objects);
myElements = (ArrayList<String>) objects;
azIndexer = new HashMap<String, Integer>(); //stores the positions for the start of each letter
this.apps = apps;
int size = elements.size();
for (int i = size - 1; i >= 0; i--) {
String element = elements.get(i);
//We store the first letter of the word, and its index.
azIndexer.put(element.substring(0, 1), i);
}
Set<String> keys = azIndexer.keySet(); // set of letters
Iterator<String> it = keys.iterator();
ArrayList<String> keyList = new ArrayList<String>();
while (it.hasNext()) {
String key = it.next();
keyList.add(key);
}
Collections.sort(keyList);//sort the keylist
sections = new String[keyList.size()]; // simple conversion to array
keyList.toArray(sections);
}
public int getPositionForSection(int section) {
if (section == 35) {
return 0;
}
for (int i = 0; i < myElements.size(); i++) {
String l = myElements.get(i);
char firstChar = l.toUpperCase().charAt(0);
if (firstChar == section) {
return i;
}
}
return -1;
}
public int getSectionForPosition(int position) {
Log.v("getSectionForPosition", "called");
return 0;
}
public Object[] getSections() {
return sections; // to string will be called to display the letter
}
}class MyAZAdapter<T> extends ArrayAdapter<T> implements SectionIndexer {
ArrayList<String> myElements;
HashMap<String, Integer> azIndexer;
String[] sections;
List<ApplicationInfo> apps;
public MyAZAdapter(Context context, int textViewResourceId, List<T> objects, List<ApplicationInfo> apps) {
super(context, textViewResourceId, objects);
myElements = (ArrayList<String>) objects;
azIndexer = new HashMap<String, Integer>(); //stores the positions for the start of each letter
this.apps = apps;
int size = elements.size();
for (int i = size - 1; i >= 0; i--) {
String element = elements.get(i);
//We store the first letter of the word, and its index.
azIndexer.put(element.substring(0, 1), i);
}
Set<String> keys = azIndexer.keySet(); // set of letters
Iterator<String> it = keys.iterator();
ArrayList<String> keyList = new ArrayList<String>();
while (it.hasNext()) {
String key = it.next();
keyList.add(key);
}
Collections.sort(keyList);//sort the keylist
sections = new String[keyList.size()]; // simple conversion to array
keyList.toArray(sections);
}
public int getPositionForSection(int section) {
if (section == 35) {
return 0;
}
for (int i = 0; i < myElements.size(); i++) {
String l = myElements.get(i);
char firstChar = l.toUpperCase().charAt(0);
if (firstChar == section) {
return i;
}
}
return -1;
}
public int getSectionForPosition(int position) {
Log.v("getSectionForPosition", "called");
return 0;
}
public Object[] getSections() {
return sections; // to string will be called to display the letter
}
}
My AppsActivity code
elements = new ArrayList<String>();
List<ApplicationInfo> apps = getInstalledApplication(getActivity());
for (int i = 0; i < apps.size(); i++) {
elements.add(apps.get(i).loadLabel(getActivity().getPackageManager()).toString());
}
Collections.sort(elements,String.CASE_INSENSITIVE_ORDER); // Must be sorted!
// listview
myListView = (ListView) rootView.findViewById(R.id.myListView);
//myListView.setFastScrollEnabled(true);
MyAZAdapter<String> adapter = new MyAZAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
elements, apps);
myListView.setAdapter(adapter);
SideBar indexBar = (SideBar) rootView.findViewById(R.id.sideBar);
indexBar.setListView(myListView);
adapter.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object2.compareTo(object1);
};
});
you need the above code right before:
myListView.setAdapter(adapter);

Error in Dijkstra algorithm in android

I am implementing the 'Dijkstra algorithm' in Android for making an app for Metro Network.
When I click on the button to show the path, it stops the app.
I have explicitly defined the graph to store in array adj[][].
MetroRoute class
public class MetroRoute extends Activity implements OnClickListener{
EditText source, destination;
TextView Route;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.metroroute);
source = (EditText) findViewById(R.id.etSource);
destination = (EditText) findViewById(R.id.etDest);
button = (Button) findViewById(R.id.bGetroute);
Route = (TextView) findViewById(R.id.tvRoute);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count, i;
count = findpath(Integer.parseInt(source.getText().toString()), Integer.parseInt(destination.getText().toString()), path, sdist );
if(sdist!=0)
{
Route.setText("Shortest distance is : \n" + sdist);
Route.setText("Shortest Path is : ");
for( i=count;i>1;i--)
Route.setText(path[i] + " -> ");
Route.setText(path[i]);
}
else
Route.setText("There is no path from source to destination node\n");
}
int adj[][] = {{3,2,3,0,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int MAX = 10, TEMP = 0, PERM =1, INFINITY = 9999, path[], sdist=0, n=5 ;
private class Node {
int predecessor[];
int dist[]; /*minimum distance of node from source*/
int status[];
}
int findpath(int s,int d,int path[],int sdist)
{
Node state = new Node();
int i, min=0, count=0, current, newdist, u, v ;
sdist=0;
/* Make all nodes temporary */
for(i=1;i<=n;i++)
{
state.predecessor[i]=0;
state.dist[i] = INFINITY;
state.status[i] = TEMP;
}
/*Source node should be permanent*/
state.predecessor[s]=0;
state.dist[s] = 0;
state.status[s] = PERM;
/*Starting from source node until destination is found*/
current=s;
while(current!=d)
{
for(i=1;i<=n;i++)
{
/*Checks for adjacent temporary nodes */
if ( adj[current][i] > 0 && state.status[i] == TEMP )
{
newdist=state.dist[current] + adj[current][i];
/*Checks for Relabeling*/
if( newdist < state.dist[i] )
{
state.predecessor[i] = current;
state.dist[i] = newdist;
}
}
}
/*Search for temporary node with minimum distance make it current node*/
min=INFINITY;
current=0;
for(i=1;i<=n;i++)
{
if(state.status[i] == TEMP && state.dist[i] < min)
{
min = state.dist[i];
current=i;
}
}
if(current==0) /*If Source or Sink node is isolated*/
return 0;
state.status[current]=PERM;
}
/* Getting full path in array from destination to source */
while( current!=0 )
{
count++;
path[count]=current;
current=state.predecessor[current];
}
/*Getting distance from source to destination*/
for(i=count;i>1;i--)
{
u=path[i];
v=path[i-1];
sdist+= adj[u][v];
}
return (count) ;
}
}
The easiest way to find the problem is to use the console of the adk to see the exceptions thrown by the device. When you start your app from your IDE (Eclipse, Android Studio) in a virtual device, or even your smartphone, you will get logcat-messages, which will contain the exceptions like for example the NullPointerException. You will then find the lines where the exception is thrown and then you can do some further testing (like writing some values to the console (System.Out.println(...) or System.err.println(...)).
You can post your log so we can take a look at it.
You may want to use my Dijkstra-implementation, too:
public static ArrayList<Integer> dijkstra(Graph graph, Integer orig,
Integer dest, TreeMap<Integer, Integer> distance,
ArrayList<Integer> nodesLeft) throws Exception
{
Iterator<Integer> iterator = graph.getNodes().iterator();
Integer next;
TreeMap<Integer, ArrayList<Integer>> paths = new TreeMap<Integer, ArrayList<Integer>>();
while (iterator.hasNext()) {
next = iterator.next();
distance.put(next, -1);
paths.put(next, new ArrayList<Integer>());
}
distance.put(orig, 0);
nodesLeft.addAll(Collections.unmodifiableCollection(graph.getNodes()));
while (!nodesLeft.isEmpty()) {
int u = nodesLeft.get(0);
Collection<Integer> edgesOfU = graph.getEdges(u);
Iterator<Integer> itEdgesOfU = edgesOfU.iterator();
int nextEdge;
while (itEdgesOfU.hasNext()) {
nextEdge = itEdgesOfU.next();
if (nodesLeft.contains(nextEdge)) {
int distU = distance.get(u);
if ((distance.get(nextEdge) == -1)
|| (distU + 1) < distance.get(nextEdge)) {
distance.put(nextEdge, distU + 1);
ArrayList<Integer> tmpList = paths.get(nextEdge);
for (int a : paths.get(u)) {
tmpList.add(a);
}
tmpList.add(nextEdge);
}
}
}
nodesLeft.remove(0);
}
return paths.get(dest);
}
I used some self-defined Graphs with the following Interface:
import java.util.Collection;
public interface Graph {
public Integer addNode();
public void removeNode(Integer id) throws Exception,
UnsupportedOperationException;
public Collection<Integer> getNodes();
public boolean addEdge(Integer orig, Integer dest) throws Exception;
public boolean removeEdge(Integer orig, Integer dest) throws Exception,
UnsupportedOperationException;
public Collection<Integer> getEdges(Integer orig) throws Exception;
}

HashSet to ArrayList not Displaying in Listview

So this project is driving me insane. Thank you to Ahmed Aeon Axan for the last answer. I have never worked with HashTables before but from the all the code I've looked at this should be working. Please tell me why this is not displaying in my listview.
Created in the model.java below
public class Model implements Serializable {
public static final int END_MORNING = 11; // 11:00AM, inclusive
public static final int END_AFTERNOON = 16; // 4:00PM, inclusive
private GregorianCalendar startDate;
private ArrayList<GregorianCalendar> datesSmoked = new ArrayList<GregorianCalendar>();
private ArrayList<String> locationsSmoked = new ArrayList<String>();
private ArrayList<String> locations = new ArrayList<String>();
private ArrayList<String> allIncidents = new ArrayList<String>();
private Set<String> newLocArr = new HashSet<String>(locations);
private SimpleDateFormat sdf = new SimpleDateFormat("E, MMM dd");
private ArrayList<String> times = new ArrayList<String>();
public String [] defaultLocations = {"Home", "Work", "Commuting", "School", "Bar", "Restaurant", "Social Gathering", "Other"};
public String [] eachSmoked;
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
}
public Model(){
this(new GregorianCalendar()); // now
}
public ArrayList<String> getDates() {
for (int i = 0; i < datesSmoked.size(); i++) {
String s = (sdf.format(i));
times.add(s);
}
return times;
}
public List<String> getPlacesSmoked() {
for (String key : locations) {
newLocArr.add(key+ ": " + Collections.frequency(locationsSmoked, key));
}
return new ArrayList<String>(newLocArr);
}
public ArrayList<String> getAllIncidentsArray() {
for (int i = 0; i < datesSmoked.size(); i++) {
allIncidents.add(getDates().get(i) + ", " + locationsSmoked.get(i));
}
return allIncidents;
}
public ArrayList<String> getlocationsArray() {
return this.locations;
}
public ArrayList<String> getLocationsSmokedArray() {
return this.locationsSmoked;
}
public ArrayList<GregorianCalendar> getDatesSmokedArray() {
return this.datesSmoked;
}
Ends the relevant code for model.java
called into the list view in the Locations Activity below where it is not displaying
public class LocationActivity extends Activity {
public static final String SMOKIN_DATA_FILE = "smokin.dat";
public static Model model = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
restoreModel();
ListView listView = (ListView) findViewById(R.id.location_listview_Id);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, model.getPlacesSmoked());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
Essentially Im trying to get the ArrayList locationsSmoked which Displays
Home
Home
Home
Home
School
School
School
School
to display
Home: 4
School: 4
Your locTest list is empty, since it is initialized at the Model creation with empty HashSet test1 which is initialized with empty locations list.
The List(Collection<?>) constructor is copying the values, not the pointer to the collection, as far as I remember
fast solution (not sure if it do the trick actually):
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
// calling setPlacesSmoked to process data
setPlacesSmoked();
}
public void setPlacesSmoked() {
// assuming that locations list holds the data needed to process
for (String key : locations) {
test1.add(key+ ": " + Collections.frequency(locations, key));
}
}
public List<String> getPlacesSmoked() {
//return locTest;
return new ArrayList<String>(test1);
}
The expected output:
Home: 1
Work: 1
Commuting: 1
School: 1
Bar: 1
Restaurant: 1
Social Gathering: 1
Other: 1
But that depends on the locations contents

Sorting list in alphabetical order

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()

Categories

Resources