How to make 10 fast clicks [UIautomator] - android

Im trying to make fast 10 clicks on the button using this
public static void fastClicks(String text, int index) throws Exception {
Thread.sleep(1000);
UiObject settingsButton = new UiObject(new UiSelector().resourceId(text).index(index));
Configurator cc = Configurator.getInstance();
cc.setActionAcknowledgmentTimeout(10);
for (int i = 1; i < 11; ++i){
settingsButton.click();
System.out.println("clicked "+ i + " ");
}
}
yes it makes 10 clicks but first click have a little delay or something like that so it doesn't work properly. All I need this is 10 ritmic clicks with same delay from 1 click to 10. How can I improve this code? Thank you :)
else I tried this code
public static void fastClicks(String text, int index, int clicksCount) throws Exception {
UiObject settingsButton = new UiObject(new UiSelector().resourceId(text).index(index));
for(int currentClickIndex = 0; currentClickIndex < clicksCount; currentClickIndex++) {
if(settingsButton.exists()) {
settingsButton.click();
Thread.sleep(40);
System.out.println("clicked " + currentClickIndex + " times");
}
}
}
still nothing.

Sorry, I don't have enough reputation to comment so I'll try to make this a proper answer.
Because this behavior is only seen by the first click, it might occurs because some configurations were made before (or after) the action itself. For instance:
https://android.googlesource.com/platform/frameworks/testing/+/master/uiautomator/library/core-src/com/android/uiautomator/core/UiObject.java
public boolean click() throws UiObjectNotFoundException {
[...]
AccessibilityNodeInfo node = findAccessibilityNodeInfo(mConfig.getWaitForSelectorTimeout());
[...]
}
protected AccessibilityNodeInfo findAccessibilityNodeInfo(long timeout) {
[...]
while (currentMills <= timeout) {
node = getQueryController().findAccessibilityNodeInfo(getSelector());
if (node != null) {
break;
} else {
// does nothing if we're reentering another runWatchers()
UiDevice.getInstance().runWatchers();
}
[...]
}
return node;
}
To avoid this, you can try getting the object's bounds first and then calling getUiDevice().click(...) directly:
UiObject settingsButton = new UiObject(new UiSelector().resourceId(text).index(index));
Rect bounds = settingsButton.getBounds();
for (int i = 1; i < 11; ++i){
getUiDevice().click(bounds.centerX(), bounds.centerY());
System.out.println("clicked "+ i + " ");
}
(as suggested by #Rami Kuret https://stackoverflow.com/a/17497559/2723645)

Related

How can I save and restore checked items with simple_list_item_checked?

I want to know the best way to save and restore checked items, using on adapter the "simple_list_item_checked", I've been trying for a long time using SharedPreferences, but didn't work. Could you give me some examples? Thanks in advance!
Here, found my old code for you. You can use SparseBooleanArray for this.
private SparseBooleanArray sbArray;
//set all of the items checked in the start
if (sbArray == null) {
for (int i = 0; i < listView.getCount(); i++) {
listView.setItemChecked(i, true);
}
}
selectedIdees = new ArrayList<>();
//if we already did some checking in filters, we get our previous selections.
if (sbArray != null) {
Log.i(LOG_TAG, "sbArray size " + sbArray.size());
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key)) {
listView.setItemChecked(key, true);
}
Then somewhere I placed okButton and set onClickListener to it.
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sbArray = listView.getCheckedItemPositions();
Log.i(LOG_TAG, "sbArray created. size= " + sbArray.size());
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key)) {
selectedIdees.add(key + 1);
Log.i(LOG_TAG, "added + " + (key + 1));
}
Then I suggest to save it in shared prefs, creating the parcelable wrapper around it.

Dialog box filter for edit text minimum charatures

I have set up a dialog box with one edit text box. I used a set filter for max number of charactures allowed but I dont see an a filter for minimum. I added code to add "x" to entered text if the user enters less than 8 chars. Code compiles but crashes.
and throws Error is "string longer than 9". and gives (16 as piece.length()). could use some help solving
public void onClick(View item) {
final EditText input = new EditText(this);
switch (item.getId()) {
case R.id.textView1:
strEditText = Title1.getText().toString(); // OK
input.setText(strEditText);
input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8) }); // Set max # of charactures for Input
for (int i = 0; i < strEditText.length(); i++) { //
String piece = strEditText; //
String toBeAdded = ""; //
if (piece.length() < 8) {
int length = piece.length();
toBeAdded = piece;
while (length < 8) {
toBeAdded = toBeAdded + "X";
length++;
}
} else if (piece.length() > 8) {
throw new IllegalArgumentException("Error, string longer than 9");
} else {
toBeAdded = piece;
}
strEditText = strEditText + toBeAdded;
}// return to for-loop //
new AlertDialog.Builder(ElsEditTitles.this)
.setTitle("Ttile").setView(input).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
strReturn = input.getText().toString();
Title1.setText(strReturn);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
break;
i Cant Understand Why You Put This For : for (int i = 0; i < strEditText.length(); i++)
For Example if EditText is 'abc' strEditText is 'abc' and that for repeats 3 Time.
in First Time toBeAdded = 'abcXXXXX' and when code "strEditText = strEditText + toBeAdded;" run strEditText = 'abcabcXXXXX' and when That for goes into 2nd loop its Already more than 8 character and throws your Error.
Sorry For My Bad English..

How to stop Executors.newSingleThreadScheduledExecutor(); in between the thread execution?

Below I am posting my code for the thread I am running to animate text in a RelativeLayout on top of the Page Curl activity by harism.
public void startProgress(final int index)
{
runnable = new Runnable()
{
#Override
public void run()
{
mArrWords.removeAll(mArrWords);
mStart.removeAll(mStart);
mEnd.removeAll(mEnd);
words = sentence.split(" ");
for(int i = 0; i < words.length; i++)
{
mArrWords.add(words[i]);
if(i == 0)
{
mStart.add(0);
mEnd.add(words[0].length());
}
else
{
mStart.add(mEnd.get(i-1)+1);
mEnd.add(mStart.get(i)+words[i].length());
}
/*Log.e("words", "" + "" + words[i]);
Log.e("mArrWords", "" + mArrWords);
Log.e("mStart", "" + mStart);
Log.e("mEnd", "" + mEnd);*/
}
for (int i = 0; i < mArrWords.size(); i++)
{
final int value = i;
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mHandler.post(new Runnable()
{
#Override
public void run()
{
currIndex = index;
try
{
if(CurlView.ANIMATE)
tv1.setVisibility(View.VISIBLE);
else
tv1.setVisibility(View.GONE);
final Pattern p = Pattern.compile(mArrWords.get(value));
final Matcher matcher = p.matcher(sentence);
SpannableString spannableTxt = new SpannableString(sentence);
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
while(matcher.find())
spannableTxt.setSpan(span, mStart.get(value), mEnd.get(value), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv1.setText(spannableTxt);
mHandler.sendEmptyMessage(0);
}
catch (Exception e)
{
e.printStackTrace();
mHandler.sendEmptyMessage(0);
}
}
});
}
}
};
final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(runnable, CurlView.ANIMTIME+50, TimeUnit.MILLISECONDS);
}
Here, I am animating the text over images. I need to change the text for each page I am changing. I am able to change the text, however, when I turn the page, the index values I store in ArrayLists are not getting cleared. I am storing a sentence in an ArrayList named mArrWords and the indexes to refer to each word of sentence are stored in mStart and mEnd.
The problem I am facing is when the text changes, the animation starts with the previous indexes stored in mStart and mEnd ArrayLists I use to store index of a particular word. What I need to know is how do I stop my thread when the page is turned or the index of the page changes. I am calling this function inside the updatePage(final CurlPage page, final int width, final int height, final int index) method of Curl activity. I hope I was able to explain my problem. Thanks!
EDIT: I would like to specify my question more clearly. How do I check if the thread is already running before starting another thread and stop the execution of the previous thread?
removeCallbacks(..) only stops pending messages (Runnables).If runnable is started then u can not stop it in this way. See the following :
removecallbacks-not-stopping-runnable

Android: Reading from a file and increasing the readed lines not working

I have a file with different questions and I need to read them one after another when the user clicks the "Next Button". However, I can only read the first line and the following one and after that one the layout remains the same and doesn't work. I will appreciate some help in order to read total questions. Here is part of my code:
public class Questions {
int i = 0;
int questionCount = 0;
int category;
String question;
int questionNumber=1;
void currentQuestion(Context context, int cat) {
category = cat;
String questionFile = "";
questionFile = "VerbalSup1.txt";
questionCount = 25;
Log.i("Question", questionFile + ": " + questionCount);
try {
InputStream is = context.getAssets().open(questionFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i< questionNumber; i++) {
reader.readLine();
}
question = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
void Next(){
questionNumber=questionNumber + 1;
}
Here is the next button:
bNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
questions.Next();
questions = new Questions();
questions.Next();
currentQuestion();
}
});
The issue is that you are resetting the questions object so it will get only the first line..
Here:
questions.Next();
questions = new Questions(); // this is wrong as the counts will be reset to defaults
questions.Next();
currentQuestion();
You should have:
questions.Next();
currentQuestion();
currentQuestion();
I hope it helps.

Trying to set textview

Here is my class it goes in to infinite loop please check where I am going wrong ... I am trying to get id's of image view making it random and then trying to set text view with imageview's description
public class Object {
int ObectIds[];
LinearLayout HUDDisplay;
int HudDisplayText[] = {R.id.HUD_Text_Element1,
R.id.HUD_Text_Element2,
R.id.HUD_Text_Element3,
R.id.HUD_Text_Element4,
R.id.HUD_Text_Element5,
R.id.HUD_Text_Element6,
R.id.HUD_Text_Element7};
TextView[] text;
View v;
Object(Context context,View vs) {
super();
ObectIds = new int[8];
HUDDisplay=(LinearLayout)vs.findViewById(R.id.HUD_Display);
for (int i = 0; i < 8; i++) {
ObectIds[i] = (R.id.imageView1) + i;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
randomize(vs);
setTextView();
}
public void setTextView()
{
for(int i=0;i<8;++i)
{
text[i] =(TextView) HUDDisplay.findViewById(HudDisplayText[i]);
text[i].setText(v.getContentDescription());
}
}
public void randomize(View vs) {
for (int i = 0; i < 8; i++) {
while (true) {
shuffleArray(ObectIds);
v = vs.findViewById(ObectIds[i]);
Log.d("Image", "Image Id's " + v.getId());
if (!v.isClickable()) {
v.setClickable(true);
break;
}
}
}
}
static void shuffleArray(int[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i >= 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Hey man I observed your code & found error in code :
Please compare following code with your code... Constructor
for (int i = 0; i < 8; i++) {
ObectIds[i] = **HudDisplayText[i]**;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
You have a while(true) loop that you break from only if v is not clickable. What happens if v is clickable? Nothing in your code ever sets v to not clickable, and views by default are not clickable.
I notice you're using the Object class. Object is basically the root of which all classes extend. If you call super() in the constructor, it will call the super class constructor, which is Object as well... That might be the problem.
Try looking for tutorials on how to start with Java/Android, since you are also using variables names that are not recommended. E.g. in Java,:
- a Class starts with a Capital
- a variable, starts with lowercase
- a function starts with lowercase:
public class Captial
{
private int anIntegerStartsWithLowerCase;
private void functionsAreLowerCaseAsWell()
{
}
}
Also take a look at your loop... It looks like it is never ending

Categories

Resources