subtracting integer from string textview - android

I'm trying to replace a textview that has the contents "330" after either some addition or subtraction has occurred with fixed numbers.
for example
int points = 75
totalPoints = totalPoints - points
I think I have managed to get the data from the string and convert it into an integer but i am having trouble putting the result back into the textview
this is what i have tried so far but get a result of 2131230752
TextView tmpTxtview = (TextView) findViewById(R.id.premPoints);
int adjustPoints = Integer.valueOf(R.id.premPoints);
switch (v.getId()) {
case R.id.premTeam1:
points = 75;
adjustPoints = adjustPoints - points;
tmpTxtview.setText(String.valueOf(adjustPoints));
break;
case R.id.premTeam2:
points = 74;
adjustPoints = adjustPoints - points;
tmpTxtview.setText(String.valueOf(adjustPoints));
break;
}

Change this:
int adjustPoints = Integer.valueOf(R.id.premPoints);
into this:
int adjustPoints = Integer.valueOf(tmpTextview.getText());
(if it doesn't work, use tmpTextview.getText().toString() instead).

Related

Randomly Switch Case

Hello friends I have 2 situation but I want to do it randomly. When user click button then there is 2 situation case0 or case1 randomly changes. So text's are randomly changes too...
*lastImageName and lastImageName2 are variable strings...
Random rand = new Random();
int newrand = rand.nextInt(1) + 1;
switch(newrand) {
case 0:
text1.setText(lastImageName);
text2.setText(lastImageName2);
break;
case 1:
text1.setText(lastImageName2);
text2.setText(lastImageName);
break;
}
But that's not working sometimes.. What's the rand. problem?
Random rand = new Random();
int a = 0;
int b = 1;
int c = random.nextBoolean() ? a : b;
Remove the +1. Just do that: int newrand = rand.nextInt(2);
Random#nextInt(int) generates a random number between 0 inclusive and the upper bound exclusive. I.e., nextInt(1) will always return 0. Instead, you should just use:
int newrand = rand.nextInt(2);
If you only have two cases then use
boolean state = rand.nextBoolean();
text1.setText(state?lastImageName:lastImageName2);
text2.setText(state?lastImageName2:lastImageName);
For multiple you can also use
Random rand = new Random();
int newrand = rand.nextInt() % count;//count = 2 for your case
switch(newrand) {
case 0:
text1.setText(lastImageName);
text2.setText(lastImageName2);
break;
case 1:
text1.setText(lastImageName2);
text2.setText(lastImageName);
break;
}

How to convert double to int in Android? [duplicate]

This question already has answers here:
Converting double to integer in Java
(3 answers)
Closed 6 years ago.
I just wants to convert from double to int in my UI i am rendering as a double but for the backend i want convert to integer.
Double d = 45.56;
OutPut = 4556;
Please can anybody tell me how to get the value in this format.
Try this way, Courtesy
double d = 45.56;
int i = (int) d;
For better info you can visit converting double to integer in java
If you just want to convert the Double to int,
Double D = 45.56;
int i = Integer.valueOf(D.intValue());
//here i becomes 45
But if you want to remove all decimal numbers and count the whole value,
//first convert the Double to String
double D = 45.56;
String s = String.valueOf(D);
// remove all . (dots) from the String
String str = str.replace(".", "");
//Convert the string back to int
int i = Integer.parseInt(str);
// here i becomes 4556
You are using the Double as object(Wrapper for type double). You need to fist convert it in to string and then int.
Double d=4.5;
int i = Integer.parseInt(d.toString());
If you want it in the Integer Object Wrapper then can be written as
Integer i = Integer.parseInt(d.toString());
EDIT
If you want to get the desired result -
You can go like this-
Double d = 4.5;
double tempD = d;
int tempI = (int) tempD * 100;
//Integer i = tempI;
try this code
double d = 45.56;
String temp = String.valueOf(d);
if (temp .contains(".")) {
temp = temp .replaceAll(".","");
}
// After if you want to convert to integer then
int output = Integer.parseInt(temp);

SetImageResource random value not work

I want to get RANDOM value in my function, But n always equals 0. What am I doing wrong?
image = (ImageView) findViewById(R.id.imageView1);
//блок Random
Log.d(Tag, "1");
int NUM_IMAGES=7;
int imageArr[] = new int[NUM_IMAGES];
Log.d(Tag, "2");
imageArr[0] = R.drawable.image1;
imageArr[1] = R.drawable.image2;
imageArr[2] = R.drawable.image3;
imageArr[3] = R.drawable.image4;
imageArr[4] = R.drawable.image5;
imageArr[5] = R.drawable.image6;
imageArr[6] = R.drawable.image7;
Log.d(Tag, "3");
int n = (int)Math.random()*NUM_IMAGES;
Log.d(Tag, "n="+n);
image.setImageResource(imageArr[n]);
(int) Math.random() is executed first and will always return 0. Then multiplying NUM_IMAGES by 0 still returns 0.
You should add brackets around your expression so the conversion to int will be done after the multiplication :
int n = (int) (Math.random()*NUM_IMAGES);
If you read here, the priority of type cast is more than that of multiplication. Also the priority of ()(bracket) is higher than that of type cast. So the right way might be to put multiplication in bracket so that multiplication happens before casting. Something like:
int n = (int)(Math.random() * NUM_IMAGES);
Notice the brackets. Hope this helps.

Display decimals with a textview

Hi i want make so the TextView level can put out decimal but i don'ty know how to do that any one got an idea? NOw it only puts out 1 but i want it to put out 1.80. :)
public class Main extends Activity {
int counter;
EditText weight, hours;
TextView amount, level;
Button calcuate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
weight = (EditText) findViewById(R.id.weight);
hours = (EditText) findViewById(R.id.hours);
amount = (TextView) findViewById(R.id.amount);
level = (TextView) findViewById(R.id.alcohol_level);
calcuate = (Button) findViewById(R.id.calcuate);
final String widmark = getResources().getString(
R.string.widmark);
final String hundra = getResources().getString(
R.string.hundra);
final String cl = getResources().getString(
R.string.cl);
calcuate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer wid, mgs;
String w = weight.getText().toString();
String h = hours.getText().toString();
wid = Integer.parseInt(w) * Integer.parseInt(widmark) / Integer.parseInt(hundra);
mgs = Integer.parseInt(cl) / Integer.parseInt(wid.toString()) / Integer.parseInt(hundra);
level.setText(mgs.toString());
}
});
}
}
Your mgs variable is a Integer object. Set it to type float to have decimal places be displayed.
float mgs = Integer.parseInt(cl) / Integer.parseInt(wid.toString()) / Integer.parseInt(hundra);
I hope this helps.
int division will only produce int's. If you want your output to be of float or double type, you must use double or float division.
Double mgs;
mgs = Double.parseDouble(cl) / Double.parseDouble(wid.toString()) / Double.parseDouble(hundra);
Note that not all variables considered in the expression need to be double's, only one of them does.
Another thing that is noteworthy here is whether or not you want two decimal places (assuming a currency here). By default, Java/Android will only spit out as many decimal places as necessary. 1.80 will display as 1.8. To alleviate this, you should use a NumberFormat (specifically, use NumberFormat.getCurrencyInstance()) so that you can specify that you want the number of decimals for your default Locale's currency.

How to find android TextView number of characters per line?

So I have a TextView in android that has the width of the whole length of the screen and a padding of dip 5. How can I calculate the number of characters that will fit a single line on the screen? I guess in other words, I'm trying to get the number of columns of a textview?
I considered manual calculation depending on textsize and width, but 1) don't know the correlation and 2) due to the padding in the units of dip, different screens will use different number of actual pixels to pad.
Overall Question: I am trying to use this to solve: if given a string how can I manually edit to string such that when the textview prints the string character by character, I will know when to start a word that won't fit on one line on the next. Note: I know that textview automatically puts words that won't fit onto the next line, however, since I'm printing character by character, like typing animation, textview doesn't know the word won't fit until it prints out the overflowing characters of that word.
Been searching everywhere for this...
Thanks!
Added solutions:
one possible solution:
public String measure2 (TextView t, String s) {
String u = "";
int start = 0;
int end = 1;
int space = 0;
boolean ellipsized = false;
float fwidth = t.getMeasuredWidth();
for(;;) {
//t.setText(s.substring(start, end));
float twidth = t.getPaint().measureText(s.substring(start, end));
if (twidth < fwidth){
if (end < s.length())
end++;
else {
if (!ellipsized)
return s;
return u + s.subSequence(start, end);
}
}
else {
ellipsized = true;
space = (u + s.substring(start, end)).lastIndexOf(" ");
if (space == -1)
space = end - 1;
u += s.subSequence(start, space) + "\n";
start = space + 1;
end = start + 1;
}
}
}
solution 2, but still uses solution1 sometimes:
public String measure3 (TextView t, String s) {
List<String> wlist = Arrays.asList(s.split(" "));
if (wlist.size() == 1)
return measure2(t, s);
String u = "";
int end = 1;
float fwidth = t.getMeasuredWidth();
for(;;) {
//t.setText(s.substring(start, end));
if (wlist.isEmpty())
return u;
String temp = listStr(wlist, end);
float twidth = t.getPaint().measureText(temp);
if (twidth < fwidth){
if (end < wlist.size())
end++;
else {
return u + temp;
}
}
else {
temp = listStr(wlist, end-1);
if (end == 1)
temp = measure2(t, temp);
if (wlist.isEmpty())
return u + temp;
else
u = u + temp + "\n";
wlist = wlist.subList(end - 1, wlist.size());
end = 1;
}
}
}
public String listStr (List<String> arr, int end) {
String s = "";
for (String e : arr.subList(0, end) ){
s = s + e + " ";
}
return s.trim();
}
I used the above code to generate off a original string s, a string u that would be printed. However, I think this approach is very inefficient. Is there another approach or a better algorithm? Note: there are some errors in measure3 that I fixed, but was too lazy to edit
Try this:
private boolean isTooLarge (TextView text, String newText) {
float textWidth = text.getPaint().measureText(newText);
return (textWidth >= text.getMeasuredWidth ());
}
Detecting how many characters fit will be impossible due to the variable width of the characters. The above function will test if a particular string will fit or not in the TextView. The content of newText should be all the characters in a particular line. If true, then start a new line (and using a new string to pass as parameter).
Answer to the comment:
because the app can be run in many systems is exactly why you need to measure it.
This is a way to solve your "overall question". What is the difference between using str.size()>numCol vs is too large? You will need to implement your animation (hint #1: insert a newline character)
as I said before when you start a new line, you start a new string (hint #2: if you extend TextView, you can implement all this in overriding setText). (hint #3: Keep track of the lines created with a static int lines; and use newString.split("\\r?\\n")[lines-1] to check for length).
You can get total line of Textview and get string for each characters by below code.Then you can set style to each line whichever you want.
I set first line bold.
private void setLayoutListner( final TextView textView ) {
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
final Layout layout = textView.getLayout();
// Loop over all the lines and do whatever you need with
// the width of the line
for (int i = 0; i < layout.getLineCount(); i++) {
int end = layout.getLineEnd(0);
SpannableString content = new SpannableString( textView.getText().toString() );
content.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, end, 0);
content.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), end, content.length(), 0);
textView.setText( content );
}
}
});
}
Try this way.You can apply multiple style this way.
I had the same issue and I calculated the number characters per line by 2 steps:
Step 1: Calculate the number of lines
val widthOfTvComment = widthOfScreen - marginLeft - marginRight
var bounds = Rect()
var paint = Paint()
paint.textSize = textSize
paint.getTextBounds(comment,0,comment.length,bounds)
val lines = ( bounds.width()/widthOfTvComment)
Step 2: Calculated the number characters per line
val charactersPerLine = comment.length / lines

Categories

Resources