I have been working on this problem for about five hours, implementing many different ways to achieve this goal, but nothing seems to be working. I am at the point to where I can't even think straight any more, so I am posting this here.
I have a shared preference which retrieves a string. that string is converted into a string array. I have a 2d array with four arrays set to the index. I want to loop through the 2d array and compare my string array to it. If the contents of each 2d array index are found in my string array, print true, else, false.
final SharedPreferences sharedPref = CocktailsFrag.this.getActivity().getPreferences(Activity.MODE_PRIVATE);
//recall stored ingredients
String arrayString = sharedPref.getString("myIngredients", null);
if(arrayString ==null) {
//do nothing
} else {
String str1 = arrayString.replace("[", "");
String str2 = str1.replace("]", "");
String[] strValues = str2.split(",");
String drink1[] = {"Ale", "Brandy"};
String drink2[] = {"Vodka", "Tobasco Sauce"};
String drink3[] = {"Lager", "Stout"};
String drink4[] = {"Guiness", "Champagne"};
String[][] arrays = {drink1, drink2, drink3, drink4};
for(int i=0; i<arrays.length-1;i++) {
String[] indexValue = arrays[i];
if(strValues[i].contains(indexValue[i])) {
Toast.makeText(getActivity().getApplicationContext(), indexValue[i]+ "", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
}
Any thoughts on how to achieve this?
This code is not as efficient as simply iterating over the arrays but it doesn't matter with the number of elements and it is easier to read.
final SharedPreferences sharedPref = CocktailsFrag.this.getActivity().getPreferences(Activity.MODE_PRIVATE);
//recall stored ingredients
String arrayString = sharedPref.getString("myIngredients", null);
if(arrayString ==null) {
//do nothing
} else {
String str1 = arrayString.replace("[", "").replace("]", "");
List<String> strValues2 = Arrays.asList(str1.split(","));
String drink1[] = {"Ale", "Brandy"};
String drink2[] = {"Vodka", "Tobasco Sauce"};
String drink3[] = {"Lager", "Stout"};
String drink4[] = {"Guiness", "Champagne"};
String[][] arrays = {drink1, drink2, drink3, drink4};
for(String[] drinkArr : arrays){
if(strValues2.containsAll(Arrays.asList(drinkArr))) {
Toast.makeText(getActivity().getApplicationContext(), "true", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
}
If you wanted to do this using arrays only one option is the following.
for(String[] drinkArr : arrays) {
boolean allDrinksFound = true;
for(int i = 0; i < drinkArr.length; i++) {
boolean drinkFound = false;
for(int j = 0; j < strValues.length; j++) {
if(drinkArr[i].equals(strValues[j])) {
drinkFound = true;
break;
}
}
allDrinksFound = allDrinksFound && drinkFound;
}
if(allDrinksFound) {
Toast.makeText(getActivity().getApplicationContext(), "true", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
Related
I m using this framework, I already trying many times for making this problem, but I cant do it. I already asking on stackoverflow but no one cant help me. Actually I m tried.
I m using this framework : https://github.com/kikoso/Swipeable-Cards
And I m using SimpleCardStackAdapter like this :
for (int i = 0; i < user.length(); i++) {
final JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
// adapter.add(new CardModel(name, email, image1));
//Set JSON Data in TextView
Log.i("image1image1image1image1", image1);
// CardModel cardModel = new CardModel(" cardModel", " CardModel", r.getDrawable(R.drawable.picture1));
card = new CardModel(name, email, image1);
card.setOnClickListener(new CardModel.OnClickListener() {
#Override
public void OnClickListener() {
Log.i("Swipeable Cards", "I am pressing the card");
// Intent no = new Intent(HomeListview.this, YayDetailActivity.class);
/// startActivity(no);
}
});
card.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
#Override
public void onLike(CardModel card) {
Log.i("Swipeable Cards", "I dislike the card");
}
#Override
public void onDislike(CardModel card) {
Log.i("Swipeable Cards", "I like the card");
// new sendNewYay().execute(sharedToken, card.getTitle());
Toast.makeText(getApplicationContext(), card.getDescription(), Toast.LENGTH_SHORT).show();
}
});
// I m added adapter
adapter.add(card);
mCardContainer.setAdapter(adapter);
}
At the onDislike method, I need to get item name.
in this line : new sendNewYay().execute(sharedToken, name);
I send the item name, But it dont work.
1.How can I get the item name, in this method?
2.I have two button, one of them for onLike method, another one for onDislike Method. Ho can I triggered this two method with my button?
Thank you.
Decleare two variable global as string
String itemname;
try {
JSONArray c = new JSONArray(user.toString());
for (int i = 0 ; i < c.length();i++) {
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
System.out.println("Position : " + "" + i + ""+ c.getString(i));
itemname = name.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Final itemname is " + itemname);
So, I have at this point a collections.sort of java values as you can see
and I have two keys that are integers (let's say for the sake of the example that the values of tipo are 1,2 and the values of id are 3 and 4) and I want to sort the result of theyr multiplication:
Something like this:
valA = a.get(KEY_ONE)*a.get(KEY_TWO);
valB = b.get(KEY_ONE)*b.get(KEY_TWO);
Then compare them.
How can I do it??
here is the code that I have at this point.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
private static final String KEY_ONE = "tipo";
private static final String Key_TWO = "id";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_ONE.toString());
valB = (String) b.get(KEY_ONE.toString());
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
tvJson.setText(sortedJsonArray.toString());
}
}
Thanks in advance !
JSON is only displaying the last object '100 g' of "serving_description" in the JSON Formatted Data, See below. instead of all of the "serving_description" objects.
The Array is serving
If you look at the JSON Formatted Data below you will see that there are multiple "serving_description" 's.
I am trying to get the "serving_description" of all of the the available options to display instead of the last object in which it is displaying. How do I display all of the "serving_descriptions"?
I believe the error lies in, but I can be wrong, that is why I am asking :
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
Class, AsyncTask
#Override
public void onClick(View v) {
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... arg0) {
search = (EditText) findViewById(R.id.editText1);
String SEARCH = search.getText().toString();
JSONObject food = getFood(SEARCH);
Log.v("FATSEC", "TEST");
String ret = "";
try {
JSONArray foodName = food.getJSONObject("food")
.getJSONObject("servings")
.getJSONArray("serving");
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object
.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
} catch (JSONException e) {
e.printStackTrace();
}
return ret;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// ans.setText("# of Servings: " + result);
ans.setText("Servings: " + result);
}
}.execute();
}
});
Formatted JSON DATA
{
"servings":{
"serving":[
{
"vitamin_a":"0",
"calcium":"2",
"serving_description":"1 cup cooked",
"vitamin_c":"0",
"carbohydrate":"44.08",
"metric_serving_unit":"g",
"fat":"0.44",
"sodium":"577",
"polyunsaturated_fat":"0.119",
"fiber":"0.6",
"cholesterol":"0",
"iron":"10",
"serving_id":"16834",
"protein":"4.20",
"monounsaturated_fat":"0.138",
"potassium":"55",
"number_of_units":"1.000",
"calories":"204",
"measurement_description":"cup, cooked",
"saturated_fat":"0.120",
"metric_serving_amount":"158.000",
"sugar":"0.08",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=16834&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"6",
"serving_description":"1 cup, dry, yields",
"vitamin_c":"0",
"carbohydrate":"159.03",
"metric_serving_unit":"g",
"fat":"1.60",
"sodium":"2080",
"polyunsaturated_fat":"0.429",
"fiber":"2.3",
"cholesterol":"0",
"iron":"38",
"serving_id":"15284",
"protein":"15.16",
"monounsaturated_fat":"0.497",
"potassium":"200",
"number_of_units":"1.000",
"calories":"735",
"measurement_description":"cup, dry, yields",
"saturated_fat":"0.432",
"metric_serving_amount":"570.000",
"sugar":"0.29",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=15284&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 oz, dry, yields",
"vitamin_c":"0",
"carbohydrate":"24.27",
"metric_serving_unit":"g",
"fat":"0.24",
"sodium":"318",
"polyunsaturated_fat":"0.065",
"fiber":"0.3",
"cholesterol":"0",
"iron":"6",
"serving_id":"18252",
"protein":"2.31",
"monounsaturated_fat":"0.076",
"potassium":"30",
"number_of_units":"1.000",
"calories":"112",
"measurement_description":"oz, dry, yields",
"saturated_fat":"0.066",
"metric_serving_amount":"87.000",
"sugar":"0.04",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=18252&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 serving (105 g)",
"vitamin_c":"0",
"carbohydrate":"29.30",
"metric_serving_unit":"g",
"fat":"0.29",
"sodium":"383",
"polyunsaturated_fat":"0.079",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"17592",
"protein":"2.79",
"monounsaturated_fat":"0.092",
"potassium":"37",
"number_of_units":"1.000",
"calories":"135",
"measurement_description":"serving (105g)",
"saturated_fat":"0.080",
"metric_serving_amount":"105.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=17592&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"100 g",
"vitamin_c":"0",
"carbohydrate":"27.90",
"metric_serving_unit":"g",
"fat":"0.28",
"sodium":"365",
"polyunsaturated_fat":"0.075",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"53181",
"protein":"2.66",
"monounsaturated_fat":"0.087",
"potassium":"35",
"number_of_units":"100.000",
"calories":"129",
"measurement_description":"g",
"saturated_fat":"0.076",
"metric_serving_amount":"100.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=53181&portionamount=100.000"
}
]
},
"food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular",
"food_type":"Generic",
"food_name":"White Rice",
"food_id":"4501"
}
Use + to append all serving_description value in ret as:
ret += shit + "\n\n";
Each iteration of the loop overrides the value of ret so that you are never able to accumulate them. For this reason, when you return it has the last value you stored there and none of the previous values that were wiped out. Consider using a StringBuilder.
StringBuilder builder = new StringBuilder();
...
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
builder.append(shit).append("\n");
}
...
return builder.toString();
I am having a problem with the above task in my android application. I am accepting user input from the EditText widget in the form of String. I accepting numbers from the user so I have to parse them to integers so they can be compared with another array of integers. I have the line:
String message = editText.getText().toString()
then to try and parse the String to an int I have the code line:
int userNumbers = Integer.parseInt(message).
However when I attempt to compare the array userArray with the array numbers I am getting the error that "Incompatible operand types String and Integer.
Can anyone see where my problem is or how I can solve it? Here's my code:
Thanks in advance.
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = ".com.example.lotterychecker.MESSAGE";
static boolean bonus = false;
static boolean jackpot = false;
static int lottCount = 0;
Button check;
Integer [] numbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//link to the intended web site and get the lottery numbers while the app is opening
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").userAgent("Mozilla").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//called when the user clicks the send button
public void checkNumbers(View view) {
final int SIZE =6;
String [] userArray = new String[SIZE];
//create an intent to display the numbers
Intent intent = new Intent(this, DisplayNumbersActivity.class);
EditText editText = (EditText) findViewById(R.id.enter_numbers);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message );
startActivity(intent);
//parse string message to an int for user numbers
try{
int userNumbers = Integer.parseInt(message); //is this right?
}//try
catch (NumberFormatException e)
{
System.out.println("Not a number" + e.getMessage());
}
Toast.makeText(MainActivity.this, "Here are your numbers", Toast.LENGTH_LONG).show();
for (int count =0; count < SIZE; count ++)
{
if (check.isPressed())
{
userArray[count] = editText.getText().toString();
}
}//for
//compare the two arrays of integers
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (userArray[loop] == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}//for
}//for main
You have this
Integer [] numbers; // numbers is an integer array
You have string array
String [] userArray = new String[SIZE]; // userArray is a string array
You compare like below
if (userArray[loop] == numbers[loopOther])
So you get the error Incompatible operand types String and Integer.
try
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
Enclosing the above with try catch block
String message = editText.getText().toString();
try{
int userNumbers = Integer.parseInt(message);
//is this right? yes
}
catch (NumberFormatException e)
{
e.printStacktrace();
}
Change String to Int here:
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.valueOf(userArray[loop]) == numbers[loopOther]) //how do I parse this?
{
lottCount++;
}else if (Integer.valueOf(userArray[loop]) == bonus)
{
bonus = true;
}
}//for
}//for main
Parse Like this :
for (int loop = 0; loop < userArray.length; loop++)
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (Integer.parseInt(userArray[loop]) == numbers[loopOther])
{
lottCount++;
}else if (userArray[loop] == bonus)
{
bonus = true;
}
}
}
I want to save/recall an integer array using SharedPreferences. Is this possible?
You can try to do it this way:
Put your integers into a string, delimiting every int by a character, for example a comma, and then save them as a string:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
int[] list = new int[10];
StringBuilder str = new StringBuilder();
for (int i = 0; i < list.length; i++) {
str.append(list[i]).append(",");
}
prefs.edit().putString("string", str.toString());
Get the string and parse it using StringTokenizer:
String savedString = prefs.getString("string", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
int[] savedList = new int[10];
for (int i = 0; i < 10; i++) {
savedList[i] = Integer.parseInt(st.nextToken());
}
You can't put Arrays in SharedPreferences, but you can workaround:
private static final String LEN_PREFIX = "Count_";
private static final String VAL_PREFIX = "IntValue_";
public void storeIntArray(String name, int[] array){
SharedPreferences.Editor edit= mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE).edit();
edit.putInt(LEN_PREFIX + name, array.length);
int count = 0;
for (int i: array){
edit.putInt(VAL_PREFIX + name + count++, i);
}
edit.commit();
}
public int[] getFromPrefs(String name){
int[] ret;
SharedPreferences prefs = mContext.getSharedPreferences("NAME", Context.MODE_PRIVATE);
int count = prefs.getInt(LEN_PREFIX + name, 0);
ret = new int[count];
for (int i = 0; i < count; i++){
ret[i] = prefs.getInt(VAL_PREFIX+ name + i, i);
}
return ret;
}
Here's my version, based on Egor's answer. I prefer not to use StringBuilder unless I'm building an enourmous string, but thanks to Egor for using StringTokenizer -- haven't made much use of this in the past, but it's very handy! FYI, this went in my Utility class:
public static void saveIntListPrefs(
String name, Activity activity, List<Integer> list)
{
String s = "";
for (Integer i : list) {
s += i + ",";
}
Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
editor.putString(name, s);
editor.commit();
}
public static ArrayList<Integer> readIntArrayPrefs(String name, Activity activity)
{
SharedPreferences prefs = activity.getPreferences(Context.MODE_PRIVATE);
String s = prefs.getString(name, "");
StringTokenizer st = new StringTokenizer(s, ",");
ArrayList<Integer> result = new ArrayList<Integer>();
while (st.hasMoreTokens()) {
result.add(Integer.parseInt(st.nextToken()));
}
return result;
}
I like to use JSON, which can be stored and retrieved as a string, to represent any complex data in SharedPreferences.
So, in the case of an int array:
public void setPrefIntArray(String tag, int[] value)
{
SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(context)
.edit();
String s;
try
{
JSONArray jsonArr = new JSONArray();
for (int i : value)
jsonArr.put(i);
JSONObject json = new JSONObject();
json.put(tag, jsonArr);
s = json.toString();
}
catch(JSONException excp)
{
s = "";
}
prefEditor.putString(tag, s);
prefEditor.commit();
}
public int[] getPrefIntArray(String tag, int[] defaultValue)
{
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String s = pref.getString(tag, "");
try
{
JSONObject json = new JSONObject(new JSONTokener(s));
JSONArray jsonArr = json.getJSONArray(tag);
int[] result = new int[jsonArr.length()];
for (int i = 0; i < jsonArr.length(); i++)
result[i] = jsonArr.getInt(i);
return result;
}
catch(JSONException excp)
{
return defaultValue;
}
}
The beauty is that the same idea can be applied to any other complex data representable as a JSON.
Two solutions:
(1) Use http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
It has split/join functions that let you join and split the integers in one liners:
StringUtils.join([1, 2, 3], ';') = "1;2;3"
StringUtils.split("1;2;3", ';') = ["1", "2", "3"]
You'd still have to convert the strings back to integers, though.
Actually, for splitting java.lang.String.split() will work just as fine:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
(2) Use the SharedPreferences.putStringSet() (API 11):
SharedPreferences.Editor editor = preferences.edit();
int count = this.intSet.size();
if (count > 0) {
Set<String> theSet = new HashSet<String>();
for (Long l : this.intSet) {
theSet.add(String.valueOf(l));
}
editor.putStringSet(PREFS_KEY, theSet);
} else {
editor.remove(PREFS_KEY);
}
editor.commit();
And to get it back:
Set<String> theSet = this.preferences.getStringSet(PREFS_KEY, null);
if (theSet != null && !theSet.isEmpty()) {
this.intSet.clear();
for (String s : theSet) {
this.intSet.add(Integer.valueOf(s));
}
}
This code does not catch the NPEs or NumberFormatExceptions because the intSet is otherwise assured to not contain any nulls. But of course, if you cannot assure that in your code you should surround this with a try/catch.
Here is how the "convert to comma-separated String" solution could look in Kotlin, implemented as extension functions:
fun SharedPreferences.Editor.putIntArray(key: String, value: IntArray): SharedPreferences.Editor {
return putString(key, value.joinToString(
separator = ",",
transform = { it.toString() }))
}
fun SharedPreferences.getIntArray(key: String): IntArray {
with(getString(key, "")) {
with(if(isNotEmpty()) split(',') else return intArrayOf()) {
return IntArray(count(), { this[it].toInt() })
}
}
}
That way you can use putIntArray(String, IntArray) and getIntArray(String) just like the other put and set methods:
val prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
prefs.edit().putIntArray(INT_ARRAY_TEST_KEY, intArrayOf(1, 2, 3)).apply()
val intArray = prefs.getIntArray(INT_ARRAY_TEST_KEY)
I went for the below solution, it's the least verbose of what I could see in this thread (in my case I wanted to have a set as a collection). "value" is the of type Set<Int>.
Save:
sharedPreferences.edit {
if (value.isNotEmpty()) {
putStringSet(key, hashSetOf(*value.map { it.toString() }.toTypedArray()))
} else {
remove(key)
}
}
Retrieve:
val stringSet = sharedPreferences.getStringSet(key, null)
if (stringSet.isNullOrEmpty()) return emptySet()
return setOf<Int>(*stringSet.map { Integer.valueOf(it) }.toTypedArray())
You can only save primitive values in sharedPreference. Use Sqlite instead.