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++;
}
Related
I'm developing a recipe book and I'm implementing this method to insert my Recipe in the Database. In the for cycle I get the ingredient's name and quantity from multiples EditText, saving each of them in an Ingredient.class instance (newIngredient). Then I insert the instance into the DB and add it to an ArrayList. The followings "if conditions" are for the title, time and other Recipe's attributes. Finally, I also insert Recipe and Tag instances in the relatives DB's tables and I close DB.
public void saveRecipe() {
dbHelper = new DatabaseHelper(context);
// creating new recipe from user input
Ingredient newIngredient;
String title, childIngredient, instruction, tag;
int target, time, childQuantity, calories;
int countIngredients = parentIngredientLayout.getChildCount();
int countTags = chipGroup.getChildCount();
ArrayList<Ingredient> ingredients = null;
ArrayList<Tag> tags = null;
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;
// ingredients fields settings
for (int d=0; d<countIngredients; d++) {
childViewIng = parentIngredientLayout.getChildAt(d);
childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
//recipe fields settings
if (photoPath1 == null)
photoPath1 = "";
if (photoPath2 == null)
photoPath2 = "";
if (photoPath3 == null)
photoPath3 = "";
if (titleText.getText().toString().isEmpty()) {
title = "";
} else {
title = titleText.getText().toString();
}
if (targetNumber.getText().toString().isEmpty()) {
target = 0;
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
if (timeNumber.getText().toString().isEmpty()) {
time = 0;
} else {
time = Integer.parseInt(timeNumber.getText().toString());
}
if (instructionText.getText().toString().isEmpty()) {
instruction = "";
} else {
instruction = instructionText.getText().toString();
}
if (caloriesNumber.getText().toString().isEmpty()) {
calories = 0;
} else {
calories = Integer.parseInt(caloriesNumber.getText().toString());
}
if (tagName.getText().toString().isEmpty()) {
tag = "";
} else {
tag = tagName.getText().toString();
}
Recipe newRecipe = new Recipe(title, photoPath1, photoPath2, photoPath3, instruction, target, time, calories, ingredients);
Tag newTag = new Tag(tag);
dbHelper.insertRecipe(newRecipe);
dbHelper.insertTag(newTag);
dbHelper.close(); }
I found out by debugging that in this case is inserted only the first ingredient. I tried to move the FOR until the end of code, but in that case, are inserted both recipe and tag and always only the first ingredient. I think the problem is relative to the opening/closing of the DB. Can somebody help me?
Ingredient constructor:
public Ingredient(String ingredient_name, int quantity) {
this.ingredient_name = ingredient_name;
this.quantity = quantity;
}
dbHelper.insertIngredient(newIngredient) method:
public boolean insertIngredient(Ingredient ingredient) {
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INGREDIENT_NAME, ingredient.getIngredient_name());
contentValues.put(QUANTITY, ingredient.getQuantity());
contentValues.put(KEY_CREATED_AT, time.getTime().toString());
long result = db.insert(TBL_INGREDIENTS, null, contentValues);
//db.close();
Log.e(TAG, "Ingredient inserted!");
if (result == -1) {
return false;
} else {
return true;
}
}
Ok, thanks to your comment we got the problem :)
You are calling .add(newIngredient) on a list that you initialized with ArrayList<Ingredient> ingredients = null;
Change it to
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
and it will work :)
Good luck!
I have an ArrayList with one String value and two Integer values. I want the sum of integers under the same String value. For example
aaa , 1 , 2
aaa , 2 , 1
bbb , 1 , 2
ccc , 3 , 3
ccc , 1 , 2
ccc , 2 , 2
So final list should come as
aaa , 3, 3
bbb , 1, 2
ccc , 6, 7
I was able to get the sum using one String and one Integer.
this is what i used for one String and one Integer.
ArrayList<InvoiceData> invoiceHeaderList = new ArrayList<>();
invoiceHeaderList.clear();
Map<String, Integer> sumMap = new TreeMap<String, Integer>();
for (ItemData dashboardOneData : invoiceList) {
String key = dashboardOneData.getInvoiceNo() + "#" + dashboardOneData.getInvoiceDate();
if (sumMap.containsKey(key)) {
int sum = sumMap.get(key);
sum += dashboardOneData.getMatQty();
sumMap.put(key, sum);
} else {
sumMap.put(key, dashboardOneData.getMatQty());
}
}
for (Map.Entry<String, Integer> e : sumMap.entrySet()) {
String[] splitInvoice;
InvoiceData invTempData = new InvoiceData();
if (e.getKey() != null || !e.getKey().equals("")) {
splitInvoice = e.getKey().split("#+");
invTempData.setInvoiceNo(splitInvoice[0]);
invTempData.setInvoiceDate(splitInvoice[1]);
invTempData.setInvoiceQty(e.getValue());
invoiceHeaderList.add(invTempData);
}
}
I tried to do as below but no luck, I was not able to take the sum of the two integers inside the method.
public class QuantityData {
private int oriQty;
private int newQty;
public QuantityData() {
}
}
Method....
ArrayList<InvoiceData> invoiceHeaderList = new ArrayList<>();
invoiceHeaderList.clear();
Map<String, List<QuantityData>> sumMap = new TreeMap<String, List<QuantityData>>();
for (ItemData dashboardOneData : invoiceList) {
String key = dashboardOneData.getInvoiceNo() + "#" + dashboardOneData.getInvoiceDate();
QuantityData qtyData = new QuantityData();
if (sumMap.containsKey(key)) {
ArrayList<QuantityData> qtyArrayList = new ArrayList<>();
qtyArrayList.add(qtyData);
sumMap.put(key, qtyArrayList);
} else {
ArrayList<QuantityData> qtyArrayList = new ArrayList<>();
qtyData.setOriQty(dashboardOneData.getMatQty());
qtyData.setNewQty(dashboardOneData.getNewMatQty());
qtyArrayList.add(qtyData);
sumMap.put(key, qtyArrayList);
}
}
for (Map.Entry<String, List<QuantityData>> e : sumMap.entrySet()) {
String[] splitInvoice;
InvoiceData invTempData = new InvoiceData();
if (e.getKey() != null || !e.getKey().equals("")) {
}
}
If I understood your goal correctly, you don't need ArrayLists at all.
Have you tried something like this?
Map<String, QuantityData> sumMap = new TreeMap<String, QuantityData>();
QuantityData qtyData;
for (ItemData dashboardOneData : invoiceList) {
String key = dashboardOneData.getInvoiceNo() + "#" + dashboardOneData.getInvoiceDate();
if (sumMap.containsKey(key)) {
qtyData = sumMap.get(key)
qtyData.setOriQty(qtyData.getOriQty() + dashboardOneData.getMatQty());
qtyData.setNewQty(qtyData.getNewQty() + dashboardOneData.getNewQty());
} else {
qtyData = new QuantityData();
qtyData.setOriQty(dashboardOneData.getMatQty());
qtyData.setNewQty(dashboardOneData.getNewMatQty());
}
sumMap.put(key, qtyData);
}
I don't entirely understand what your input data structure looks like, but I'll do my best.
Let's say you have an input data structure that looks something like this:
#Data //using Lombok #Data annotation
class Data{
String key;
Integer[] values;
}
then you can do something like this:
Map<String, Integer[]> getSummedDataByKey(List<Data> items){
Map<String, Integer[]> summedData;
for (Data d : items){
if (!summedData.contains(d.getKey())){
summedData.put(d.getKey(), d.getValues());
}else{
Integer[] oldValues = summedData.get(d.getKey());
for (int i = 0; i < oldValues.length; i++){
oldValues[i] += d.getValues()[i];
}
summedData.put(d.getKey(), oldvalues);
}
}
return summedData;
}
this is what I figured out.
for (ItemData dashboardOneData : invoiceList) {
String key = dashboardOneData.getInvoiceNo() + "#" + dashboardOneData.getInvoiceDate();
QuantityData qtyData = new QuantityData();
if (sumMap.containsKey(key)) {
ArrayList<QuantityData> qtyArrayList = new ArrayList<>();
List<QuantityData> bobs = sumMap.get(key);
int sum1 = bobs.get(0).getOriQty();
int sum2 = bobs.get(0).getNewQty();
sum1 += dashboardOneData.getMatQty();
sum2 += dashboardOneData.getNewMatQty();
qtyData.setOriQty(sum1);
qtyData.setNewQty(sum2);
qtyArrayList.add(qtyData);
sumMap.put(key, qtyArrayList);
} else {
ArrayList<QuantityData> qtyArrayList = new ArrayList<>();
qtyData.setOriQty(dashboardOneData.getMatQty());
qtyData.setNewQty(dashboardOneData.getNewMatQty());
qtyArrayList.add(qtyData);
sumMap.put(key, qtyArrayList);
}
}
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);
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. :)
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]);
}