Sort two dependent string arrays - android

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

Related

Sort ListView Items

I have 2 item types in my listview, Venue and Distance.
List<String> ls_Distance;
List<String> ls_Venue;
ls_Distance = new ArrayList<String>();
ls_Venue = new ArrayList<String>();
I'm adding string items into both list arrays in a for loop.
(I'm assuming sort function can sort a list of numbers that are in string format e.g. "9","15","20" etc.. and I don't need to covert to int first?)
ls_Distance.add(data_Distance);
ls_Venue.add(data_Venue);
I would like to sort the items by distance (showing lowest distance first), and maintain the index of the venue.
Note: This sorting can only be done once data is added to array and not before (distance obtained from location updates calculations)
Then I want to set my listview adpater after sorting:
ListViewRowCount = ls_Venue.size();
lv.setAdapter(lv_custom_adapter);
EDIT:
My code for sorting (not working)
private void sortByDistance() {
Collections.sort(ls_Distance, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
Log.v("TAG", "zzz_compare_lhs: " +lhs);
Log.v("TAG", "zzz_compare_rhs: " +rhs);
return lhs.compareTo(rhs);
}
});
//setAdapter();
}
Resolved: (Using TreeMap)
private void consolidateData() {
if (currentLat != 0.0){
Map<Integer, String> map = new TreeMap<Integer, String>();
for (int i=0;i<stringArr_markerVenue.size();i++){
data_Distance = Integer.parseInt(stringArr_markerDistance.get(i));
data_Venue = stringArr_markerVenue.get(i);
//ls_Distance.add(data_Distance);
//ls_Venue.add(data_Venue);
map.put(data_Distance, data_Venue);
}
TreeMap<Integer, String> sorted = new TreeMap<>(map);
Set<Map.Entry<Integer, String>> mappings = sorted.entrySet();
System.out.println("HashMap after sorting by keys in ascending order ");
for(Map.Entry<Integer, String> mapping : mappings){
System.out.println(mapping.getKey() + " ==> " + mapping.getValue());
int data_Distance = mapping.getKey();
String data_Venue = mapping.getValue();
Log.v("TAG", "zzz_com: " + data_Distance + " ==> " + data_Venue);
ls_Distance.add(data_Distance+"");
ls_Venue.add(data_Venue);
}
setAdapter();
}
}
private void setAdapter() {
ListViewRowCount = ls_Distance.size();
lv.setAdapter(lv_custom_adapter);
}

Assign Integer Value to String

I am developing an app in which i have to assign integer values to different string of words. For Example I want to assign:
John = 2
Good = 3
Person= 7
Now these John, Good and person are strings while 2,3 and 7 are int values. But I am so confused about how to implement that. I read many things about how to convert int to string and string to int but this is different case.
I am giving option to user to enter a text in editText and if for example User enters "Hello John you are a good person" then this line output will be 12 as all the three words John, Good and person are there in the input text. Can you tell me how to achieve that?
I am stuck here is my little code:
String s = "John";
int s_value= 2;
now I want to assign this 2 to John so that whenever user give input and it contains John then the value 2 is shown for John. Please Help as I am just a beginner level programmer
Here is my code (Edited)
String input = "John good person Man";
Map<String, Integer> map = new HashMap<>();
map.put("John", 2);
map.put("Good", 3);
map.put("Person", 7);
//int number = map.get("Good");
String[] words = input.split(" ");
ArrayList<String> wordsList = new ArrayList<String>();
for(String word : words)
{
wordsList.add(word);
}
for (int ii = 0; ii < wordsList.size(); ii++) {
// get the item as string
for (int j = 0; j < stopwords.length; j++) {
if (wordsList.contains(stopwords[j])) {
wordsList.remove(stopwords[j]);//remove it
}
}
}
for (String str : wordsList) {
Log.e("msg", str + " ");
}
As u see i applied code of you and then i want to split my main string so that each word of that string compares with the strings that are in the Map<>. Now i am confused what to write in the for loop ( 'stopwords' will be replaced by what thing?)
You can use a Map<String, Integer> to map words to numbers:
Map<String, Integer> map = new HashMap<>();
map.put("John", 2);
map.put("Good", 3);
map.put("Person", 7);
and then query the number given a word:
int number = map.get("John"); // will return 2
UPDATE
The following code iterates over a collection of words and adds up the values that the words match to:
List<String> words = getWords();
int total = 0;
for (String word : words) {
Integer value = map.get(word);
if (value != null) {
total += value;
}
}
return total;
I would use a Dictionary for this. You can add a string and an int (or anything else actually) value for that string.
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("John", 2);
d.Add("Good", 3);
d.Add("Person", 7);
You can use String contains to achieve this. Following is the code:
String input = "John you are a good person";
String s1 = "John";
String s2 = "good";
String s3 = "person";
int totScore =0;
if(input.contains(s1)) {
totScore=totScore+2;
}
else if (input.contains(s2)) {
totScore=totScore+3;
}
else if (input.contains(s3)) {
totScore=totScore+7;
}
System.out.print(totScore);
You can use class like.
class Word{
String wordName;
int value;
public Word(String wordName, int value){
this.wordName = wordName;
this.value = value;
}
// getter
public String getWordName(){
return this.wordName;
}
public int getValue(){
return this.value;
}
// setter
public void setWordName(String wordName){
this.wordName = wordName;
}
public void zetValue(int value){
this.value = value;
}
}
You can create an object of the word
Word person = new Word("Person",3);

Distinct value in Parse.com

I am retrieving a list of cities in Parse.
mMidwifeLocation = users;
String[] locations = new String[mMidwifeLocation.size()];
int i = 0;
for(ParseUser user : mMidwifeLocation) {
locations[i] = user.getString("city");
i++;
}
Within this, I want distinct values, and no null values.. Can someone give me an assist on how to do this?
Well this should be good.
If not to long, not that inefficeint.
mMidwifeLocation = users;
String[] locations = new String[mMidwifeLocation.size()];
String check;
int i = 0;
for(ParseUser user : mMidwifeLocation) {
check=user.getString("city");
if(check!=null){
if(!Arrays.asList(locations).contains(check)){
locations[i] = user.getString("city");
}
}
i++;
}

How to sort numbers in TextViews and display them?

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

Updating values to Hash-table?

I have some problem in updating the values to hash-table,here is my problem i will explain it clearly.
1.I have getting the response from server,i am adding the values to layout,by using layout Layout-Inflater.
2.in our application we have streaming request.when the streaming request is turned on the values need to be updated regularly.
storing values in hash-tables
Hashtable<String, View> indicesHashtable = new Hashtable<String, View>();
For(Step 1)code i have written belowthe code.
private void addIndices(LinearLayout parent, final String key,final String value) {
LayoutInflater factory = LayoutInflater.from(mContext);
final View row = factory.inflate(R.layout.indices_values, null);
final TextView keyTextView = (TextView) row.findViewById(R.id.txtCompany);
final TextView valueTextView = (TextView) row.findViewById(R.id.txtIndex);
final Button iconImageView = (Button) row.findViewById(R.id.btnIcon);
row.setBackgroundResource(android.R.drawable.list_selector_background);
if (value.length() > 0) {
keyTextView.setText(Html.fromHtml("<b>"+indices.get(key)+"</b>"));
valueTextView.setText(Html.fromHtml(value));
if(quoteArrowIconId != -1)
iconImageView.setBackgroundResource(quoteArrowIconId);
else
iconImageView.setBackgroundDrawable(null);
}else{
keyTextView.setText(Html.fromHtml(key));
}
indicesHashtable.put(key, row);
parent.addView(row);
}
For(Step 2)i need help from you guys.
i have written code..that i have shown below.
private void handleResponseOfResponses(ResponseParser response) {
Hashtable responses = (Hashtable) response.getValue(Response_890.RESPONSES);
String[] symbols = new String[responses.size()];
int index = 0;
indicesHashtable.clear();
for(int i =indicesSymbols.length-1; i >= 0; i--){
Enumeration e = responses.keys();
while (e.hasMoreElements()) {
ResponseParser subResponse = (ResponseParser) responses.get(e.nextElement());
if (subResponse.getResponseCode() == ResponseCodes.QUOTES_RESPONSE) {
String[] quoteProperties = (String[]) subResponse.getValue(Response_312.QUOTES_KEY);
if(quoteProperties[0].equalsIgnoreCase(indicesSymbols[i])){
// symbolTable.put(quoteProperties[0].toUpperCase(), index);
symbols[index++] = quoteProperties[0];
String value = quoteValue(quoteProperties);
For displaying the values coming for response i have added (AddIndices)method
addIndices(linear_Indices, quoteProperties[0], value);
}
}
}
}
autoscroll();
indicesStreamerClient = new StreamerClient(indicesSymbols){
#Override
public void onStreamDataReceived(QuoteData quoteData) {
System.out.println("onStreamDataReceived () -> "+quoteData.getSymbol());
HERE I NEED TO ADDED ANOTHER METHOD FOR UPDATING THE VALUES..HOW I CAN WRITE THE CODE.
};
};
Streamer.getInstance(mContext).registerStramerClient(indicesStreamerClient);
}
Guys i am fresher as well as new to andriod.
Thanks in advance!!!!!!

Categories

Resources