Variable not recognized after if argument - android

In the databse adapter, I'm trying to create a if (a & b) {select count from sqlite} .. full code as below.. however the cat variable is not recognized (as highlighted?
int samsung = 10;
int iphone = 20
public int getChick() {
int cat = 0;
if (red == 1 & blue == 2) {
int pit = (int) DatabaseUtils.longForQuery(db, "SELECT COUNT(*)
FROM table where one >= " + samsung + " and two >= " + iphone, null);
//////>>>>>> this cat is not recognized by eclipse
int cat = 0 + pit;
}
int dog = cat;
return dog;
}
Thing is, I don't see how it is wrong. If you could please point it out to me. Thanks.

you declare cat in the first line of the method and again inside the if statement. you need to remove the int declaration on the second one

Change
int cat = 0 + pit;
to
cat = 0 + pit;
It looks like you're simply declaring it again when you've already declared it.

Related

how to start count upto 1 until press comma(,) it should count tow

its may be silly but am confused on that this i want to start count up to one and if press comma(,)then i want to count comma only, here how i am try.
String conCount;
conCount = "1";
int countComma = conCount.length() - conCount.replace(",", "").length();
String lenVar;
lenVar = conCount;
convert = String.valueOf(countComma);
if (conCount.length() == 0) {
lenVar = "0";
} else {
textViewConCount.setText(convert);
}
String editTextString = "abc,efg,pqr,xyz";
if (editTextString.contains(",")) {
int countStringsSeperatedByComma = 0;
countStringsSeperatedByComma = editTextString.split(",").length;
System.out.println("Count of strings seperated by comma : " + countStringsSeperatedByComma);
int commaCount = countStringsSeperatedByComma - 1;
System.out.println("Count of commas : " + commaCount);
} else {
System.out.println("Count of characters in editText string : " + editTextString.length());
}
Output for above condition will be :
Count of strings seperated by comma : 4
Count of commas : 3
Suppose if your string is "abcefgpqrxyz" i.e. without comma then it will execute else part and print characters count as 12 in this case
Count of characters in editText string : 12
Your question statement is so ambiguous. Elaborate it completely and explain your end result with example. It's regarding string functions, I can give you the answer about it if I understand it :) :D
thanks for that i got that answer like that.
String varStr = editextContact.getText().toString();
//int VarCount = editextContact.getText().length();
int countStringsSeperatedByComma = varStr.split(",").length;
String convet=String.valueOf(countStringsSeperatedByComma);
textViewConCount.setText(varStr);
if (varStr.length() == 0){
textViewConCount.setText("0");
}else {
textViewConCount.setText(convet);
}

Is it possible to use adb commands to click on a view by finding its ID?

Suppose I have an app (in debug/release build , made by me or not), which has an ID for a specific view.
Is it possible to call adb command to click on this view?
I know it's possible to make it click on a specific coordinate, but is it possible to use the ID instead ?
I ask this because I do know that the "Layout Inspector" tool (available via Android Studio) and the "View hierarchy" tool (available via "Android Device Monitor", previously used via DDMS) can show the ids of the views (and even their coordinates and bounding box), so maybe it can be a better way to simulate touches when performing some automatic tests.
I can use a rooted method if needed.
EDIT: I've set a bounty in case there is an easier/better way than what I've written in my own answer, which was to parse the result of "adb shell dumpsys activity top" .
I would like to know if it's possible to get the views coordinates (and sizes of course) that are shown on the screen, including as much information about them (to identify each).
This should be possible via the device too. Maybe something that has the same output data of what's available from the "monitor" tool :
Notice how it can get the basic information of the views, including the text, the id, and the bounds of each.
As I've read, this might be possible via AccessibilityService, but sadly I can't understand how it all works, what are its capabilities, how to trigger it, what are its requirements, etc...
Using what #pskink explained in the comments above, here's how I achieved this:
First, I ran this command:
adb shell dumpsys activity top
Then, I used this code to parse it:
public class ViewCoordsGetter {
public static Rect getViewBoundyingBox(String viewIdStr) {
final List<String> viewHierarchyLog = //result of the command
for (int i = 0; i < viewHierarchyLog.size(); ++i) {
String line = viewHierarchyLog.get(i);
if (line.contains(":id/" + viewIdStr + "}")) {
Rect result = getBoundingBoxFromLine(line);
if (i == 0)
return result;
int currentLineStart = getStartOfViewDetailsInLine(line);
for (int j = i - 1; j >= 0; --j) {
line = viewHierarchyLog.get(j);
if ("View Hierarchy:".equals(line.trim()))
break;
int newLineStart = getStartOfViewDetailsInLine(line);
if (newLineStart < currentLineStart) {
final Rect boundingBoxFromLine = getBoundingBoxFromLine(line);
result.left += boundingBoxFromLine.left;
result.right += boundingBoxFromLine.left;
result.top += boundingBoxFromLine.top;
result.bottom += boundingBoxFromLine.top;
currentLineStart = newLineStart;
}
}
return result;
}
}
return null;
}
private static int getStartOfViewDetailsInLine(String s) {
int i = 0;
while (true)
if (s.charAt(i++) != ' ')
return --i;
}
private static Rect getBoundingBoxFromLine(String line) {
int endIndex = line.indexOf(',', 0);
int startIndex = endIndex - 1;
while (!Character.isSpaceChar(line.charAt(startIndex - 1)))
--startIndex;
int left = Integer.parseInt(line.substring(startIndex, endIndex));
startIndex = endIndex + 1;
endIndex = line.indexOf('-', startIndex);
endIndex = line.charAt(endIndex - 1) == ',' ? line.indexOf('-', endIndex + 1) : endIndex;
int top = Integer.parseInt(line.substring(startIndex, endIndex));
startIndex = endIndex + 1;
endIndex = line.indexOf(',', startIndex);
int right = Integer.parseInt(line.substring(startIndex, endIndex));
startIndex = endIndex + 1;
//noinspection StatementWithEmptyBody
for (endIndex = startIndex + 1; Character.isDigit(line.charAt(endIndex)); ++endIndex)
;
int bot = Integer.parseInt(line.substring(startIndex, endIndex));
return new Rect(left, top, right, bot);
}
}

Android: Count strings and drawables

I'm circulating some drawable images (fx. I have a few images named image_1, image_2 etc.) as header images in a fragment. The images are loaded randomly as I hardcode the number of images available for me, and generate a random index from 0 to this number.
mHeaderBackgroundImagesCount is a final:
private int getHeaderBackground() {
// Random index between 0 and mHeaderBackgroundImagesCount
Random rand = new Random();
int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1;
return getResources()
.getIdentifier("image_" + index, "drawable", getPackageName());
}
As hard coding anything isn't normally the way to go in correct programming, I therefore like to dynamically find out how many 'image_X' drawables I have and set it to mHeaderBackgroundImagesCount.
I would like to do the same with strings from the strings.xml resource file as I'm also circulating some strings on every page load.
Solution Update
This update is inspired by Lalit Poptani's suggestion below. It includes syntax corrections and optimizations and have been tested to work.
private int countResources(String prefix, String type) {
long id = -1;
int count = -1;
while (id != 0) {
count++;
id = getResources().getIdentifier(prefix + (count + 1),
type, getPackageName());
}
return count;
}
System.out.println("Drawables counted: " + countResources("image_", "drawable"));
System.out.println("Strings counted: " + countResources("strTitle_", "string"));
Note: This method assumes that the resources counted start with index 1 and have no index holes like image_1 image_2 <hole> image_4 etc. because it will terminate on first occasion of id=0 thus resulting a faulty count.
If you are sure that your list of drawables will be in a sequence of image_1, image_2,... and so on then you can apply below logic,
int count = 0;
int RANDOM_COUNT = 10; //which is more than your drawable count
for (int i = 1; i < RANDOM_COUNT; i++){
int id = getResources().getIdentifier("ic_launcher_"+i,
"drawable", getPackageName());
if(id != 0){
count = + count;
}
else{
break;
}
}
Log.e(TAG, "This is your final count of drawable with image_x - "+ count);
You use this logic because of there will be no drawable with any name as image_x then id will be 0 and you can break the loop
I am not sure if it's possible to dynamically get the number of resources or drawables.
A way to circumvent this issue is to use string arrays as resources in strings.xml.
e.g.
<resources>
<string-array name="foo_array">
<item>abc1</item>
<item>abc2</item>
<item>abc3</item>
</string-array>
int count = getResources().getStringArray(R.array.foo_array).length;

Android: Int stays the same

i feel dumb for asking this but i have been fighting with this for a day now and i can't seem to get it working.
So my problem is I want to keep adding 1 to and integer and make it go like ;
1+1=2
2+1=3
That it keeps updating the Integer I have this now;
int val = 1;
int g = 1;
val = g + val;
But it keeps saying its 2 how come?
Thanks.
I'm guessing you put all of your code in your click handler. Instead, put the variable declaration/initialization in the class level and only your addition code in your click handler. Rough code as follows:
public YourActivity extends Activity {
int val = 1;
int g = 1;
#Override
protected void onCreate (Bundle savedInstanceState) {
... //find button in here
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
val = g + val;
}
});
}
}
Because you keep setting it to 1. Initialize it outside the loop.
int val = 1;
int g = 1;
The next line:
val = g + val;
is therefore equivalent to
val = 1 + 1;
which is equivalent to
val = 2;
Not sure what you would expect here...
int val = 1; int g = 1; val = g + val;
Will always evaluate to 2. Because what happens is you take the value in g which is 1 and the value in val which is 1. This produces the sum of 2. You then take 2 and assign it to the variable val (which previously was initialized to 1).
1+1 will always be 2 (in Integer mathematics)
So my problem is I want to keep adding 1 to and integer and make it go like ;
1+1=2
2+1=3
I'm guessing you want to do something like this, to produce your output a given number of times.
int timesToLoop = 10;
int summedUp = 0;
for (int i=0; i < timesToLoop; i++)
{
summedUp = i + 1;
System.out.println(i + " + " + "1 = " + summedUp);
}

Android Phrase o-matic

I'd like to port this little program to Android, thing is that im level basic -1 at android, what the program does is that it randomly creates a phrase taken from strings in an array. I know how to make a button to show me an xml from the layout resources but thatjust works with textviews that do not change, Could you please tell me which steps to follow in order to display a randomly generated string taken from the array of strings?
heres the code(head first java):
public class PhraseOMatic
{
public static void main (String[] args)
{
String[] wordListOne = {"24/7", "multi-tier", "30,OOO foot", "B-to-B" , "win-win" , "frontend", "web- based" , "pervasive", "smart", "sixsigma", "critical-path", "dynamic"};
String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded", "outaide-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};
String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare", "portal", "space", "vision", "paradigm", "session"};
// find out how many words are in each list
int oneLenqth = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.length;
// generate .... random numbers
int randl = (int) (Math.random() * oneLenqth);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);
//now build a phrase
String phrase = wordListOne[randl] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];
// print out the phrase
System.out.println("What we need is a " + phrase);
}
}

Categories

Resources