MultiSelectListPreference from code - java

I would like to know how to use MultiSelectListPreference preference in code.
The following code is taken from the API examples file PreferencesFromCode.java, if someone could give a similar example for MultiSelectListPreference you would make my day :)
// List preference
ListPreference listPref = new ListPreference(this);
listPref.setEntries(R.array.entries_list_preference);
listPref.setEntryValues(R.array.entryvalues_list_preference);
listPref.setDialogTitle(R.string.dialog_title_list_preference);
listPref.setKey("list_preference");
listPref.setTitle(R.string.title_list_preference);
listPref.setSummary(R.string.summary_list_preference);
dialogBasedPrefCat.addPreference(listPref);

I couldn't find any examples online, but I put this together and it works.
Edit: This solution will only work on ICS+. Honeycomb completely ignores .setValues() and the HashSet passed to the listener contains different values. This is a known bug, but I hope this will help people wanting to implement in Android v4+
MultiSelectListPreference listPreference = new MultiSelectListPreference(context);
listPreference.setTitle(R.string.configure_category_title);
listPreference.setDialogTitle(R.string.configure_category_title);
listPreference.setSummary(R.string.configure_category_summary);
listPreference.setEntries(R.array.configure_category_array);
listPreference.setEntryValues(new CharSequence[]{
ProcessList.PREF_SERVICES + mAppWidgetId,
ProcessList.PREF_INACTIVE + mAppWidgetId,
ProcessList.PREF_INTERNAL + mAppWidgetId
});
//Create a Set<String> with list items that should be selected
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
boolean showServices = sharedPref.getBoolean(ProcessList.PREF_SERVICES + mAppWidgetId, true);
boolean showInactive = sharedPref.getBoolean(ProcessList.PREF_INACTIVE + mAppWidgetId, true);
boolean showInternal = sharedPref.getBoolean(ProcessList.PREF_INTERNAL + mAppWidgetId, true);
String[] strings = new String[3];
int cnt = 0;
if (showServices)
strings[cnt++] = ProcessList.PREF_SERVICES + mAppWidgetId;
if (showInactive)
strings[cnt++] = ProcessList.PREF_INACTIVE + mAppWidgetId;
if (showInternal)
strings[cnt] = ProcessList.PREF_INTERNAL + mAppWidgetId;
Set<String> mySet = new HashSet<String>();
Collections.addAll(mySet, strings);
//Add the set
listPreference.setValues(mySet);
//Listen for changes, I'm not sure if this is how it's meant to work, but it does :/
listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object o) {
HashSet hashSet = (HashSet) o;
Iterator stringIterator = hashSet.iterator();
boolean[] states = {false, false, false};
String prefString;
while (stringIterator.hasNext()) {
prefString = (String) stringIterator.next();
if (prefString == null)
continue;
if (prefString.compareTo(ProcessList.PREF_SERVICES + mAppWidgetId) == 0)
states[0] = true;
else if (prefString.compareTo(ProcessList.PREF_INACTIVE + mAppWidgetId) == 0)
states[1] = true;
else if (prefString.compareTo(ProcessList.PREF_INTERNAL + mAppWidgetId) == 0)
states[2] = true;
}
PreferenceManager
.getDefaultSharedPreferences(getActivity())
.edit()
.putBoolean(ProcessList.PREF_SERVICES + mAppWidgetId, states[0])
.putBoolean(ProcessList.PREF_INACTIVE + mAppWidgetId, states[1])
.putBoolean(ProcessList.PREF_INTERNAL + mAppWidgetId, states[2])
.commit();
return true;
}
});
preferenceCategory.addPreference(listPreference);

Related

Java: Comparing String

I am trying to compare two Strings based on which the boolean dontuse will be set. For practice I have set string as static but they may vary (Please dont ask how I get these Strings it a whole big beast in itself).
What I am trying to do is, check if String 'allofmycode' has any element more then 'codeChoosen' then 'dontuse' is false. But if both of the string are equal then its is false or if the string has same element written several times then also false.
So, for
(1) it will be false as it contains AB & CD which are extra.
(2) will be true as it has the same element but is duplicate.
I hope it make sense, any suggestions or help? Thanks
public static void main(String[] args) {
boolean dontuse = false;
String codeChoosen = "EX,ZX";
String allofmycode = "EX,AB,CD,EX"; //(1) dontuse=false
//String allofmycode = "EX,EX,ZX"; //(2) dontuse =true
List<String> mycodeChoosen = Arrays.asList(codeChoosen.split("\\s*,\\s*"));
System.out.println("Selected : \t " + mycodeChoosen);
List<String> allofmyresult = Arrays.asList(allofmycode.split("\\s*,\\s*"));
System.out.println("All : \t" + allofmyresult);
if (mycodeChoosen.equals(allofmyresult)) {
dontuse = true;
} else {
for (int i = 0; i < mycodeChoosen.size(); i++) {
if (allofmyresult.contains(mycodeChoosen.get(i))) {
System.out.println(mycodeChoosen.get(i));
}
}
}
System.out.println("\n[DONT USE IS] : \t " + dontuse);
}
For example in basic english, If you have Apple, Orange and Banana; and I say people with Apple and Orange are not coming to my party. But you also have Banana so you are allowed to come to the party. But if you had two Apples or Apple and Banana then you are not allowed. I hope it make sense.
dontuse = !allofmyresult.stream().anyMatch(str -> !mycodeChoosen.contains(str));
As the problem seems to require only a view as sets, do:
static Set<String> codes(String list) {
Set<String> set = new HashSet<>();
Collections.addAll(set, list.split("\\s*,\\s*"));
return set;
}
String codeChoosen = "EX,ZX";
String allofmycode = "EX,AB,CD,EX"; //(1) dontuse=false
Set<String> choosen = codes(codeChoosen);
Set<String> all = codes(allofmycode);
boolean dontuse = choosen.equals(all);
// all.containsAll(choosen)
The original code probably was meant to do:
if (mycodeChoosen.equals(allofmyresult)) {
dontuse = true;
} else {
dontuse = true;
for (int i = 0; i < mycodeChoosen.size(); i++) {
if (allofmyresult.contains(mycodeChoosen.get(i))) {
dontuse = false;
break;
}
}
}

how to use shared preferences to save array list items?

I use these 2 methods for save and load my array list and I need to save my array list after each item dynamically added to array.
public void addItems(int howMany){
if (howMany > 0) {
int lastInsertedIndex = 11;
for (int i = lastInsertedIndex + 1; i <= lastInsertedIndex + howMany; i++) {
mList.add("Item " + i);
notifyItemInserted(mList.size() - 1);
}
lastInsertedIndex = lastInsertedIndex + howMany;
}
}
and my save and load method:
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(mainListAdapter.mList);
editor.putStringSet("list", set);
return editor.commit();
}
public ArrayList<String> getArray() {
SharedPreferences sp = context.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}
My problem is : when I add a new item with button nothing happen and like the array list is full how to fix this ?
The the following:
Declare myList globally:
ArrayList<String> myList = new ArrayList<String>();
For setting value:
for (int i = 0; i < totalSize; i++) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("number" + i, value + "").commit();
}
For getting value:
for (int i = 0; i < totalSize; i++) {
myList.add(PreferenceManager.getDefaultSharedPreferences(this)
.getString("number" + i, "0"));
}
NOTE:- totalSize is the size of your array
enjoy coding.............
I think you should try using TinyDB, it's an implementation of SharedPreferences and is very simple to use.
TinyDB tinydb = new TinyDB(context);
tinydb.putList("identifier", list);
You can even save objects:
tinydb.putObject(key, object);
tinydb.putListObject(key, objectsArray);

scroll view in relation to tts android

how can i scroll a view (recyclerview) in relation to my tts,
ive looked at onUtterance but it seems to only have a start and stop listener, so i need to think outside the box, i give my tts a string from an Arraylist like this
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++)
{
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
speakWords(words);
I was thinking about cutting the string up into sections and giving it to the TTS one string at a time and move the view as I go. I already give my gridlayout manager an int for the amount of columns (called columns).
The array list adds a comma after every word, so I was thinking something like
find the nth/(column) comma
split the string
check if tts is speaking and listen for onUtterance onDone to pass new string
read the string
move the view
and keep doing this until theres no words left and coding for the remainder % im not sure how to do all of that so if anyone wants to help feel free, (I think Im looking at StringUtils and creating each smaller string with a for loop and passing them to the tts in onUtteranceListener onDone, but im still a little new to android), but mainly does anyone have a better way
okay this is what i have so far but it could probably use some work im still an amateur, I've split the string into blocks based on the size of the screen, and the handler that scrolls the screen relies on the amount of letters in each broken up string, also the smoothscrolltoposition is scrolling a custom layout manager that scrolls pretty slowly im having an issue though where on some devices the array list counting the words will only reach 20 not sure why but ill ask and hopefully update this when ive fixed it so here is my speak and move method
public void speakAndMove(){
final ArrayList<String> list = new ArrayList<>();
SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(0);
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++) {
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
Integer numOfWords = list.size();
words = list.toString();
Integer count = 0;
Integer startPoint = 0;
scrollPos = 0;
final Integer speed = words.length() * 15;
Integer leftOver = 0;
final int columns = getResources().getInteger(R.integer.grid_columns);
System.out.println(numOfWords);
ArrayList<String> arrayList = new ArrayList<>();
if (list.size() <= columns) {
if (words.contains("[]")) {
speakWords("");
} else if (words.contains(", 's")) {
formatString = words.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (words.contains(", ing")) {
formatString = words.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(words);
}
}
if (list.size()>=columns) {
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) == ',') {
count++;
if (count == columns) {
String ab = words.substring(startPoint, i + 1);
//speakWords(ab);
if (ab.contains(", 's")) {
formatString = ab.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab.contains(", ing")) {
formatString = ab.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab);
}
startPoint = i + 1;
count = 0;
leftOver = words.length() - startPoint;
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("main string"+" scroll " + scrollPos + " startpoint " + startPoint +" speed " + speed);
}
}
if (leftOver > 0) {
String ab2 = words.substring(startPoint, words.length());
//speakWords(ab2);
if (ab2.contains(", 's")) {
formatString = ab2.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab2.contains(", ing")) {
formatString = ab2.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab2);
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("leftovers "+ leftOver + " scroll " + scrollPos + " startpoint " + startPoint +" count " + scrollPos);
count = 0;
//scrollPos = 0;
}
}
final Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
scrollPos = scrollPos + columns;
SpeakGrid.recyclerView.getLayoutManager().smoothScrollToPosition(SpeakGrid.recyclerView, null ,scrollPos);
System.out.println("position "+ scrollPos + " speed " + speed + " list size " + list.size());
if (scrollPos < list.size())
h.postDelayed(this,speed);
// close this activity
}
}, speed);
}

Check if two numbers exist in two dependent arrays - Java

I have two arrays of double values called lat2[] and lon2[]. I have there stored the particular lattitude and longtitude values. And I can get those values as simple double values. My question is how can I find if this two doubles exist in the array (to check which marker has been clicked simply). Here is what I've done so far but it doesnt seem to work:
#Override
public boolean onMarkerClick(Marker marker) {
markerLatLng = marker.getPosition();
markerLat = markerLatLng.latitude;
markerLng = markerLatLng.longitude;
for (int i = 0; i < lat2.length; i++) {
if (markerLat == lon2[i]) {
for (int j = 0; j < lon2.length; j++) {
if (markerLng == lon2[j]) {
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
}
}
}
return true;
}
Probably if I understood your data structure there is a problem in your for loop.
If you store latitude and longitude in two arrays I imagine that a point in position n is defined by longitude[n] and latitude[n].
If this is how you store your points here is how you need to update your code:
#Override
public boolean onMarkerClick(Marker marker) {
int markerLat = marker.getPosition().latitude;
int markerLng = marker.getPosition().longitude;
for (int i = 0; i < lat2.length; i++) {
if (markerLat == lat2[i] && markerLng == lon2[j]) {
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
}
return true;
}
Please don't use global variables. I edited your code to define markerLat and markerLng local to the method (I don't know if int is the correct type).
Create a List for example ArrayList from the lat2, log2 array and check if the numbers contains like:
List lat = new ArrayList(lat2);
List lon = new ArrayList(lon2);
if (lat.contains(markerLat) && lon.contains(markerLng)){
String title = marker.getTitle();
Log.e("TAG", " " + title);
}

linkedlist has two sizes

I'm trying to add to a LinkedList values from the accelerometer.
private LinkedList<Float> rawValues = new LinkedList<Float>();
public void onSensorChanged(SensorEvent event)
{
int eventType = event.sensor.getType();
switch(eventType)
{
case Sensor.TYPE_ACCELEROMETER:
float accelerometer_z = event.values[2];
rawValues.add(accelerometer_z);
/**
* This printout gives me positions and event values
*/
System.out.println("getAccelerometer size: " +
rawValues.size() + " entry: " + rawValues.getLast());
break;
}
}
So far so good, I get readings and number positions as expected.
However, when I'm trying to do stuff with the list in other methods, it appears to be empty!
public String[] getVelocity()
{
String[] velocityString = {"42","42"};
String values = "";
String theInteger = "";
/**
* Returns a 0 size...
*/
int theSize = rawValues.size();
System.out.println("getVelocity size: " + theSize);
LinkedList<Float> slopeValues = calculateSlopeValues( rawValues);
for (int i = 0; i < theSize; i++)
{
values += "Raw:"+i+ " " + String.valueOf(rawValues.get(i)) + "\n";
values += "\tSlope:"+i+ " " + String.valueOf(slopeValues.get(i)) + "\n";
}
theInteger = String.valueOf(Math.round(Collections.max(slopeValues)*100));
/**
* After adding everything to local variables, the list is cleared.
*/
slopeValues.clear();
velocityString[0] = theInteger;
velocityString[1] = values;
return velocityString;
}
getVelocity method is called from the onTouch in the main activity.
Shed some light, please?
Regards
/M
Overridden onTouch method:
#Override
public boolean onTouch(View view, MotionEvent event)
{
MySensorEventListener eventListener = new MySensorEventListener();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
String[] strings = eventListener.getVelocity();
String velocity_int = strings[0];
String velocity_string = strings[1];
velocityView.setText(velocity_int);
listView.setText(velocity_string);
break;
}
return false;
}
Well, each time onTouch() is called, you create a new instance of MySensorEventListener, and ask this new instance for its velocity. Since each MySensorEventListener instance has its own linked list of raw values, you get an empty list each time.
The listener should probably be created only once, and stored in an instance field of the enclosing class.

Categories