Disable Checkbox click in multiselectListPreference in android - java

I am using mutliselectlistpreference that extends DialogPreference in my application. And i have not use any adapter for building the UI. Please find the below image.
The issue here is I am able to persist the CheckBox checked for Monday and Tuesday but i am not able to make the items read only wherein user will not able to unchecked the items. I want to make both items grey out. could you please help me out on this ?
#Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
if (entries == null || entryValues == null) {
throw new IllegalStateException(
"MultiSelectListPreference requires an entries array and an entryValues array.");
}
checked = new boolean[entryValues.length];
List<CharSequence> entryValuesList = Arrays.asList(entryValues);
List<CharSequence> entriesList = Arrays.asList(entries);
for (int i = 0; i < entryValues.length; ++i) {
if("Monday".equals(entriesList.get(i).toString())){
checked[i]=true;
}
}
if (values != null) {
for (String value : values) {
int index = entryValuesList.indexOf(value);
if (index != -1) {
checked[index] = true;
}
}
}
builder.setMultiChoiceItems(entries, checked,
new OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
checked[which] = isChecked;
}
});
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && entryValues != null) {
for (int i = 0; i < entryValues.length; ++i) {
if (checked[i]) {
newValues.add(entryValues[i].toString());
}
}
if (callChangeListener(newValues)) {
setValues(newValues);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
CharSequence[] array = a.getTextArray(index);
Set<String> set = new HashSet<String>();
for (CharSequence item : array) {
set.add(item.toString());
}
return set;
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
#SuppressWarnings("unchecked")
Set<String> defaultValues = (Set<String>) defaultValue;
setValues((restorePersistedValue ? getPersistedStringSet(values)
: defaultValues));
}
private Set<String> getPersistedStringSet(Set<String> defaultReturnValue) {
String key = getKey();
//String value = getSharedPreferences().getString("4", "Generic");
return getSharedPreferences().getStringSet(key, defaultReturnValue);
}
private boolean persistStringSet(Set<String> values) {
if (shouldPersist()) {
// Shouldn't store null
if (values == getPersistedStringSet(null)) {
return true;
}
}
SharedPreferences.Editor editor = getEditor();
editor.putStringSet(getKey(), values);
editor.apply();
return true;
}
#Override
protected Parcelable onSaveInstanceState() {
if (isPersistent()) {
return super.onSaveInstanceState();
} else {
throw new IllegalStateException("Must always be persistent");
}
}

You can use them;
checkBox.setEnabled(true); // enable checkbox
checkBox.setEnabled(false); // disable checkbox
Also you can disable them after check the checkBox with this code:
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if (isChecked){
checkBox.setEnabled(false); // disable checkbox
}
}
});

Related

How to pass current data from Adapter to Adapter?

Heterogeneous RecyclerView
Hello friends I have a simple doubt
Here i am adding singleLineText
`addSingleLine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String singleLineText = singleline.getText().toString();
if(singleLineText.length() != 0)
{
mAdapter.addItem(singleLineText,null);
mAdapter.notifyDataSetChanged();
Log.e(TAG,"adding single line text");
}
singleline.getText().clear();
}
});`
On this part i am adding MultiLineText
` addMultiLine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String multiLineText = multiline.getText().toString();
String myList[] = multiLineText.split(",");
for(String item : myList)
{
mAdapter.addItem(null,item);
mAdapter.notifyDataSetChanged();
Log.e(TAG,"adding multi line text");
}
multiline.getText().clear();
}
});
}`
My Adapter part of code:
` public void addItem(String singleLineText, String item) {
Model model = new Model();
if(item == null) {
model.setText1(singleLineText);
model.settingSingleLineText(true); // How to identify single line
}
else
{
model.setText2(item);
model.settingMultiLineText(true); // How to identify multiple line
}
modelList.add(model);
}`
GetViewType Method:
` public int getItemViewType(int position) {
if (modelList.get(position).IfSingleLine() != null)
return VERTICAL;
else {
return HORIZONTAL;
}
}`
Model class code snippet:
private Boolean checkSingleLine = null;
public Boolean IfSingleLine()
{
return checkSingleLine;
}
public void settingSingleLineText(Boolean txt1)
{
checkSingleLine = txt1;
}
public void settingMultiLineText(Boolean txt2)
{
checkMultiLine = txt2;
}
`
Problem: How to identify the singleLineText and multiLineText by using the Model Class??
You have a problem with your if (modelList.get(position).IfSingleLine() != null). IfSingleLine() will never be null. You want to check if it is true or false and this is not how you check for that.
Change your getItemViewType to the following and you will get correct orientation result from this function.
public int getItemViewType(int position) {
if (modelList.get(position).IfSingleLine())
return VERTICAL;
else {
return HORIZONTAL;
}
}`

Camera is working but I can't see it

In app based on Vuforia I want to have some demo also based on Vuforia . So I stop one Vuforia (ARactivity) and use intent to start new activity (Md2activity.class) with something like this:
arActivity.stopAR();
Intent intent = new Intent(arActivity, Md2activity.class);
arActivity.startActivity(intent);
and .stopAR method:
public void stopAR(){
try {
vuforiaAppSession.stopAR();
} catch (SampleApplicationException e) {
e.printStackTrace();
}
vuforiaAppSession.stopCamera();
mTextures.clear();
mTextures = null;
}
I can see in consol that it's working fine. Camera recognizes targets etc. But I don't have camera view on the screen. Just ProgressBar.
edit:
public class Md2activity extends Activity implements SampleApplicationControl,
SampleAppMenuInterface
{
private static final String LOGTAG = "Md2activity";
SampleApplicationSession vuforiaAppSession;
private DataSet mCurrentDataset;
private int mCurrentDatasetSelectionIndex = 0;
private int mStartDatasetsIndex = 0;
private int mDatasetsNumber = 0;
private ArrayList<String> mDatasetStrings = new ArrayList<String>();
private Activity mActivity;
private SampleApplicationControl mSessionControl;
// Our OpenGL view:
private SampleApplicationGLView mGlView;
// Our renderer:
private ImageTargetRendererMd2 mRenderer;
private GestureDetector mGestureDetector;
// The textures we will use for rendering:
private Vector<Texture> mTextures;
private boolean mSwitchDatasetAsap = false;
private boolean mFlash = false;
private boolean mContAutofocus = false;
private boolean mExtendedTracking = false;
private View mFlashOptionView;
private RelativeLayout mUILayout;
private SampleAppMenu mSampleAppMenu;
LoadingDialogHandler loadingDialogHandler = new LoadingDialogHandler(this);
// Alert Dialog used to display SDK errors
private AlertDialog mErrorDialog;
private boolean mIsDroidDevice = false;
// Called when the activity first starts or the user navigates back to an
// activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(LOGTAG, "onCreate");
super.onCreate(savedInstanceState);
//setContentView(R.layout.camera_md2);
vuforiaAppSession = new SampleApplicationSession(this);
startLoadingAnimation();
mDatasetStrings.add("StonesAndChips.xml");
mDatasetStrings.add("Tarmac.xml");
vuforiaAppSession
.initAR(this, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mGestureDetector = new GestureDetector(this, new dr.ar.browser.Md2activity.GestureListener());
// Load any sample specific textures:
mTextures = new Vector<Texture>();
mIsDroidDevice = android.os.Build.MODEL.toLowerCase().startsWith(
"droid");
}
// Process Single Tap event to trigger autofocus
private class GestureListener extends
GestureDetector.SimpleOnGestureListener
{
// Used to set autofocus one second after a manual focus is triggered
private final Handler autofocusHandler = new Handler();
#Override
public boolean onDown(MotionEvent e)
{
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e)
{
// Generates a Handler to trigger autofocus
// after 1 second
autofocusHandler.postDelayed(new Runnable()
{
public void run()
{
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_TRIGGERAUTO);
if (!result)
Log.e("SingleTapUp", "Unable to trigger focus");
}
}, 1000L);
return true;
}
}
// Called when the activity will start interacting with the user.
#Override
protected void onResume()
{
Log.d(LOGTAG, "onResume");
super.onResume();
// This is needed for some Droid devices to force portrait
if (mIsDroidDevice)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
try
{
vuforiaAppSession.resumeAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Resume the GL view:
if (mGlView != null)
{
mGlView.setVisibility(View.VISIBLE);
mGlView.onResume();
}
}
// Callback for configuration changes the activity handles itself
#Override
public void onConfigurationChanged(Configuration config)
{
Log.d(LOGTAG, "onConfigurationChanged");
super.onConfigurationChanged(config);
vuforiaAppSession.onConfigurationChanged();
}
// Called when the system is about to start resuming a previous activity.
#Override
protected void onPause()
{
Log.d(LOGTAG, "onPause");
super.onPause();
if (mGlView != null)
{
mGlView.setVisibility(View.INVISIBLE);
mGlView.onPause();
}
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
try
{
vuforiaAppSession.pauseAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
}
// The final call you receive before your activity is destroyed.
#Override
protected void onDestroy()
{
Log.d(LOGTAG, "onDestroy");
super.onDestroy();
try
{
vuforiaAppSession.stopAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Unload texture:
mTextures.clear();
mTextures = null;
System.gc();
}
// Initializes AR application components.
private void initApplicationAR()
{
// Create OpenGL ES view:
int depthSize = 16;
int stencilSize = 0;
boolean translucent = Vuforia.requiresAlpha();
mGlView = new SampleApplicationGLView(this);
mGlView.init(translucent, depthSize, stencilSize);
mRenderer = new ImageTargetRendererMd2(this, vuforiaAppSession);
mGlView.setRenderer(mRenderer);
}
private void startLoadingAnimation()
{
mUILayout = (RelativeLayout) View.inflate(this, R.layout.camera_overlay,
null);
mUILayout.setVisibility(View.VISIBLE);
mUILayout.setBackgroundColor(Color.BLACK);
// Gets a reference to the loading dialog
loadingDialogHandler.mLoadingDialogContainer = mUILayout
.findViewById(R.id.loading_indicator);
// Shows the loading indicator at start
loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.SHOW_LOADING_DIALOG);
// Adds the inflated layout to the view
addContentView(mUILayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
}
// Methods to load and destroy tracking data.
#Override
public boolean doLoadTrackersData()
{
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset == null)
mCurrentDataset = objectTracker.createDataSet();
if (mCurrentDataset == null)
return false;
if (!mCurrentDataset.load(
mDatasetStrings.get(mCurrentDatasetSelectionIndex),
STORAGE_TYPE.STORAGE_APPRESOURCE))
return false;
if (!objectTracker.activateDataSet(mCurrentDataset))
return false;
int numTrackables = mCurrentDataset.getNumTrackables();
for (int count = 0; count < numTrackables; count++)
{
Trackable trackable = mCurrentDataset.getTrackable(count);
if(isExtendedTrackingActive())
{
trackable.startExtendedTracking();
}
String name = "Current Dataset : " + trackable.getName();
trackable.setUserData(name);
Log.d(LOGTAG, "UserData:Set the following user data "
+ (String) trackable.getUserData());
}
return true;
}
#Override
public boolean doUnloadTrackersData()
{
// Indicate if the trackers were unloaded correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset != null && mCurrentDataset.isActive())
{
if (objectTracker.getActiveDataSet(0).equals(mCurrentDataset)
&& !objectTracker.deactivateDataSet(mCurrentDataset))
{
result = false;
} else if (!objectTracker.destroyDataSet(mCurrentDataset))
{
result = false;
}
mCurrentDataset = null;
}
return result;
}
#Override
public void onInitARDone(SampleApplicationException exception)
{
if (exception == null)
{
initApplicationAR();
mRenderer.mIsActive = true;
// Now add the GL surface view. It is important
// that the OpenGL ES surface view gets added
// BEFORE the camera is started and video
// background is configured.
addContentView(mGlView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
// Sets the UILayout to be drawn in front of the camera
mUILayout.bringToFront();
// Sets the layout background to transparent
mUILayout.setBackgroundColor(Color.TRANSPARENT);
try
{
vuforiaAppSession.startAR(CameraDevice.CAMERA_DIRECTION.CAMERA_DIRECTION_DEFAULT);
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
mContAutofocus = true;
else
Log.e(LOGTAG, "Unable to enable continuous autofocus");
mSampleAppMenu = new SampleAppMenu(this, this, "Image Targets",
mGlView, mUILayout, null);
setSampleAppMenuSettings();
} else
{
Log.e(LOGTAG, exception.getString());
showInitializationErrorMessage(exception.getString());
}
}
// Shows initialization error messages as System dialogs
private void showInitializationErrorMessage(String message)
{
final String errorMessage = message;
runOnUiThread(new Runnable()
{
public void run()
{
if (mErrorDialog != null)
{
mErrorDialog.dismiss();
}
}
});
}
#Override
public void onVuforiaUpdate(State state)
{
if (mSwitchDatasetAsap)
{
Log.e("onVuforiaUpdate","成功");
mSwitchDatasetAsap = false;
TrackerManager tm = TrackerManager.getInstance();
ObjectTracker ot = (ObjectTracker) tm.getTracker(ObjectTracker
.getClassType());
if (ot == null || mCurrentDataset == null
|| ot.getActiveDataSet(0) == null)
{
Log.d(LOGTAG, "Failed to swap datasets");
return;
}
doUnloadTrackersData();
doLoadTrackersData();
}
}
#Override
public boolean doInitTrackers()
{
// Indicate if the trackers were initialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
Tracker tracker;
// Trying to initialize the image tracker
tracker = tManager.initTracker(ObjectTracker.getClassType());
if (tracker == null)
{
Log.e(
LOGTAG,
"Tracker not initialized. Tracker already initialized or the camera is already started");
result = false;
} else
{
Log.i(LOGTAG, "Tracker successfully initialized");
}
return result;
}
#Override
public boolean doStartTrackers()
{
// Indicate if the trackers were started correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.start();
return result;
}
#Override
public boolean doStopTrackers()
{
// Indicate if the trackers were stopped correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.stop();
return result;
}
#Override
public boolean doDeinitTrackers()
{
// Indicate if the trackers were deinitialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
tManager.deinitTracker(ObjectTracker.getClassType());
return result;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
// Process the Gestures
if (mSampleAppMenu != null && mSampleAppMenu.processEvent(event))
return true;
return mGestureDetector.onTouchEvent(event);
}
private boolean isExtendedTrackingActive() {
return mExtendedTracking;
}
final public static int CMD_BACK = -1;
final public static int CMD_EXTENDED_TRACKING = 1;
final public static int CMD_AUTOFOCUS = 2;
final public static int CMD_FLASH = 3;
final public static int CMD_CAMERA_FRONT = 4;
final public static int CMD_CAMERA_REAR = 5;
final public static int CMD_DATASET_START_INDEX = 6;
// This method sets the menu's settings
private void setSampleAppMenuSettings()
{
SampleAppMenuGroup group;
group = mSampleAppMenu.addGroup("", false);
group.addTextItem(getString(R.string.menu_back), -1);
group = mSampleAppMenu.addGroup("", true);
group.addSelectionItem(getString(R.string.menu_extended_tracking),
CMD_EXTENDED_TRACKING, false);
group.addSelectionItem(getString(R.string.menu_contAutofocus),
CMD_AUTOFOCUS, mContAutofocus);
mFlashOptionView = group.addSelectionItem(
getString(R.string.menu_flash), CMD_FLASH, false);
Camera.CameraInfo ci = new Camera.CameraInfo();
boolean deviceHasFrontCamera = false;
boolean deviceHasBackCamera = false;
for (int i = 0; i < Camera.getNumberOfCameras(); i++)
{
Camera.getCameraInfo(i, ci);
if (ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
deviceHasFrontCamera = true;
else if (ci.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
deviceHasBackCamera = true;
}
if (deviceHasBackCamera && deviceHasFrontCamera)
{
group = mSampleAppMenu.addGroup(getString(R.string.menu_camera),
true);
group.addRadioItem(getString(R.string.menu_camera_front),
CMD_CAMERA_FRONT, false);
group.addRadioItem(getString(R.string.menu_camera_back),
CMD_CAMERA_REAR, true);
}
group = mSampleAppMenu
.addGroup(getString(R.string.menu_datasets), true);
mStartDatasetsIndex = CMD_DATASET_START_INDEX;
mDatasetsNumber = mDatasetStrings.size();
group.addRadioItem("Stones & Chips", mStartDatasetsIndex, true);
group.addRadioItem("Tarmac", mStartDatasetsIndex + 1, false);
mSampleAppMenu.attachMenu();
}
#Override
public boolean menuProcess(int command)
{
boolean result = true;
switch (command)
{
case CMD_BACK:
finish();
break;
case CMD_FLASH:
result = CameraDevice.getInstance().setFlashTorchMode(!mFlash);
if (result)
{
mFlash = !mFlash;
} else
{
showToast(getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
Log.e(LOGTAG,
getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
}
break;
case CMD_AUTOFOCUS:
if (mContAutofocus)
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_NORMAL);
if (result)
{
mContAutofocus = false;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_off));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_off));
}
} else
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
{
mContAutofocus = true;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_on));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_on));
}
}
break;
case CMD_CAMERA_FRONT:
case CMD_CAMERA_REAR:
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
vuforiaAppSession.stopCamera();
try
{
vuforiaAppSession
.startAR(command == CMD_CAMERA_FRONT ? CameraDevice.CAMERA_DIRECTION.CAMERA_DIRECTION_FRONT
: CameraDevice.CAMERA_DIRECTION.CAMERA_DIRECTION_BACK);
} catch (SampleApplicationException e)
{
showToast(e.getString());
Log.e(LOGTAG, e.getString());
result = false;
}
doStartTrackers();
break;
case CMD_EXTENDED_TRACKING:
for (int tIdx = 0; tIdx < mCurrentDataset.getNumTrackables(); tIdx++)
{
Trackable trackable = mCurrentDataset.getTrackable(tIdx);
if (!mExtendedTracking)
{
if (!trackable.startExtendedTracking())
{
Log.e(LOGTAG,
"Failed to start extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
} else
{
if (!trackable.stopExtendedTracking())
{
Log.e(LOGTAG,
"Failed to stop extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
}
}
if (result)
mExtendedTracking = !mExtendedTracking;
break;
default:
if (command >= mStartDatasetsIndex
&& command < mStartDatasetsIndex + mDatasetsNumber)
{
mSwitchDatasetAsap = true;
mCurrentDatasetSelectionIndex = command
- mStartDatasetsIndex;
}
break;
}
return result;
}
private void showToast(String text)
{
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}

Android ListPreference don't save the selection

i show a selectable list with all launchable installed apps. I wan't to save the selections, but the ListPreference saved all listed entries.
Where is my mistake?
Here is my ListPreference:
public class SettingsSelectsApps extends ListPreference {
private String separator;
private static final String DEFAULT_SEPARATOR = "\u0001\u0007\u001D\u0007\u0001";
private boolean[] entryChecked;
public SettingsSelectsApps(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
loadEntries();
entryChecked = new boolean[getEntries().length];
separator = DEFAULT_SEPARATOR;
}
public SettingsSelectsApps(Context context) {
this(context, null);
}
private void loadEntries() {
final Context context = getContext();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> pkgAppsList = context.getPackageManager().queryIntentActivities( mainIntent, 0);
CharSequence[] entries = new CharSequence[pkgAppsList.size()];
CharSequence[] entryValues = new CharSequence[pkgAppsList.size()];
int j = 0;
for ( ResolveInfo P : pkgAppsList ) {
entryValues[j] = (CharSequence) P.getClass().getName();
entries[j] = P.loadLabel(context.getPackageManager());
++j;
};
setEntries(entries);
setEntryValues(entryValues);
}
#Override
protected void onPrepareDialogBuilder(Builder builder) {
CharSequence[] entries = getEntries();
CharSequence[] entryValues = getEntryValues();
if (entries == null || entryValues == null || entries.length != entryValues.length) {
throw new IllegalStateException(
"MultiSelectListPreference requires an entries array and an entryValues "
+ "array which are both the same length");
}
restoreCheckedEntries();
OnMultiChoiceClickListener listener = new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean val) {
entryChecked[which] = val;
}
};
builder.setMultiChoiceItems(entries, entryChecked, listener);
}
private CharSequence[] unpack(CharSequence val) {
if (val == null || "".equals(val)) {
return new CharSequence[0];
} else {
return ((String) val).split(separator);
}
}
public CharSequence[] getCheckedValues() {
return unpack(getValue());
}
private void restoreCheckedEntries() {
CharSequence[] entryValues = getEntryValues();
CharSequence[] vals = unpack(getValue());
if (vals != null) {
List<CharSequence> valuesList = Arrays.asList(vals);
for (int i = 0; i < entryValues.length; i++) {
CharSequence entry = entryValues[i];
entryChecked[i] = valuesList.contains(entry);
}
}
SharedPreferences prefs = getSharedPreferences();
try{
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
}
} catch(NullPointerException e) {
Log.d("map values","Error: "+e);
}
}
#Override
protected void onDialogClosed(boolean positiveResult) {
List<CharSequence> values = new ArrayList<CharSequence>();
CharSequence[] entryValues = getEntryValues();
if (positiveResult && entryValues != null) {
for (int i = 0; i < entryValues.length; i++) {
if (entryChecked[i] == true) {
String val = (String) entryValues[i];
values.add(val);
}
}
String value = join(values, separator);
setSummary(prepareSummary(values));
setValueAndEvent(value);
}
}
private void setValueAndEvent(String value) {
if (callChangeListener(unpack(value))) {
setValue(value);
}
}
private CharSequence prepareSummary(List<CharSequence> joined) {
List<String> titles = new ArrayList<String>();
CharSequence[] entryTitle = getEntries();
CharSequence[] entryValues = getEntryValues();
int ix = 0;
for (CharSequence value : entryValues) {
if (joined.contains(value)) {
titles.add((String) entryTitle[ix]);
}
ix += 1;
}
return join(titles, ", ");
}
#Override
protected Object onGetDefaultValue(TypedArray typedArray, int index) {
return typedArray.getTextArray(index);
}
#Override
protected void onSetInitialValue(boolean restoreValue,
Object rawDefaultValue) {
String value = null;
CharSequence[] defaultValue;
if (rawDefaultValue == null) {
defaultValue = new CharSequence[0];
} else {
defaultValue = (CharSequence[]) rawDefaultValue;
}
List<CharSequence> joined = Arrays.asList(defaultValue);
String joinedDefaultValue = join(joined, separator);
if (restoreValue) {
value = getPersistedString(joinedDefaultValue);
} else {
value = joinedDefaultValue;
}
setSummary(prepareSummary(Arrays.asList(unpack(value))));
setValueAndEvent(value);
}
protected static String join(Iterable<?> iterable, String separator) {
Iterator<?> oIter;
if (iterable == null || (!(oIter = iterable.iterator()).hasNext()))
return "";
StringBuilder oBuilder = new StringBuilder(String.valueOf(oIter.next()));
while (oIter.hasNext())
oBuilder.append(separator).append(oIter.next());
return oBuilder.toString();
}
}
I believe you use code from this gist which works great except for the separator. I don't know why did the author choose the separator to be "\u0001\u0007\u001D\u0007\u0001".
Once I tried to change the separator to any other string, for example ",," everything worked.
The separator string chosen seems to cause android to be unable to parse the shared preferences xml document.

How to perform a Trie search using an autocompleteTextView in android?

I need to implement an AutocompleteTextView with a Trie search. I am using a Vertex class and a Trie class for the Trie tree data structure and an adapter for customize the view of the dropdown box of the autocompleteTextView.
Here are all the classes I am using:
The Vertex class:
public class Vertex {
private HashMap<Character, Vertex> vertexSons;
private List<Integer> wordsIndexList;
private List<Integer> prefixesIndexList;
private int wordsNumber;
private int prefixesNumber;
public Vertex() {
vertexSons = new HashMap<Character, Vertex>();
wordsIndexList = new ArrayList<Integer>();
prefixesIndexList = new ArrayList<Integer>();
wordsNumber = 0;
prefixesNumber = 0;
}
public boolean hasWords() {
if (wordsNumber > 0) {
return true;
}
return false;
}
public boolean hasPrefixes() {
if (prefixesNumber > 0) {
return true;
}
return false;
}
public void addVertexSon(Character character) {
vertexSons.put(character, new Vertex());
}
public void addIndexToWordsIndexList(int index) {
wordsIndexList.add(index);
}
public void addIndexToPrefixesIndexList(int index) {
prefixesIndexList.add(index);
}
public HashMap<Character, Vertex> getVertexSons() {
return vertexSons;
}
public List<Integer> getWordsIndexList() {
return wordsIndexList;
}
public List<Integer> getPrefixesIndexList() {
return prefixesIndexList;
}
public int getWordsNumber() {
return wordsNumber;
}
public int getPrefixesNumber() {
return prefixesNumber;
}
public void increaseWordsNumber() {
wordsNumber++;
}
public void increasePrefixesNumber() {
prefixesNumber++;
}
}
The Trie class:
public class Trie {
private Vertex rootVertex;
public Trie(List<Trieable> objectList, Locale locale) {
rootVertex = new Vertex();
for (int i = 0; i<objectList.size(); i++) {
String word = objectList.get(i).toString().toLowerCase(locale);
addWord(rootVertex, word, i);
}
}
public Vertex getRootVertex() {
return rootVertex;
}
public void addWord(Vertex vertex, String word, int index) {
if (word.isEmpty()) {
vertex.addIndexToWordsIndexList(index);
vertex.increaseWordsNumber();
}
else {
vertex.addIndexToPrefixesIndexList(index);
vertex.increasePrefixesNumber();
Character fChar = word.charAt(0);
HashMap<Character, Vertex> vertexSons = vertex.getVertexSons();
if (!vertexSons.containsKey(fChar)) {
vertex.addVertexSon(fChar);
}
word = (word.length() == 1) ? "" : word.substring(1);
addWord(vertexSons.get(fChar), word, index);
}
}
public List<Integer> getWordsIndexes(Vertex vertex, String word) {
if (word.isEmpty()) {
return vertex.getWordsIndexList();
}
else {
Character fChar = word.charAt(0);
if (!(vertex.getVertexSons().containsKey(fChar))) {
return null;
}
else {
word = (word.length() == 1) ? "" : word.substring(1);
return getWordsIndexes(vertex.getVertexSons().get(fChar), word);
}
}
}
public List<Integer> getPrefixesIndexes(Vertex vertex, String prefix) {
if (prefix.isEmpty()) {
return vertex.getWordsIndexList();
}
else {
Character fChar = prefix.charAt(0);
if (!(vertex.getVertexSons().containsKey(fChar))) {
return null;
}
else {
prefix = (prefix.length() == 1) ? "" : prefix.substring(1);
return getWordsIndexes(vertex.getVertexSons().get(fChar), prefix);
}
}
}
}
The Adapter class:
public class MunicipalitySearchAdapter extends ArrayAdapter<Municipality> {
private ArrayList<Municipality> municipalities;
private ArrayList<Municipality> allMunicipalities;
private ArrayList<Municipality> suggestedMunicipalities;
private List<Trieable> triableList;
private Trie municipalityTrie;
private int viewResourceId;
#SuppressWarnings("unchecked")
public MunicipalitySearchAdapter(Context context, int viewResourceId, ArrayList<Municipality> municipalities) {
super(context, viewResourceId, municipalities);
this.municipalities = municipalities;
this.allMunicipalities = (ArrayList<Municipality>) this.municipalities.clone();
this.suggestedMunicipalities = new ArrayList<Municipality>();
this.viewResourceId = viewResourceId;
this.triableList = new ArrayList<Trieable>();
for (Municipality mun : allMunicipalities) {
triableList.add(mun);
}
municipalityTrie = new Trie(triableList, Locale.ITALY);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(this.viewResourceId, null);
}
Municipality municipality = municipalities.get(position);
if (municipality != null) {
TextView munNameTxtView = (TextView) v.findViewById(R.id.name);
TextView proSignTxtView = (TextView) v.findViewById(R.id.sign);
TextView regNameTxtView = (TextView) v.findViewById(R.id.regionName);
if (munNameTxtView != null) {
munNameTxtView.setText(municipality.getName());
}
if (proSignTxtView != null) {
proSignTxtView.setText(municipality.getProvinceSign());
}
if (regNameTxtView != null) {
regNameTxtView.setText(municipality.getRegionName());
}
}
return v;
}
#Override
public Filter getFilter() {
return municipalityFilter;
}
Filter municipalityFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = ((Municipality) (resultValue)).getName();
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
String constraintString = constraint.toString().trim();
suggestedMunicipalities.clear();
List<Integer> wordsIndexesList = municipalityTrie.getWordsIndexes(municipalityTrie.getRootVertex(), constraintString);
for (int index : wordsIndexesList) {
suggestedMunicipalities.add(allMunicipalities.get(index));
}
List<Integer> prefixesIndexesList = municipalityTrie.getPrefixesIndexes(municipalityTrie.getRootVertex(), constraintString);
for (int index : prefixesIndexesList) {
suggestedMunicipalities.add(allMunicipalities.get(index));
}
FilterResults filterRes = new FilterResults();
filterRes.values = suggestedMunicipalities;
filterRes.count = suggestedMunicipalities.size();
return filterRes;
}
else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
#SuppressWarnings("unchecked")
ArrayList<Municipality> filteredMunicipalities = (ArrayList<Municipality>) results.values;
ArrayList<Municipality> supportMunicipalitiesList = new ArrayList<Municipality>();
clear();
for (Municipality mun : filteredMunicipalities) {
supportMunicipalitiesList.add(mun);
}
Iterator<Municipality> municipalityIterator = supportMunicipalitiesList.iterator();
while (municipalityIterator.hasNext()) {
Municipality municipality = municipalityIterator.next();
add(municipality);
}
notifyDataSetChanged();
}
}
};
}
I get a null pointer at this line (in the Filter performFltering() method implementation inside of the adapter):
for (int index : wordsIndexesList) {
suggestedMunicipalities.add(allMunicipalities.get(index));
}
Do you have any possible solutions to the problem? I can't fix it out. What am I missing or mistaking?
EDIT: I have found the problem, I needed to set the constraint toLowerCase(). Now it works. However. Why do I see the autocomplete suggestions ONLY when I type the FULL word? (in my case the name of a municipality).
It seems that my Trie doesn't return the PrefixIndexes which I can use for populating the List of suggestions. But I can't find out the problem. Any idea?
Thanks again!
To fix typing of FULL word issue mentioned by the author, getWordsIndexes should be replaced by getPrefixesIndexes, and getWordsIndexList - by getPrefixesIndexList in getPrefixesIndexes() method of Trie class:
public List<Integer> getPrefixesIndexes(Vertex vertex, String prefix)
{
if (prefix.isEmpty())
{
return vertex.getPrefixesIndexList();
}
else
{
Character fChar = prefix.charAt(0);
if (!(vertex.getVertexSons().containsKey(fChar)))
{
return null;
}
else
{
prefix = (prefix.length() == 1) ? "" : prefix.substring(1);
return getPrefixesIndexes(vertex.getVertexSons().get(fChar), prefix);
}
}
}

How can I speed up an AutocompleteTextView in Android?

Hi everyone I have an adapter which extends the ArrayAdapter class and overrides some Filterable methods. I am using this Adapter to perform some filtering while the user types inside an AutocompleteTextView. But I saw that if you type a bit fast the updanting of the filtered items becomes very slow. This is the adapter class:
public class MunicipalitySearchAdapter extends ArrayAdapter<Municipality> {
private ArrayList<Municipality> municipalities;
private ArrayList<Municipality> allMunicipalities;
private ArrayList<Municipality> suggestedMunicipalities;
private int viewResourceId;
#SuppressWarnings("unchecked")
public MunicipalitySearchAdapter(Context context, int viewResourceId, ArrayList<Municipality> municipalities) {
super(context, viewResourceId, municipalities);
this.municipalities = municipalities;
this.allMunicipalities = (ArrayList<Municipality>) this.municipalities.clone();
this.suggestedMunicipalities = new ArrayList<Municipality>();
this.viewResourceId = viewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(this.viewResourceId, null);
}
Municipality municipality = municipalities.get(position);
if (municipality != null) {
TextView munNameTxtView = (TextView) v.findViewById(R.id.name);
TextView proSignTxtView = (TextView) v.findViewById(R.id.sign);
if (munNameTxtView != null) {
munNameTxtView.setText(municipality.getName());
}
if (proSignTxtView != null) {
proSignTxtView.setText(municipality.getProvinceSign());
}
}
return v;
}
#Override
public Filter getFilter() {
return municipalityFilter;
}
Filter municipalityFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = ((Municipality) (resultValue)).getName();
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestedMunicipalities.clear();
for (Municipality municipality : allMunicipalities) {
if (municipality.getName().toLowerCase(Locale.getDefault()).startsWith(constraint.toString().toLowerCase(Locale.getDefault()))) {
suggestedMunicipalities.add(municipality);
}
}
FilterResults filterRes = new FilterResults();
filterRes.values = suggestedMunicipalities;
filterRes.count = suggestedMunicipalities.size();
return filterRes;
}
else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
#SuppressWarnings("unchecked")
ArrayList<Municipality> filteredMunicipalities = (ArrayList<Municipality>) results.values;
ArrayList<Municipality> supportMunicipalitiesList = new ArrayList<Municipality>();
clear();
for (Municipality mun : filteredMunicipalities) {
supportMunicipalitiesList.add(mun);
}
Iterator<Municipality> municipalityIterator = supportMunicipalitiesList.iterator();
while (municipalityIterator.hasNext()) {
Municipality municipality = municipalityIterator.next();
add(municipality);
}
notifyDataSetChanged();
}
}
};
}
I would like to ask if someone knows how to increase the performance of this kind of AutocompleteTextView and make the updating a faster. What should I do? Thanks!
EDIT: I have createed this classes:
Vertex:
public class Vertex {
private HashMap<Character, Vertex> vertexSons;
private List<Integer> wordsIndexList;
private List<Integer> prefixesIndexList;
private int wordsNumber;
private int prefixesNumber;
public Vertex() {
vertexSons = new HashMap<Character, Vertex>();
wordsIndexList = new ArrayList<Integer>();
prefixesIndexList = new ArrayList<Integer>();
wordsNumber = 0;
prefixesNumber = 0;
}
public boolean hasWords() {
if (wordsNumber > 0) {
return true;
}
return false;
}
public boolean hasPrefixes() {
if (prefixesNumber > 0) {
return true;
}
return false;
}
public void addVertexSon(Character character) {
vertexSons.put(character, new Vertex());
}
public void addIndexToWordsIndexList(int index) {
wordsIndexList.add(index);
}
public void addIndexToPrefixesIndexList(int index) {
prefixesIndexList.add(index);
}
public HashMap<Character, Vertex> getVertexSons() {
return vertexSons;
}
public List<Integer> getWordsIndexList() {
return wordsIndexList;
}
public List<Integer> getPrefixesIndexList() {
return prefixesIndexList;
}
public int getWordsNumber() {
return wordsNumber;
}
public int getPrefixesNumber() {
return prefixesNumber;
}
public void increaseWordsNumber() {
wordsNumber++;
}
public void increasePrefixesNumber() {
prefixesNumber++;
}
}
And Trie:
public class Trie {
private Vertex rootVertex;
public Trie(List<Trieable> objectList, Locale locale) {
rootVertex = new Vertex();
for (int i = 0; i<objectList.size(); i++) {
String word = objectList.get(i).toString().toLowerCase(locale);
addWord(rootVertex, word, i);
}
}
public Vertex getRootVertex() {
return rootVertex;
}
public void addWord(Vertex vertex, String word, int index) {
if (word.isEmpty()) {
vertex.addIndexToWordsIndexList(index);
vertex.increaseWordsNumber();
}
else {
vertex.addIndexToPrefixesIndexList(index);
vertex.increasePrefixesNumber();
Character fChar = word.charAt(0);
HashMap<Character, Vertex> vertexSons = vertex.getVertexSons();
if (!vertexSons.containsKey(fChar)) {
vertex.addVertexSon(fChar);
}
word = (word.length() == 1) ? "" : word.substring(1);
addWord(vertexSons.get(fChar), word, index);
}
}
public List<Integer> getWordsIndexes(Vertex vertex, String word) {
if (word.isEmpty()) {
return vertex.getWordsIndexList();
}
else {
Character fChar = word.charAt(0);
if (!(vertex.getVertexSons().containsKey(fChar))) {
return null;
}
else {
word = (word.length() == 1) ? "" : word.substring(1);
return getWordsIndexes(vertex.getVertexSons().get(fChar), word);
}
}
}
public List<Integer> getPrefixesIndexes(Vertex vertex, String prefix) {
if (prefix.isEmpty()) {
return vertex.getWordsIndexList();
}
else {
Character fChar = prefix.charAt(0);
if (!(vertex.getVertexSons().containsKey(fChar))) {
return null;
}
else {
prefix = (prefix.length() == 1) ? "" : prefix.substring(1);
return getWordsIndexes(vertex.getVertexSons().get(fChar), prefix);
}
}
}
}
And edited my Filter like this:
Filter municipalityFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = ((Municipality) (resultValue)).getName();
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
String constraintString = constraint.toString().trim();
suggestedMunicipalities.clear();
List<Integer> wordsIndexesList = municipalityTrie.getWordsIndexes(municipalityTrie.getRootVertex(), constraintString);
for (int index : wordsIndexesList) {
suggestedMunicipalities.add(allMunicipalities.get(index));
}
List<Integer> prefixesIndexesList = municipalityTrie.getPrefixesIndexes(municipalityTrie.getRootVertex(), constraintString);
for (int index : prefixesIndexesList) {
suggestedMunicipalities.add(allMunicipalities.get(index));
}
FilterResults filterRes = new FilterResults();
filterRes.values = suggestedMunicipalities;
filterRes.count = suggestedMunicipalities.size();
return filterRes;
}
else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
#SuppressWarnings("unchecked")
ArrayList<Municipality> filteredMunicipalities = (ArrayList<Municipality>) results.values;
ArrayList<Municipality> supportMunicipalitiesList = new ArrayList<Municipality>();
clear();
for (Municipality mun : filteredMunicipalities) {
supportMunicipalitiesList.add(mun);
}
Iterator<Municipality> municipalityIterator = supportMunicipalitiesList.iterator();
while (municipalityIterator.hasNext()) {
Municipality municipality = municipalityIterator.next();
add(municipality);
}
notifyDataSetChanged();
}
}
};
Now I get a null pointer warning when I type in the AutoCompleteTextView at this line:
List<Integer> wordsIndexesList = municipalityTrie.getWordsIndexes(municipalityTrie.getRootVertex(), constraintString);
for (int index : wordsIndexesList) {
suggestedMunicipalities.add(allMunicipalities.get(index));
}
In the for (int index : wordsIndexesList) statement. What should I do? Thanks!
You should look into using a trie, it would be perfect for auto complete.
Here is what one looks like:
As you get more characters, you can traverse further down the tree, and the number of possible options will get smaller and smaller.
This would be significantly faster than looking over your entire list each time.
Edit: After reflecting on my answer I think a much easier solution would be to just use any kind of sorted map. Checkout this answer for an example.

Categories