IdlingResources doesn't work Espresso Android - android

I have the problem with idling resources while testing using Espresso.
It doesn't work. It is called only twice and that's all, even if return false.
public class MyIdlingResource implements IdlingResource {
private boolean mIdle;
private ResourceCallback mResourceCallback;
public MyIdlingResource () {
this.mIdle = false;
this.mResourceCallback = null;
}
#Override
public final String getName() {
return MyIdlingResource .class.getSimpleName();
}
#Override
public final boolean isIdleNow() {
ArrayList<View> views = doStuff();
mIdle = views != null && !views.isEmpty();
if (mIdle) {
if (mResourceCallback != null) {
mResourceCallback.onTransitionToIdle();
}
}
return false;
}
#Override
public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
mResourceCallback = resourceCallback;
}
}
So in this case I return false all the time, but it doesn't work either.
What is wrong ?

You missed return true; in below peace of code:
if (mIdle) {
if (mResourceCallback != null) {
mResourceCallback.onTransitionToIdle();
return true; // this one is missed
}
}

Related

How to get the result from EventObserver in Android Java

I am following this post: https://stackoverflow.com/questions/56071990/android-architecture-singleliveevent-and-eventobserver-practicle-example-in-java
public class Event<T> {
private boolean hasBeenHandled = false;
private T content;
public Event(T content) {
this.content = content;
}
public T getContentIfNotHandled() {
if (hasBeenHandled) {
return null;
} else {
hasBeenHandled = true;
return content;
}
}
public boolean isHandled() {
return hasBeenHandled;
}
}
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
public class EventObserver<T> implements Observer<Event<T>> {
private OnEventChanged onEventChanged;
public EventObserver(OnEventChanged onEventChanged) {
this.onEventChanged = onEventChanged;
}
#Override
public void onChanged(#Nullable Event<T> tEvent) {
if (tEvent != null && tEvent.getContentIfNotHandled() != null && onEventChanged != null)
onEventChanged.onUnhandledContent(tEvent.getContentIfNotHandled());
}
interface OnEventChanged<T> {
void onUnhandledContent(T data);
}
}
I have this in my repository:
private MutableLiveData<Event<String>> _amsRepositoryError = new MutableLiveData<>();
public MutableLiveData<Event<UserModel>> amsLoginSuccessReply(){return _amsLoginSuccessReply;}
_amsLoginSuccessReply.postValue(new Event(userModel));
And I catch this in my viewmodel:
amsRepository.amsLoginSuccessReply().observe(mLifeCycleOwner, new EventObserver<UserModel>(data -> {
// HOW DO I GET THE data here.
}));
on the observe, how do I get the values of the data?

How to implement select all button to select all items in recyclerview using actionmode and selectiontracker?

I have this code in my MainActivity
recyclerView.setAdapter(customAdapter);
customAdapter.submitList(path_list);
selectionTracker = new SelectionTracker.Builder<>(
"my-selection-id",
recyclerView,
new ScrollKeyProvider(1, path_list),
new ScrollItemDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
)
.withOnItemActivatedListener(new OnItemActivatedListener<Long>() {
#Override
public boolean onItemActivated(#NonNull ItemDetailsLookup.ItemDetails<Long> item, #NonNull MotionEvent e) {
Log.d("TAG", "Selected ItemId: " + item.toString());
return true;
}
})
.withOnDragInitiatedListener(new OnDragInitiatedListener() {
#Override
public boolean onDragInitiated(#NonNull MotionEvent e) {
Log.d("TAG", "onDragInitiated");
return true;
}
}).build();
customAdapter.setSelectionTracker(selectionTracker);
selectionTracker.addObserver(new SelectionTracker.SelectionObserver() {
#Override
public void onItemStateChanged(#NonNull Object key, boolean selected) {
super.onItemStateChanged(key, selected);
}
#Override
public void onSelectionRefresh() {
super.onSelectionRefresh();
}
#Override
public void onSelectionChanged() {
super.onSelectionChanged();
if (selectionTracker.hasSelection() && actionMode == null) {
actionMode = startSupportActionMode(new ActionModeController(ScrollActivity.this, selectionTracker));
actionMode.getMenu().findItem(R.id.action_item_count).setTitle("" + selectionTracker.getSelection().size());
} else if (!selectionTracker.hasSelection() && actionMode != null) {
actionMode.finish();
actionMode = null;
} else {
actionMode.getMenu().findItem(R.id.action_item_count).setTitle("" + selectionTracker.getSelection().size());
}
Iterator<String> itemIterable = selectionTracker.getSelection().iterator();
while (itemIterable.hasNext()) {
Log.i("TAG", itemIterable.next());
}
}
#Override
public void onSelectionRestored() {
super.onSelectionRestored();
}
});
This is my ActionMode callback code
public class ActionModeController implements ActionMode.Callback {
private final Context context;
private final SelectionTracker selectionTracker;
public ActionModeController(Context context, SelectionTracker selectionTracker) {
this.context = context;
this.selectionTracker = selectionTracker;
}
#Override
public boolean onCreateActionMode(androidx.appcompat.view.ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.action_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(androidx.appcompat.view.ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(androidx.appcompat.view.ActionMode mode, MenuItem item) {
if(item.getItemId()==R.id.action_clear){
if (selectionTracker.hasSelection()){
selectionTracker.clearSelection();
}
}
else if(item.getItemId()==R.id.action_select_all){
// **THIS IS PLACE WHERE I NEED HELP TO ENTER CODE FOR SELECT ALL FUNCTIONALITY**
}
return false;
}
#Override
public void onDestroyActionMode(androidx.appcompat.view.ActionMode mode) {
selectionTracker.clearSelection();
}
}
What should I do in select all section in onActionItemClicked for selecting all items in Recyclerview using SelectionTracker?
You can see for the clear option in onActionItemClicked, I have used functions of selectionTracker to clear all the selected items. I am expecting similar solution for select all option too.
Kotlin version using PagingDataAdapter - can be reworked replacing the snapshot to items in your implementation.
var itemsArray = arrayListOf<Long>()
adapter?.snapshot()?.items?.forEach {
if (!selectionTracker.isSelected(it.id.toLong()))
itemsArray.add(it.id.toLong())
}
selectionTracker?.setItemsSelected(itemsArray.asIterable(), true)

isIdleNow() is returning true, but a message indicating that the resource has transitioned from busy to idle was never sent

I'm trying to write a test in Espresso for my Android application, and I have a problem with Idle. If my isIdleNow() looks like this
public boolean isIdleNow() {
return true;
}
then the message is sent. But if IsIdleNow() has to wait for some conditions (it doesn't return true at start) then the message isn't sent.
My code:
public class ImageViewIdlingResource implements IdlingResource {
private ImageView imageView=null;
ResourceCallback callback;
public ImageViewIdlingResource(ImageView imageView2){
this.imageView = imageView2;
}
#Override
public String getName() {
return "ImageViewIdlingResource";
}
#Override
public boolean isIdleNow() {
return !imageView.isShown();
}
#Override
public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
this.callback = resourceCallback;
}}
and the test:
public class EspressoTest extends ActivityInstrumentationTestCase2<SplashScreen> {
public EspressoTest() {
super(SplashScreen.class);
}
#Override
public void setUp() throws Exception {
super.setUp();
getActivity();
ImageViewIdlingResource imageResource = new ImageViewIdlingResource((ImageView)getActivity().findViewById(R.id.splashscreen_icon));
Espresso.registerIdlingResources(imageResource);
}
public void testListGoesOverTheFold() throws InterruptedException {
onView(withId(R.id.button)).check(matches(isDisplayed()));
}}
You have to notify callback that you are on the way to idle state, something like that:
#Override
public boolean isIdleNow() {
if (!imageView.isShown()){
if (callback != null) {
callback.onTransitionToIdle();
}
return true;
}
return false;
}

I dont know how to change ok glass phrase in google glass

I want to make glass application with offline voice recognition with no ok glass
what I want to know is changing ok glass to other words ( something like "start").
I saw the source decompiled GlassHome.apk and GlassVoice.apk.
I knew that setting to ok glass is related with VoiceInputHelper, voice_label_ok_glass in String.xml
so I tried to change all of string "ok glass" to "nice"(temp guard phrase) in String.xml
but when I said any word (like "hahaha" or "kakaka") , all of word I said is recognized to my guard phrase ("nice") by VoiceService.
what should I do for changing "ok glass" to my guard phrase and working it right ???????
(P.S sorry my bad english. I hope you understand what question means)
here is my code ( I tried to set VoiceConfig to "nice")
public class MainActivity extends GlassActivity implements VoiceListener {
public static final String TEST_SERVICE_EXTRAS_KEY = "serviceExtras";
private ImageView gradientView;
private GuardHintAnimator guardHintAnimator;
private TextView guardPhraseView;
private boolean isRunning = false;
private final FormattingLogger logger = FormattingLoggers.getLogger(this);
private VoiceConfig onWindowFocusChangedRecoverConfig;
private VoiceConfig voiceConfig;
#VisibleForTesting
VoiceInputHelper voiceInputHelper;
private IVoiceMenuDialog voiceMenuDialog;
public FormattingLogger getLogger()
{
return this.logger;
}
public boolean isRunning()
{
return this.isRunning;
}
#Override
protected void onCreateInternal(Bundle bundle) {
super.onCreateInternal(bundle);
this.voiceInputHelper = new VoiceInputHelper(this, new DelegatingVoiceListener(this)
{
public VoiceConfig onVoiceCommand(VoiceCommand paramAnonymousVoiceCommand)
{
if ((!MainActivity.this.hasWindowFocus()) && (!MainActivity.this.isMessageShowing()))
{
MainActivity.this.logger.d("Ignoring voice command because we don't have window focus.", new Object[0]);
return null;
}
Log.d("listener",paramAnonymousVoiceCommand.toString());
//return super.onVoiceCommand(paramAnonymousVoiceCommand);
return null;
}
}, getVoiceServiceExtras());
}
protected void onPauseInternal()
{
this.isRunning = false;
super.onPauseInternal();
closeVoiceMenu();
this.voiceInputHelper.setVoiceConfig(VoiceConfig.OFF);
this.voiceInputHelper.unregisterGrammarLoaders();
}
public void closeVoiceMenu()
{
if (this.voiceMenuDialog != null)
{
this.voiceMenuDialog.dismiss(false);
this.voiceMenuDialog = null;
}
}
public void onPrepareVoiceMenu(VoiceMenuDialog paramVoiceMenuDialog) {}
public boolean onResampledAudioData(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
return false;
}
protected void onResumeInternal()
{
this.isRunning = true;
super.onResumeInternal();
this.voiceInputHelper.registerGrammarLoaders();
this.voiceInputHelper.setWantAudioData(shouldProvideAudioData());
NetworkUtil.checkNetwork();
VoiceConfig localVoiceConfig = new VoiceConfig();
String[] arrayOfString = new String[1];
arrayOfString[0] = "nice";
localVoiceConfig = localVoiceConfig.setCustomPhrases(arrayOfString).setShouldSaveAudio(true);
voiceInputHelper.setVoiceConfig(localVoiceConfig);
}
public boolean isVoiceMenuShowing()
{
return (this.voiceMenuDialog != null) && (this.voiceMenuDialog.isShowing());
}
public VoiceConfig onVoiceCommand(VoiceCommand paramVoiceCommand)
{
Log.d("hhh",paramVoiceCommand.toString());
this.logger.w("Unrecognized voice command: %s", new Object[] { paramVoiceCommand });
return null;
}
protected Bundle getVoiceServiceExtras()
{
Bundle localBundle = new Bundle();
/* if (getIntent().hasExtra("serviceExtras"))
{
localBundle.putAll(getIntent().getBundleExtra("serviceExtras"));
}*/
return localBundle;
}
public void setVoiceConfig(VoiceConfig paramVoiceConfig)
{
this.voiceConfig = paramVoiceConfig;
if (paramVoiceConfig != null) {
this.voiceInputHelper.setVoiceConfig(this.voiceConfig);
}
}
public boolean shouldProvideAudioData()
{
return false;
}
public void onVoiceConfigChanged(VoiceConfig paramVoiceConfig, boolean paramBoolean) {}
}
DelegatingVoiceListener :
class DelegatingVoiceListener implements VoiceListener
{
private final VoiceListener delegate;
DelegatingVoiceListener(VoiceListener paramVoiceListener)
{
this.delegate = paramVoiceListener;
}
public FormattingLogger getLogger()
{
return this.delegate.getLogger();
}
public boolean isRunning()
{
return this.delegate.isRunning();
}
public boolean onResampledAudioData(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
return this.delegate.onResampledAudioData(paramArrayOfByte, paramInt1, paramInt2);
}
public VoiceConfig onVoiceCommand(VoiceCommand paramVoiceCommand)
{
return this.delegate.onVoiceCommand(paramVoiceCommand);
}
public void onVoiceConfigChanged(VoiceConfig paramVoiceConfig, boolean paramBoolean)
{
this.delegate.onVoiceConfigChanged(paramVoiceConfig, paramBoolean);
}
}
You need to request special permissions in your manifest to implement unlisted voice commands. Go here. However, I doubt you can change the 'ok glass' voice command. You can still try if you really want to.

RelativeLayout onClick onTouch not working

I am having trouble attaching onTouch/onClick events for a RelativeLayout. I have searched a lot on internet, and could find the possible solution as using dispatchTouchEvent(MotionEvent). But I don't want to use this way, as I am having some trouble implementing that as well. Code is attached below.
public class ConnectMeDigit extends RelativeLayout implements AddressAware {
public ConnectMeDigit(Context context, AttributeSet attrs) {
super(context, attrs);
View view = LayoutInflater.from(context).inflate(R.layout.numpad_digit, this);
Typeface face=Typeface.createFromAsset(context.getAssets(), "helveticathin.ttf");//"helveticaultralight.ttf");
String xmlProvidedSize = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "tag");
TextView keypadnumber = (TextView) view.findViewById(R.id.keypadnumber);
TextView keypadalphabets = (TextView) view.findViewById(R.id.keypadalphabets);
TextView keypadplussubscript = (TextView) view.findViewById(R.id.keypadplussubscript);
keypadnumber.setTypeface(face);
keypadalphabets.setTypeface(face);
keypadplussubscript.setTypeface(face);
keypadplussubscript.setVisibility(View.GONE);
keypadnumber.setText(xmlProvidedSize);
if(xmlProvidedSize.equals("1")) {
keypadalphabets.setVisibility(View.GONE);
}
else if(xmlProvidedSize.equals("2")) {
keypadalphabets.setText("ABC");
}
else if(xmlProvidedSize.equals("3")) {
keypadalphabets.setText("DEF");
}
else if(xmlProvidedSize.equals("4")) {
keypadalphabets.setText("GHI");
}
else if(xmlProvidedSize.equals("5")) {
keypadalphabets.setText("JKL");
}
else if(xmlProvidedSize.equals("6")) {
keypadalphabets.setText("MNO");
}
else if(xmlProvidedSize.equals("7")) {
keypadalphabets.setText("PQRS");
}
else if(xmlProvidedSize.equals("8")) {
keypadalphabets.setText("TUV");
}
else if(xmlProvidedSize.equals("9")) {
keypadalphabets.setText("WXYZ");
}
else if(xmlProvidedSize.equals("0")) {
keypadplussubscript.setVisibility(View.VISIBLE);
keypadalphabets.setVisibility(View.GONE);
}
else if(xmlProvidedSize.equals("*")) {
keypadalphabets.setVisibility(View.GONE);
}
else if(xmlProvidedSize.equals("#")) {
keypadalphabets.setVisibility(View.GONE);
}
System.out.println("ConnectMeDigit.this.getTag(): " + ConnectMeDigit.this.getTag());
System.out.println("xmlProvidedSize: " + xmlProvidedSize);
setEnabled(true);
setFocusable(true);
setFocusableInTouchMode(true);//setFocusable(true);
setClickable(true);
setLongClickable(true);
DialKeyListener lListener = new DialKeyListener(xmlProvidedSize);
setOnClickListener(lListener);
setOnTouchListener(lListener);
if (xmlProvidedSize.equals("0")) {//("0+".equals(text)) {
setOnLongClickListener(lListener);
}
}
private AddressText mAddress;
public void setAddressWidget(AddressText address) {
mAddress = address;
}
private boolean mPlayDtmf;
public void setPlayDtmf(boolean play) {
mPlayDtmf = play;
}
private class DialKeyListener implements OnClickListener, OnTouchListener, OnLongClickListener {
final char mKeyCode;
boolean mIsDtmfStarted;
/*DialKeyListener() {
mKeyCode = ConnectMeDigit.this.getText().subSequence(0, 1).charAt(0);
}*/
DialKeyListener(String character) {
mKeyCode = character.charAt(0); //ConnectMeDigit.this.getText().subSequence(0, 1).charAt(0);
System.out.println("mKeyCode: " + mKeyCode);
}
private boolean linphoneServiceReady() {
if (!LinphoneService.isReady()) {
Log.w("Service is not ready while pressing digit");
Toast.makeText(getContext(), getContext().getString(R.string.skipable_error_service_not_ready), Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onClick(View v) {
if (mPlayDtmf) {
if (!linphoneServiceReady()) return;
LinphoneCore lc = LinphoneManager.getLc();
lc.stopDtmf();
mIsDtmfStarted =false;
if (lc.isIncall()) {
lc.sendDtmf(mKeyCode);
}
}
if (mAddress != null) {
int lBegin = mAddress.getSelectionStart();
if (lBegin == -1) {
lBegin = mAddress.length();
}
if (lBegin >= 0) {
mAddress.getEditableText().insert(lBegin,String.valueOf(mKeyCode));
}
}
}
public boolean onTouch(View v, MotionEvent event) {
if (!mPlayDtmf) return false;
if (!linphoneServiceReady()) return true;
if (InCallActivity.isInstanciated()) {
InCallActivity.instance().resetControlsHidingCallBack();
}
LinphoneCore lc = LinphoneManager.getLc();
if (event.getAction() == MotionEvent.ACTION_DOWN && !mIsDtmfStarted) {
LinphoneManager.getInstance().playDtmf(getContext().getContentResolver(), mKeyCode);
mIsDtmfStarted = true;
} else {
if (event.getAction() == MotionEvent.ACTION_UP) {
lc.stopDtmf();
mIsDtmfStarted = false;
}
}
return false;
}
public boolean onLongClick(View v) {
if (mPlayDtmf) {
if (!linphoneServiceReady()) return true;
// Called if "0+" dtmf
LinphoneCore lc = LinphoneManager.getLc();
lc.stopDtmf();
}
if (mAddress == null) return true;
int lBegin = mAddress.getSelectionStart();
if (lBegin == -1) {
lBegin = mAddress.getEditableText().length();
}
if (lBegin >= 0) {
mAddress.getEditableText().insert(lBegin,"+");
}
return true;
}
};
}
I have tried setEnabled(true) setFocusable(true) setFocusableInTouchMode(true) setClickable(true) setLongClickable(true) and none of them seems to work.
Try using
view.setOnClickListener(lListener);
view.setOnTouchListener(lListener);
instead of
setOnClickListener(lListener);
setOnTouchListener(lListener);

Categories

Resources