This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
How to remove the last character from a string?
(37 answers)
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 2 years ago.
I am making the calculator app.
I tried to make the delete button, but there are errors.
(1) If I press backspace when there is no number, the app closed suddenly.
(2) If I press a new number after deleting the number, the previous deleted number shows up again.
I searched a lot about it but I cannot understand them as a beginner.
I would appreciate it if you can explain it easily.
public class MainActivity extends AppCompatActivity {
TextView workingsTV;
TextView resultsTV;
String workings = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextView();
}
private void initTextView()
{
workingsTV = (TextView)findViewById(R.id.workingsTextView);
resultsTV = (TextView)findViewById(R.id.resultTextView);
}
private void setWorkings(String givenValue)
{
workings = workings + givenValue;
workingsTV.setText(workings);
}
public void equalsOnClick(View view)
{
Double result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (Double) engine.eval(workings);
if (result != null)
{
int intVal = (int) result.doubleValue();
if (result == intVal)
{//Check if it's value is equal to its integer part
resultsTV.setText(String.valueOf(intVal));
}
else
{
resultsTV.setText(String.valueOf(result));
}
}
}
catch (ScriptException e) {
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
}
public void deleteOnClick(View view)
{
String del_number = workingsTV.getText().toString();
workingsTV.setText(del_number.substring(0,del_number.length() - 1));
}
Problem 1 is because del_number.length() is 0, so del_number.length()-1 is -1 which is an illegal parameter to substring. The easiest way to fix it is to not do anything if the length is 0.
Problem 2 is because you don't reset the variable workings when you delete. It needs to be set to "". Or don't have that variable at all and always use the workingsTV.getText() be the source of truth.
I found the solution.
I edit the code like this to prevent the app closed suddenly.
public void deleteOnClick(View view) {
if(workingsTV.getText().toString().length() >= 1) {
String getResultText = workingsTV.getText().toString();
String subString = getResultText.substring(0, getResultText.length() -1);
workingsTV.setText(subString);
}
else
{
workingsTV.setText(CLEAR_INT_TEXT);
}
}
But still I had a problem that the letter I deleted comes back when I press a new number.
The solution was this.
workings = workings.substring(0, workings.length() -1);
The letter at workings should be deleted as well like workingsTV
So here is full code for delete
public void deleteOnClick(View view) {
if(workingsTV.getText().toString().length() >= 1) {
String getResultText = workingsTV.getText().toString();
String subString = getResultText.substring(0, getResultText.length() -1);
workingsTV.setText(subString);
workings = workings.substring(0, workings.length() -1);
}
else
{
workingsTV.setText(CLEAR_INT_TEXT);
}
}
Related
This question already has answers here:
How to Delete Item Without Deleting Position in Recycler View?
(2 answers)
Closed 4 years ago.
I am trying to count clicks based on getAdapterPosition(). And it works properly. Below the code
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
if (clickcount <= 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
} // onClick
But when I am trying to count clicks using the comparison of two string, I got the problem. The result is, the computer can only count that once. Can you help me to fix the problem? The problem lays here:
public Button tombolbaca;
private int klik10 = 10;
#Override
public void onClick(View v) {
tombolbaca = (Button) v.findViewById(R.id.buttonbaca);
// Problem here
if( tombolbaca.getText().toString().equals("Baca 10x") ) {
klik10--;
tombolbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
}
} // onclick
Ok, got it now.
The problem is in logics: this is your code, written by text instead of code
if( tombolbaca.getText().toString().equals("Baca 10x"){ // this line says "if the text is exactly Baca 10x, go on"
klik10--; // this line says: "make the value of klik10 = klik10 -1
tombolbaca.setText("Baca " + klik10 + "x"); //this line says "set text of tombolbaca as the composition of the strings and the value of klik10
if (klik10 <= 0) //if klik10 is equal or less than 0, do this
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
So, the problem lays here:
First iteration:
klik10 = 10
it enter the first if
klik10 will now be 9
text will be Baca 9x
not less than 1, so skip the if
Second iteration
klik10 = 9 (because you set it before)
not going into if
so, the problem is that you are going in only if text is Baca 10x, but after the first iteration it won't be that anymore.
A solution could be this:
#Override
public void onClick(View v) {
klik10--;
tombolbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
}
The if, as it is written, is not necessary. you can just remove it and the code will work.
If not, tell me why there is the if clause and I will fix above code :)
PS:
If you want to check if the text is the correct counter, do the following if:
if(tombolbaca.getText().String().equals("Baca " + klik10.toString() + "x"){
...
In second attempt the comparation will be between "Baca 9x".equals("Baca 10x") and your if statement not will work
Try as follow
if( !tombolbaca.getText().toString().equals("Baca 0x") ) { //using "Baca 0x"
...
}
This question already has an answer here:
EditText Minimum Length & Launch New Activity
(1 answer)
Closed 8 years ago.
I am a new developer on Android and Java. How can I make at least 10 characters in EditText ? Also, when the user enter a value less than 10, the application send an error message on screen. How can I do these ? [ edittext > = 10 ]
Use something like this:
EditText et = (EditText) findViewById(YOUR_EDITTEXT);
String s = et.getText().toString();
if(s.length() <= 10){
et.setError("Must exceed 10 characters!");
} else {
// ...
}
You can do that in several ways, but you can try this way:
if (myEditText.getText().length() < minLength) {
//Your message to there is no enough caracters
} else {
//Your action if it is satisfied.
}
You can set minLenght to 10, or whatever, or simply ask if value is less than 10.
I hope that you get idea from this.
You can use text watcher to check the user input and decide what to do inside
EditText editText = new EditText(this);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Yo can validate your TextView and if it doesn't fit your requirements, use myTextView.setError(String) to show an error.
If not you will have to implement myTextView.addTextChangedListener(...) and do things manually.
Hope it helps.
I am making a basic calculator for Android in Java. I am stuck in one final step where it must add the input with the previous input. Have a look at the code:
public void displayValue(){
String mything = display.getText().toString();
input = Integer.parseInt(mything);
}
public void number1(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(1));
displayValue();
}
public void number2(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(2));
displayValue();
}
public void plus(View view){
displayValue(); //result= 0
result = result + input; //result= input
input = 0; //input=0
//in this step input becomes 0 to let the user enter new number input but this
//input never add the old result and the equal shows the old result.
}
public void equal(View view){
displayValue();
display.setText(Integer.toString(result));
}
I noticed that if I add a line in equal method and add the result to input I get the correct answer but that's not gonna be helpful as there will be minus button too.
Any ideas?
Thanks.
It's definitely hard to tell because you don't include full code, which would be helpful, but could it be because you call displayValue(); in some places before doing the math? Specifically in the plus method.
Ok finally I came up with a solution.
As the only option for calculation of result and new input is in equal method (because logically when user press the equal button, so wants to ends the equation), so I added two boolean values for each minus and plus calculation. Then I added both calculation for adding or minus 2 values.
Then when the user inter first part of the calculation and then hit plus sign, the boolean value of plus becomes true and after entering new input and hitting the equal sign, it does the true part of the calculation. Well it is a bit hard to explain but i guess by looking at the code you would get what I mean.
boolean whenMinus = false;
boolean whenPlus = false;
public void plus(View view){
displayValue();
result = input;
input = 0;
whenPlus = true;
}
public void minus(View view){
displayValue();
result = input;
input = 0;
whenMinus = true;
}
public void equal(View view){
if (whenPlus == true){result = result + input; whenPlus = false;}
if (whenMinus == true){result = result - input; whenMinus = false;}
display.setText(Integer.toString(result));
}
I am not sure if it is the correct way of making this calculator. But I fixed my problem anyway. It would be great to comment me and let me know if it is the standard way or its kinda hacking. I am not a pro anyway.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Syntax Question IF ELSE (Java)
I am trying to make a calculator which shows a message if no value is entered in editbox. But it FC's!! I am making apps after long time so I am quite confused.
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
double a=0;
double b=0;
double c=0;
EditText edit;
EditText edit2;
TextView edit3;
String lname="";
edit=(EditText)findViewById(R.id.edit);
edit2=(EditText)findViewById(R.id.edit2);
edit3=(TextView)findViewById(R.id.edit3); // everything defined above
String editstr= edit.getText().toString(); // real work starts
if(editstr.contentEquals(lname))
edit3.setText("Enter value");
else
a=Double.parseDouble(edit.getText().toString()); // else add the stuff
b=Double.parseDouble(edit2.getText().toString());
c=a+b;
edit3.setText(Double.toString(c));
} };
put brackets around your if-else, currently in case of else it only executes the first line, other lines are executed no matter if your if passes or fails.
if(editstr.contentEquals(lname)) {
edit3.setText("Enter value");
} else {
a=Double.parseDouble(edit.getText().toString()); // else add the stuff
b=Double.parseDouble(edit2.getText().toString());
c=a+b;
edit3.setText(Double.toString(c));
}
As written, only the a=Double.parseDouble(edit.getText().toString()); is affected by the else. If you want the rest of it there, surround the block in {}
It does work, it just never fires.
You should do
if(editStr.isEmpty())
editStr = "Enter value";
else
{
//editStr.equals("someValue"); //test against some value
//rest
}
This question already has answers here:
Android, getting resource ID from string?
(14 answers)
Closed 9 years ago.
public void correctLetter(String Letter, int pos){
if(letter.equals("a")){
ImageView image = images[pos];
image.setImageResource(R.drawable.a);
image.setVisibility(ImageView.VISIBLE);
}
At the moment i got a method looking like this. But, when i got 26 letters, thats going to be a lot of ifs.
Anyone got an idea how i can change that? I tried doing something like this, but the setImageResource required int anyways.
public void correctLetter(String letter, int pos) {
char newLetter = letter.toCharArray()[0];
String startS = "R.drawable." + letter;
startS += Character.toString(newLetter);
ImageView image = images[pos];
image.setImageResource(startS);
image.setVisibility(ImageView.VISIBLE);
}
You can init startS by this way:
int startS = getResources().getIdentifier(letter, "drawable","com.yourpackage.name");
You can keep the resource ids for the images in a static int array and index into it while calling setImageResource(). Please refer to the code below
private static final int charImgIds[] = { R.drawable.a, R.drawable.b, ... , R.drawable.z };
public void correctLetter(String letter, int pos) {
int letterIndex = letter.toCharArray()[0];
ImageView image = images[pos];
image.setImageResource(charImgIds[letterIndex]);
image.setVisibility(ImageView.VISIBLE);
}