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())
Related
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 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.
EDIT:A Pastebin consisting of the relevant parts of my project:
Here is the updated code
Also ColouredItem is a wrapper for:
public class ColouredItem
{//Only a wrapper class,no behaviour has been defined here
String name,colour;
}
I get a NumberFormatException when trying to parse a colour from a String using the following code:
row.setBackgroundColor(Color.parseColor(item.colour));
I use the following to create a list of items from a resource:
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.colour="#"+cmenu[1];
Log.d(TAG, item.colour);
menuList.add(item);
}
This is the exception that I get...I have found that view.setBackgroundColor only takes an integer value:
#ffffff
#ffffBB
#fff45f
#ffff00
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x4001d800)
FATAL EXCEPTION: main
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.makeAndAddView(ListView.java:1727)
at android.widget.ListView.fillDown(ListView.java:652)
at android.widget.ListView.fillFromTop(ListView.java:709)
at android.widget.ListView.layoutChildren(ListView.java:1580)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Adding the # as some of the answers suggest did not solve the issue:
java.lang.NumberFormatException: Invalid long: "#ffffff"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
No difference with this implementation either:
String cmenu=list[i];
item.name=cmenu.substring(0, cmenu.indexOf("#"));
item.colour=cmenu.substring(cmenu.indexOf("#"));
Use this code
row.setBackgroundColor(Color.parseColor("#424242"));
it helped me too,dont remove "#".
i used this code
private List<String> item;
item = new ArrayList<String>();
item.add("#424242");
row.setBackgroundColor(Color.parseColor(item.get(0)));
and its working gud for me,may be your split thing is not working good
or for your code
Button btn;
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[] { "Page1 #ffffff", "Page2 #ffffBB" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
try {
btn = (Button) findViewById(R.id.button1);
for (int i = 0; i < list.length; i++) {
item = new ColouredMenuItem();
String[] cmenu = list[i].split("#");
item.name = cmenu[0];
item.color = "#" + cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
btn.setBackgroundColor(Color.parseColor(menuList.get(1).color));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is working good at my side
this is new code
Make your colored item as a bean class with getter and setter like this
public class ColouredMenuItem {// Only a wrapper class,no behaviour has been defined
// here
String name, colour;
List<ColouredMenuItem> list=new ArrayList<ColouredMenuItem>();
public List<ColouredMenuItem> getList() {
return list;
}
public void setList(List<ColouredMenuItem> menuList) {
this.list = menuList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
Then in your adapter use this code
try {
Log.d(TAG, menuList.get(position).colour);
textView.setText(menuList.get(position).getName());
{
row.setBackgroundColor(Color.parseColor(menuList.get(position).getColour()));
}
} catch (Exception ex) {
Log.e(TAG, "Still does not work");
}
Just give it a try,it works here at my side
Also your array is like this only na
<string-array name="menu_array">
<item>Page1 #ff7788</item>
<item>Page1 #ff6688</item>
<item>Page1 #424242</item>
</string-array>
Try Color.parseColor("#ffffff"); instead of Color.parseColor("ffffff");
look at the Stack trace it will tell you:
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
Line by Line:
you are trying to format Hexadecimal (base 16) value "0xffffff" to a decimal (base 10) value
you're trying to parse hexadecimal string "ffffff" to type Long
same as above.
error is thrown when calling `Color.parseColor()`
error is thrown from your MadAdapter.java Class on line 60.
so, you need to find a way to parse it from Hexadecimal instead of decimal value. Hexadecimal values are usually preceeded by 0x[value] OR #[value]
Assuming: while parsing the color from string object "item" is not taken from array of list, rather its taking instance variable of ColoureMenuItem.
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[]{"#ffffff","#00ffff"};
// parsing your string here, no change in this
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.color="#"+cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
// confirming whether value are parsing or not.
for(int i=0;i<menuList.size();i++)
{
int color = Color.parseColor(menuList.get(i).color);
Log.d("color",""+menuList.get(i).color);
}
and your ColouredMenuItem class.
public class ColouredMenuItem {
public String color;
public String name;
}
Following code gives me numberformatexception. can you please tell me where to put exepcions or what to do about following lines? logcat tells that there is a problem on commented line
public void zaplatiti(){
EditText zbrojka = (EditText) findViewById(R.id.editText7);
Float[] strings = new Float[allTexts.size()];
Float zbroj=(float) 0;
for(int i=0; i < allTexts.size(); i++){
strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
}
for (int k=0;k<strings.length;k++){
zbroj =zbroj+ strings[k];}
}
zbrojka.setText(String.valueOf(zbroj)+"KN");
}
for(int i=0; i < allTexts.size(); i++){
try {
strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
}
catch (NumberFormatException e) {
// Code to execute if the entered value is not a number
}
}
This is also possible to avoid by only allowing your EditTexts to have numerical values. That will force the user to only enter a numerical value in the first place, then you don't have to catch the exception. But then you should check if the entered text is empty first.
EDIT:
For doing this you must make an if statement, but the correct comparison beetween String values is:
if ( mEditText.getText().toString().equals("String to compare with")){ ... }
the "numerical mode" of an editText could be set up in the XML file as:
android:inputType = "number"
Other valid numerical modes are numberSigned and numberDecimal.
So after changing the input type your code could look like:
for(int i=0; i < allTexts.size(); i++){
if (!allTexts.get(i).getText().toString().equals("")) {
strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
}
else {
// Code to execute if there is no entered value
}
}
Did you check the allTexts Array type?
I have this code to control if a EditTextPreference is null or not:
case R.id.prochain_vidange:
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String choix_huile = settings.getString("listPref_huile_moteur", "0");
km = settings.getString("km", "");
Log.d("TAG",km);
int x= Integer.valueOf(km);
if (km != "")
{
if (Integer.valueOf(choix_huile) == 0) {
............
The problem is in this line:
int x= Integer.valueOf(km);
What could be the problem ?
Thanks.
If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:
km = settings.getString("km", "0");
Alternatively, you can catch the exception, and set x to 0:
km = settings.getString("km", "");
int x;
try {
x = Integer.valueOf(km);
} catch(NumberFormatException e) {
x = 0;
}
Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException
You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".
before:
int x= Integer.valueOf(km);
if (km != "") {
after:
if (km != "") {
int x= Integer.valueOf(km);
Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.
However, wrapping it in a try { } catch() block is not an approach I would recommend.
The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:
km = settings.getString("km", "0");
Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.
Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.