App keeps crashing after clicking button in emulator [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Whenever i run the app, enter the name and press the submit button the app crashes.Here's the code
public class MainActivity extends AppCompatActivity {
int x, sum=0;
String str,str2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Button chk = findViewById(R.id.check);
final Button sub = findViewById(R.id.submit);
final EditText name = findViewById(R.id.name);
chk.setEnabled(false);
sub.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
x = str.length();
str = name.getText().toString();
if (x >= 4 && x <= 10)
chk.setEnabled(true);
}
});
And here's the xml code for the submit button
<Button
android:id="#+id/submit"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
I'm a beginner and it's my first app so please excuse me if you find it a naïve question.
The following is the logcat message:
12-11 22:55:20.678 4277-4277/com.example.shantanu.namerank D/AndroidRuntime: Shutting down VM
12-11 22:55:20.702 4277-4277/com.example.shantanu.namerank E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shanu.namerank, PID: 4277
java.lang.NullPointerException: Attempt to invoke virtual method 'int'java.lang.String.length()' on a null object reference
at com.example.shanu.namerank.MainActivity$1.onClick(MainActivity.java:32)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

x = str.length();
str = name.getText().toString();
these lines are disordered. Put the first line second and second line first.

Looks like str variable is null because you didn't initialize it, but please post your logcat output to confirm it.

The problem is in the onClick() function:
public void onClick(View view) {
x = str.length(); // length of 'str' calculated first
str = name.getText().toString(); // 'str' initialized later
if (x >= 4 && x <= 10)
chk.setEnabled(true);
}
You are calculating length of str before initializing it.
The code should be:
public void onClick(View view) {
str = name.getText().toString();
x = str.length();
if (x >= 4 && x <= 10)
chk.setEnabled(true);
}
First, initialize the varible str and then calculate the length of str.
Hope that helps :)

Related

Inputting Array In Multiline Text In Android

I am new to android and am trying to make an app where the user inputs an array in a text box with inputType = textMultiLine. The problem is that I want to make it so that whenever user hits enter, the app takes input of the next array element and not treat the entire text in the textbox as one element. The code is as below :
EditText input = findViewById(R.id.inputtext);
Button show = findViewById(R.id.button);
TextView output = findViewById(R.id.output);
String [] name = new String[3];
for (int i = 0 ; i < 3 ; i++)
{
name[i] = input.getText().toString();
output.setText(name[i]);
}
But whenever i try to take name[1] after hitting enter the app doesnt treat the next line as name[2] but instead treats it as name[1]. For example if type the names john,steve and frank, then i should get an array that is like this :
name[0] = john
name[1] = steve
name[2] = frank
but instead whenever I typejohn,press enter,type steve, press enter and type frank the app treats it as :
name[0] = john
steve
frank
also if i set the output to something like this :
output.setText(name[i] + i)
instead of getting an oupt like this :
john 0
steve 1
frank 2
I get an output like this :
john
steve
frank2
Any and all help would be much appreciated.
Thanks
======================================================================================================================================================
EDIT 1
I tried this code but didn't work:
String name[] = input .getText().toString().split("\\r?\\n");
for (int i = 0 ; i < name.length; i++)
{
output.setText(name[i]);
}
Still get only frank when I input john,steve and frank
If you want to put each line to different array item :
String [] name = input.getText().toString().split("\n");
input.getText().toString() gives you string containing whole EditText content with lines separated by new line - "\n". You need to split this string to get each line.
try below code
String name[] = input .getText().toString().split("\\r?\\n");
String disp="";
for (int i = 0 ; i < name.length; i++)
{
disp += name[i] +"\n";
}
output.setText(disp);
Maybe the following example will be useful:
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/edit_text"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginBottom="100dp"
android:inputType="textMultiLine"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show"/>
<TextView
android:id="#+id/text_view"
style="#style/Widget.AppCompat.EditText"
android:layout_width="300dp"
android:layout_height="wrap_content"/>
</LinearLayout>
Java Code
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
final String newLine = System.getProperty("line.separator");
final String[] inputText = inputString.split(newLine);
String outputText = "";
for (int i = 0; i < inputText.length; i++) {
outputText += inputText[i];
if (i != inputText.length - 1) {
outputText += newLine;
}
}
output.setText(outputText);
}
}
});
}
You can download de APK here or here the complete source code
(another way:simple!) In the following code it is not necessary to make a split on the input text.
final EditText input = findViewById(R.id.edit_text);
final Button show = findViewById(R.id.button);
final TextView output = findViewById(R.id.text_view);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String inputString = input.getText().toString();
if (!TextUtils.isEmpty(inputString)) {
output.setText(inputString);
}
}
});
Note that, your code is wrong, because in for each loop, you override the text was setted in the previous loop.

java.lang.NumberFormatException: Invalid int: android.support.v7.widget.AppCompatEditText

I wrote this code in order to simplify part numbers in math e.g. 2a/2b = a/b. android studio shows no problems but when i run this code: (maz stands for lowest number, liels stands for highest number, skait is the 2a in the previous example and sauc is the 2b int the previous example, skaitout and saucout are the output text fields corresponding to the part number parts, skaitout is the top number and saucout is the bottom number)
package com.example.mikus.simplify;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View skait = findViewById(R.id.skait);
View sauc = findViewById(R.id.sauc);
TextView skaitout = (TextView) findViewById(R.id.skaitout);
TextView saucout = (TextView) findViewById(R.id.saucout);
int maz;
int liels;
int x;
int i = 0;
maz = Integer.parseInt(skait.toString());
liels = Integer.parseInt(sauc.toString());
if(maz > liels){
x = maz;
maz = liels;
liels = x;
i = 1;
}
if(maz == liels){
skaitout.setText('1');
saucout.setText('1');
}else{
x = maz;
while(true){
if(maz % x == 0 && liels % x == 0){
maz /= x;
liels /= x;
x = maz;
}else{
if(x == liels){
return;
}else{
x++;
}
}
}
}
if (i == 0) {
skaitout.setText(maz);
saucout.setText(liels);
}
if(i == 1){
skaitout.setText(liels);
saucout.setText(maz);
}
}
}
i get the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mikus.simplify, PID: 24905
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mikus.simplify/com.example.mikus.simplify.MainActivity}: java.lang.NumberFormatException: Invalid int: "android.support.v7.widget.AppCompatEditText{11f3506 VFED..CL. ......ID 0,0-0,0 #7f0b0057 app:id/skait}"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3352)
at android.app.ActivityThread.access$1100(ActivityThread.java:223)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1797)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7231)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NumberFormatException: Invalid int: "android.support.v7.widget.AppCompatEditText{11f3506 VFED..CL. ......ID 0,0-0,0 #7f0b0057 app:id/skait}"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:410)
at java.lang.Integer.parseInt(Integer.java:367)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.mikus.simplify.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:6877)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3352) 
at android.app.ActivityThread.access$1100(ActivityThread.java:223) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1797) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7231) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
in phone the program just crashes. can anyone help me.
You try to convert a view to string and parse this to integer:
liels = Integer.parseInt(sauc.toString());
maz = Integer.parseInt(skait.toString());
I guess you want to do something like this:
liels = Integer.parseInt(sauc.getText().toString());
maz = Integer.parseInt(skait.getText().toString());
Also, it´s possible that the user make some wrong input. You could catch the exception if the input is not a number like:
try{
liels = Integer.parseInt(sauc.getText().toString());
maz = Integer.parseInt(skait.getText().toString());
}catch(NumberFormatException ex){
//inform the user about wrong input
}
or you can restrict user input to only numbers by setting this attribute to editTexts:
android:inputType="number"
And be aware: Later you will get also exceptions by setting the text:
if (i == 0) {
skaitout.setText(maz);
saucout.setText(liels);
}
if(i == 1){
skaitout.setText(liels);
saucout.setText(maz);
}
This will throw an exception, you have to cast the integer to a string like:
if (i == 0) {
skaitout.setText(Integer.toString(maz));
saucout.setText(Integer.toString(liels));
}
if(i == 1){
skaitout.setText(Integer.toString(liels));
saucout.setText(Integer.toString(maz));
}
or just for example with some quitation marks:
saucout.setText(""+maz);
You're trying to parse View as int.

My apps keeps crashing when button is pressed and EditText is empty [duplicate]

This question already has answers here:
Proper way to avoid parseInt throwing a NumberFormatException for input string: ""
(7 answers)
Closed 6 years ago.
I've tried lot of things found here, but it keeps crashing. I wanna know what do i need to add in order to show a Toast message when button is clicked and EditText is empty.
INFO: The app is supposed to send the two values in the EditText's to another activity, showing Toast's in the following exceptions:the first value higher than 6; the second value higher than (firstvalue*14); and if the fields are empty (which is my problem)
Here's my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView saludo_bienvenida;
EditText et1_creditos;
EditText et2_faltas;
Button boton_ingresar;
Button boton_info;
String numero_creditos;
String numero_faltas_actuales;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saludo_bienvenida = (TextView) findViewById(R.id.saludo_bienvenida);
et1_creditos = (EditText) findViewById(R.id.edittext1_numero_creditos);
et2_faltas = (EditText) findViewById(R.id.edittext2_numero_faltas);
boton_ingresar = (Button) findViewById(R.id.boton_ingresar);
boton_info = (Button) findViewById(R.id.boton_info);
if (boton_ingresar != null) {
boton_ingresar.setOnClickListener(this);
}
if (boton_info != null) {
boton_info.setOnClickListener(this);
}
et1_creditos.setInputType(InputType.TYPE_CLASS_NUMBER);
et2_faltas.setInputType(InputType.TYPE_CLASS_NUMBER);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.boton_ingresar:
numero_creditos = et1_creditos.getText().toString();
numero_faltas_actuales = et2_faltas.getText().toString();
int numero_creditos1 = Integer.parseInt(numero_creditos);
int numero_faltas_actuales1 = Integer.parseInt(numero_faltas_actuales);
int o = numero_creditos1 * 14;
if (numero_creditos1>6) {
Toast.makeText(getApplicationContext(), "Ingrese un número válido de créditos", Toast.LENGTH_LONG).show();
}else if (numero_faltas_actuales1 > o){
Toast.makeText(getApplicationContext(), "El número de faltas ingresadas es mayor que el número de horas del curso", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(MainActivity.this,Resultados.class);
intent.putExtra("numero_creditos",numero_creditos);
intent.putExtra("numero_faltas_actuales",numero_faltas_actuales);
startActivity(intent);
}
break;
case R.id.boton_info:
Intent informacion = new Intent(MainActivity.this,Informacion.class);
startActivity(informacion);
break;
}
}
}
This is the log:
06-17 01:36:17.419 2738-2738/absence_counter.app.jorgepasco.com.absencecounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: absence_counter.app.jorgepasco.com.absencecounter, PID: 2738
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at absence_counter.app.jorgepasco.com.absencecounter.MainActivity.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
So thanks you for your log !
You can see on your log that you have a problem when you parseInt. You try to parseInt an empty String.
So when the user do not write anything, you have to set a default value yourself.
You can do something like that before your parse:
if(numero_creditos.equals(""))
numero_creditos = "0";
But if I were you, I would force the user to right directly an integer
Please, show us your log box.
Perhaps the app crash because you don't have any default case in your switch case. So if v.getId() is not what you think, it will crash.
Simply, add that at the end of your switch case:
switch(v.getId()){
case: ...
case: ...
default: Toast.makeText(getApplicationContext(),"v.getId = " + v.getId());
}
But I would be easier for me to solve your problem with your log box !
et1_creditos.getText() can maybe send a null value. Then null.toString() has no sense because null does not have toString().
try:
String creditos = et1_creditos.getText()
if(creditos != null){
//stuff here
}
It is failing on this line.
int numero_creditos1 = Integer.parseInt(numero_creditos);
If your numeor_creditos is empty it won't be integer.
Try
int numero_creditos1;
if(TextUtils.isEmpty(numero_creditos){
numero_creditos1 = 0;
} else {
numero_creditos1 = Integer.parseInt(numero_creditos);
}

Android App force closes, found java.lang.nullpointerexception

I built an android app that casts a spinner to a switch, to enable the user to select an operator for a calculation and see the result.
It is from the Android Boot Camp lessons. I was unhappy to find my app had no compile errors but crashed on start-up. I was watching the logcat as I ran the application and found the nullpointer exception to be on line 40. Where I pull the spinner's selection to a string variable.
//spinner
op3 = operation.getSelectedItem().toString();
I dumped the contents of my logcat to a text file. Here is what I think is relevant.
09-30 22:26:58.401: E/AndroidRuntime(1565): FATAL EXCEPTION: main
09-30 22:26:58.401: E/AndroidRuntime(1565): Process: com.schmop.flashmath, PID: 1565
09-30 22:26:58.401: E/AndroidRuntime(1565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.schmop.flashmath/com.schmop.flashmath.MainActivity}: java.lang.NullPointerException
and
**09-30 22:26:58.401: E/AndroidRuntime(1565): Caused by: java.lang.NullPointerException
09-30 22:26:58.401: E/AndroidRuntime(1565): at** com.schmop.flashmath.MainActivity.onCreate(MainActivity.java:40)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Activity.performCreate(Activity.java:5231)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-30 22:26:58.401: E/AndroidRuntime(1565): ... 11 more
Here is the contents of my mainActivity in
MainActivity.java
public class MainActivity extends ActionBarActivity {
int number1;
int number2;
int result;
int op1;
int op2;
String op3 = null;
int calculator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText)findViewById(R.id.num);
final EditText second = (EditText)findViewById(R.id.num2);
final Spinner operation = (Spinner)findViewById(R.id.operator);
final Button equals = (Button)findViewById(R.id.button1);
final TextView t = (TextView)findViewById(R.id.result);
operation.setSelection(0);
//spinner
op3 = operation.getSelectedItem().toString();
//start logic
//onclick listener
equals.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//gettext
number1 = Integer.parseInt(first.getText().toString());
number2 = Integer.parseInt(second.getText().toString());
if(number1 < 21 && number1 > 0 && number2 < 21 && number2 > 0) {
//switch
switch(calculator) {
case 1: op3 = "+";
calculator = number1 + number2;
break;
case 2: op3 = "-";
calculator = number1 - number2;
break;
case 3: op3 = "x";
calculator = number1 * number2;
break;
}
} else {
t.setText("Error: One of your Numbers is out of Range");
}
t.setText(number1 + op3 + number2 + "=" + calculator);
}
});
//end logic
}
Since it was calling a null variable, I tried adding junk data into the declaration of op3 as an attempt to fix my problem. This proved unsuccessful. I've seen some examples being solved by adding a check for null in an if statement, however I dont think it would apply here.
Documentation for getSelectedItem():
Returns The data corresponding to the currently selected item, or null if there is nothing selected.
When the app is starting up, nothing is yet selected. Move the
op3 = operation.getSelectedItem()
inside the onClick() and check for != null before trying to call toString() on the result.
You haven't set any contents for the spinner, so operation.getSelectedItem() is returning null. The NPE is from trying to then call toString(). Populate your spinner first before trying to access items, or at least put a null check when you try to retrieve an item.

Android: Is there a method equivalent to XML android:digits?

In my layout xml, I use the following to define an EditText that can display currency.
<EditText
android:id="#+id/et1"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:imeOptions= "actionNext"
android:inputType="phone"
android:digits="0123456789.,$" >
However, this is not localized. I want to be able to use the symbol returned by NumberFormat.getCurrencyInstance().getCurrency().getSymbol(); in place of the $ in android:digits.
What I don't know is how to set android:digits from within my program.
Solved thanks to Agarwal. I just need to read the documentation more thoroughly.
Try this:
<EditText
android:inputType="number"
android:digits="0123456789."
/>
From Code:
weightInput.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
But, it allows the user to include several "."
You can also do this for accepting on digits...
EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
Yes you can check here
http://developer.android.com/reference/android/widget/EditText.html
for almost every attribute there is equivalent method present.
setKeyListener(KeyListener)
For those interested, here is how I solved the original question. It is the complete implementation of a currency edit text that can handle multiple locales. Still may be some problems (Doesn't seem to display Japanese currency symbol correctly, and I can't get the keyboard I want (12_KEY)), but otherwise, some may find this helpful.
public class CurrencytestActivity extends Activity
{
private static final Integer MAX_VALUE_DIGITS = 9;
EditText et1;
NumberFormat mCurrencyFormatter;
CurrencyTextWatcher tw;
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get info about local currency
mCurrencyFormatter = NumberFormat.getCurrencyInstance();
int fractionDigits = mCurrencyFormatter.getCurrency().getDefaultFractionDigits();
et1 = (EditText)findViewById(R.id.et1); // Get a handle to the TextEdit control
// Add local currency symbol to digits allowed for EditText display and use
// DigitsKeyListener to tell the control. Unfortunately, this also resets the inputType
// that is specified in the XML layout file. Don't know how to fix that yet.
// Also, this doesn't seem to work for Japanese (probably due to UNICODE or something).
// The symbol gets added to displayCharacters, but the EditText doesn't use it.
String displayCharacters = "0123456789.," + mCurrencyFormatter.getCurrency().getSymbol();
et1.setKeyListener(DigitsKeyListener.getInstance( displayCharacters ));
// Add a text watcher to the EditText to manage currency digit entry. The TextWatcher
// won't allow the symbol or decimal or comma to be entered by the user, but they are
// still displayed when the result is formatted in afterTextChanged().
tw = new CurrencyTextWatcher( MAX_VALUE_DIGITS, fractionDigits );
et1.addTextChangedListener( tw );
et1.setCursorVisible( false );
((Button)findViewById(R.id.button1)).setOnClickListener(onButtonClick);
}
public class CurrencyTextWatcher implements TextWatcher
{
boolean mEditing; // Used to prevent recursion
Double mAmount;
int mDigitCount, mMaxDigits, mFractionDivisor;
public CurrencyTextWatcher( int maxDigits, int fractionDigits )
{
mEditing = false;
mFractionDivisor = (fractionDigits == 0) ? 1 : ((fractionDigits == 1) ? 10 : 100);
mAmount = 0.0;
mDigitCount = 0;
mMaxDigits = maxDigits;
}
public synchronized void afterTextChanged(Editable s)
{
// Don't update EditText display if we are editing
if ( !mEditing )
{
// Under cover of mEditing, update the EditText display with
// the newly formatted value
mEditing = true;
s.replace( 0, s.length(), mCurrencyFormatter.format( mAmount ));
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public double GetAmount() { return( mAmount ); }
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if ( !mEditing )
{
// Added a digit to the value
if (( count == 1 ) && ( mDigitCount < mMaxDigits ))
{
// Obtain the added character
CharSequence x = s.subSequence( start, start + count );
// Ignore any characters other than number digits for addition to value
if (( x.charAt( 0 ) >= '0') && ( x.charAt( 0 ) <= '9'))
{
// Multiply by ten to shift existing digits to the left and
// add in the new digit as the decimal place appropriate to this currency
mAmount = (mAmount * 10) + (Double.parseDouble( x.toString() ) / mFractionDivisor);
mDigitCount += 1;
}
}
// Delete last digit from the value
else if (( count == 0 ) && ( mDigitCount > 0))
{
// Subtract the amount of the last digit and divide by ten to
// effectively delete the last character entered
mAmount -= (mAmount % (0.001 * mFractionDivisor) );
mAmount /= 10;
mDigitCount -= 1;
}
}
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener()
{
#Override public void onClick(View v)
{
if (v.getId() == R.id.button1 )
{
// Get the value from the textwatcher and display it.
double mAmountTest = tw.GetAmount();
((TextView)findViewById(R.id.tv1)).setText(mCurrencyFormatter.format( mAmountTest ));
}
}
};
}
And the accompanying XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center|top"
android:orientation="vertical" >
<EditText
android:id="#+id/et1"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:imeOptions= "actionNext"
android:inputType="phone" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Extract from TextWatcher" />
</LinearLayout>

Categories

Resources