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.
Related
I'm new to development so sorry if my question is very simple.
I'm developing an app for D&D. When the user inserts a number in the first edittext i use onTextChanged of edittext so I setText to the second edittex the result.
My problem only occurs if the checkbox is checked. If the checkbox is not checked, it works fine but if the checkbox is checked the app will make a sum (proficiencybonus + mod). It works but only for positive numbers. When the app sets a velue of f.e. -5 the app crashes. The data is all saved in the sharedpreferences.
checkBox_strength.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(checkBox_strength.isChecked()) {
float result_num;
int num1, num2;
int f= 0;
DecimalFormat df = new DecimalFormat("0.##########");
num1 = Integer.parseInt(proficiencybonus.getText().toString());
if (strength_mod.getText().toString().length() > 0) {
num2 = Integer.parseInt(strength_mod.getText().toString());
} else {
num2=f;
}
result_num = num1 + num2;
strength_save.setText(" = " + df.format(result_num));
editor.putBoolean("checkBox_strength", true);
editor.apply();
}else{
editor.putBoolean("checkBox_strength", false);
editor.apply();
}
}
});
Have tried something else but I can't go find a solution
float result_num;
int num1, num2;
int f= 0;
DecimalFormat df = new DecimalFormat("0.##########");
num1 = Integer.parseInt(proficiencybonus.getText().toString());
if (strength_mod.getText().toString().length() > 0) {
num2 = Integer.parseInt(strength_mod.getText().toString());
} else {
num2=f;
}
result_num = num1 + Math.abs(num2);
strength_save.setText(" = " + df.format(result_num));
This is my error of the crash, it crashes "num2 = Integer.parseInt(strength_mod.getText().toString());"
2020-05-03 17:09:24.440 10318-10318/jekanapplication.charactersheet5e E/AndroidRuntime: FATAL EXCEPTION: main
Process: jekanapplication.charactersheet5e, PID: 10318
java.lang.NumberFormatException: For input string: "−1"
at java.lang.Integer.parseInt(Integer.java:608)
at java.lang.Integer.parseInt(Integer.java:643)
at jekanapplication.charactersheet5e.MainActivity$51.onCheckedChanged(MainActivity.java:1394)
at android.widget.CompoundButton.setChecked(CompoundButton.java:172)
at android.widget.CompoundButton.toggle(CompoundButton.java:128)
at android.widget.CompoundButton.performClick(CompoundButton.java:133)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
In the XML define this attribute: android:inputType="numberSigned"
The Problem is how set the text in the second edittext , is use onTextchange of the first edittext, I set the text edittext.settext"-2" I have changed in edittext.settext"R.String.two_" so when the i get the text I have no proble when I get the string.
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);
}
I have lists of color variations of a product in the ListView . Each list color variation has an EditText. I want to try to make the validation process orders when my button clicked.
This My Code:
btnOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int count = listView.getAdapter().getCount();
String[] listData = new String[count];
int[] listData2 = new int[count];
int sum = 0;
try {
for (int i = 0; i < count; i++) {
View quantity=listView.getChildAt(i);
if (quantity.findViewById(R.id.quantityOrder) != null){
EditText quantityOrder = (EditText) quantity.findViewById(R.id.quantityOrder);
listData[i] = quantityOrder.getText().toString();
listData2[i] = Integer.parseInt(quantityOrder.getText().toString()); // set edittext to int
sum += listData2[i];
jsonObject.put("params_"+i,listData[i]); // put to params for volley request
}
}
if (sum < 1) {Toast.makeText(getApplicationContext(),
"Sorry, you need to fill Order Quantity", Toast.LENGTH_SHORT) // validation input if edittext empty
.show();} else {
Log.d(TAG, jsonObject.toString()); }
} catch (JSONException e) {
e.printStackTrace();
}
}
});
My app get force close. here the error code
09-25 23:01:05.679 32623-32623/id.nijushop.ikutan E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:359)
at java.lang.Integer.parseInt(Integer.java:332)
at id.nijushop.ikutan.ProductDetail$1.onClick(ProductDetail.java:150)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Please, some one fix my code...I think i need to do something about this
quantity.findViewById(R.id.quantityOrder)// need to set to Interger
The problem is in this line:
listData2[i] = Integer.parseInt(quantityOrder.getText().toString()); // set edittext to int
The Integer.parseInt(String string) method will return an int or throw a NumberFormatException if passed string is not a valid integer string. An empty string - "" doesn't make up a valid integer, so if your EditText is empty, the problem arises.
You need to shield the execution of parseInt with a try - catch block catching a NumberFormatException and act accordingly - abort the method or else, but you obviously cannot continue with your arithmetic if you haven't provided a valid number.
Also, the thing that would help you is, within your EditText element in xml file, include an inputType property, for example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number|numberSigned" />
This inputType property will cause the system to use an automatic inputFilter and provideonly numeric soft keyboard, so the user cannot enter an invalid number (in this case, only a signed integer). However this will still not account for empty input, so you'll need to either catch NumberFormatException or check whether string from your EditText is not empty. (!string.isEmpty())
Recently I've started to mess around with Android Studio and decided to make an app. I've made the most of my app, but I encounter a little problem. I need to memorize in a variable a number from user input, but I don't know how to that, I've tried solutions found on the internet, even here but I get an error.
Can somebody help me with some ideas or the code edited which I must put in my app ?
This is the java code for the activity:
public class calc_medie_teza extends ActionBarActivity implements View.OnClickListener {
EditText adaug_nota;
static final int READ_BLOCK_SIZE = 100;
TextView afisare;
TextView afisare2;
Button calc;
EditText note_nr;
EditText nota_teza;
int suma;
double medie;
double medieteza;
int nr_note = 0;
int notamedie;
int notateza;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc_medie_teza);
afisare = (TextView) findViewById(R.id.afisare);
afisare2 = (TextView) findViewById(R.id.afisare2);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(this);
note_nr = (EditText) findViewById(R.id.note_nr);
nota_teza = (EditText) findViewById(R.id.nota_teza);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_calc_medie_teza, menu); // creare meniu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); // meniu
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void onClick(View v) // afisare medie
{
calcul_medie();
}
public void buton_adauga(View v)
{
if(note_nr == )
suma = suma + notamedie;
nr_note = nr_note + 1;
}
public double calcul_medie() // calculul mediei
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
Here is a photo with the activity: http://onlypro.ro/img/images/ootllv2f55hnwdgi0xlv.png
Basically the app needs to add the input number to variable when I press the "Adauga nota" [Add grade] button and then I have to insert the "teza" number and when press the "Calculeaza media" [Calculate] the app will then calculate the calcul_medie() and return a decimal number. Between "Introduceti notele aici" [Add grades here] and "Adaugata nota"[Add grade] I have a Number enter text, the same is between "Introduceti teza aici" [Add thesis bere] and "Calculeaza media" [Calculate]. I don't know how to store the number the user puts in and sum it in "notamedie" variable.
I hope you understand my problem.
For any questions you'll have I'll respond as soon as I can.
Thanks in advance !
Well, I think your probably asked how to get the input of the String from the UI and translate them into Integer/BigDecimal. If so, here is some solution:
first, you get get the string from the UI:
String input = note_nr.getText().toString().trim();
change the string input to integer/BigDecimal:
int number1 = Integer.parseInt(input);
BigDecimal number2 = new BigDecimal(input);
Correct me if misunderstood your questions. Thanks.
I did not understand the problem at all. Please clearly define the problem and use english if you can. As fas the I understood there will be a Edittext to which the user will input the value. Gets its value in the activity and then use it.
EditText edittext;
editext = (EditText) findViewById(R.id.editext);
String value = edit text.getText().toString(); // the value that the user inputted in String data format
// Here for addition you will need the value in int or decimal for that
int valueInt = Integer.parse(value); // this will be the value in int type
double valueInt = = Double.parseDouble(value); // this will be the value (user inputted) in double data type ( which you will need if you want to use decimal numbers).
When you press a button just retrieve the appropriate value from the edittext in the following way
edittext = (EditText)layout.findViewById(R.id.txtDescription);
String string = edittext.getText().toString();
to retrieve the text do this
String string = note_nr.getText().toString();
// Converting String to int
int myValue =Integer.parseInt(string);
I tried that one more time, but the IDE says that the variable I used for "string" is never used, but I've used it.
number1= (EditText) findViewById(R.id.number1);
String number_1 = number1.getText().toString();
number2= (EditText) findViewById(R.id.number2);
String number_2= number2.getText().toString();
R3muSGFX, can you post the whole codes?
String number_1 = number1.getText().toString(); this line codes just mean that you initialized a String variable "number_1".
and you will used it when app perform a math function, like you wrote in the beginning:
public double calcul_medie()
{
medie = suma / nr_note;
medieteza = ((medie * 3)+ notateza)/4;
return medieteza;
}
but if you did not use "number_1" at all, IDE will imply you the warning message
:the variable I used for "string" is never used
i have an arraylist that do this :
ArrayList<Integer> id = new ArrayList<Integer>();
for (int i = 0; i <= 20; i++) {
id.add(getResources().getIdentifier("q"+i, "raw", getPackageName()));}
this method before a little change is working good but now have force close!
and i get this logcat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{yaAli.package313.hossein110/yaAli.package313.hossein110.know}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at yaAli.package313.hossein110.know.onCreate(know.java:33)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
... 12 more
Here is my OnCreate():
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.basetxt);
SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ln=settings.getString("LASTREADln", null);
if(ln.equals("-1")){ln="0";}
if(ln!=null){
final ScrollView s1=(ScrollView) findViewById(R.id.sV1);
s1.post(new Runnable() {#Override
public void run() {s1.scrollTo(0, Integer.valueOf(ln));} });}
final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.arza);
String pos = getIntent().getStringExtra("key");
String arr = getIntent().getStringExtra("list");
TextView tvfa = (TextView)findViewById(R.id.TEXT313);
String fontPath = "fonts/font1.ttf";
String fontPath1 = "fonts/font2.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontPath1);
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
tvfa.getRootView().setKeepScreenOn(sharedpreferences.getBoolean("scrnon", false));
String sizefa= sharedpreferences.getString("fontsizefa",null);
String colorfa= sharedpreferences.getString("fontcolorfa",null);
boolean style= sharedpreferences.getBoolean("appfont", false);
boolean music= sharedpreferences.getBoolean("musictype", false);
boolean curr= sharedpreferences.getBoolean("currputfont", false);
String t = read(file(pos,arr,null)); {
if (curr){tvfa.setText(PersianReshape.reshape(t));}else{tvfa.setText(t);} // Txt
tvfa.setTextSize(1, Float.valueOf(sizefa).floatValue()); // Size
tvfa.setTextColor(Color.parseColor(colorfa)); // Color
if (style) { tvfa.setTypeface(tf1); } else {tvfa.setTypeface(tf);} // Type
if (music) { mp1.start(); } else { mp1.stop(); } }} // Play
//----------------------------------------------------------------------------
best practice for java development is to have the literal string do the .equals call. so instead of:
var.equals("string")
you do:
"string".equals(var)
This guarantees you will NEVER have a null pointer exception when doing string comparison.
Also, it looks like you are storing numeric values as strings. Any particular reason you aren't storing them as ints?
Its likely here
ln=settings.getString("LASTREADln", null);
this should be
ln=settings.getString("LASTREADln", "");
since null is set to be your default value if that key does not exist or contain anything, so if it doesn't contain anything you should set it to "", and for your string comparisons you should look for !ln.contentsEquals("") instead of checking it for null
the same goes for all of the strings you get from a preferences file. set the default value to "" instead of null