I have to add values to my sq lite from the list view. In my list view there are two edit texts and text view. I just want to get value from each edit text and multiply it to the corresponding text view value. when I am running the app, I need not to enter data to every edit text. due to this I am ending with a "number format exception : invalid int". From other examples I can understand that multiplication on null value may cause the error. how can I skip the null value contained edit texts from the iteration?
this is my code
protected void InsertDb() {
// TODO Auto-generated method stub
DatabaseHelper databasecontroller = new DatabaseHelper(Orders.this);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
if(list != null){
for(int i = 0; i< list.getChildCount();i++){
View vie = list.getChildAt(i);
EditText ed1= (EditText) vie.findViewById(R.id.cases);
EditText ed2 = (EditText) vie.findViewById(R.id.pcs);
String qty = ed1.getText().toString();
TextView tv = (TextView)findViewById(R.id.srp);
String imsrpv= tv.getText().toString();
float srps = Float.valueOf(imsrpv);
int qtys = Integer.valueOf(qty);
float amts = srps * qtys;
String amount = Float.toString(amts);
datanum.put("A",qty );
datanum.put("B",ed2.getText().toString() );
datanum.put("L", amount);
Log.d("value of amnt",amount);
databasecontroller.entercustdetails(datanum);
}
}
Log.v("compleated", data.toString());
}
Thanks in advance..
Check either returning value from edittext is a proper number or it is not null.if a null value is there it may give exeception of numberformat.you have to handle this.
if both are correct then you can also you
float srps=0.0;
int qtys=0;
try
{
srps = Float.valueOf(imsrpv);
qtys = Integer.valueOf(qty);
}
catch (NumberFormatException e)
{
srps =//Default value you want;
qtys =//Default value you want;
}
Hope it works..
Your problem is not how You have parsed the values. For explanation:
parseFloat(), parseInt() will return a primitive type of int and float and valueOf() returns a new type of Integer and Float. Also, parseInt(), parseFloat() will recognize plus and minus signs, valueOf() doesn´t. That´s the difference between these two types/methods. Your problem seems to be, that the value is empty and You can simply get rid of this by:
//set a default float and int
float srps = 0.0;
int qtys = 0;
//now parse the values by checking if the strings are not null or empty
if(imsrpv!=null&&!imsrpv.isEmpty()){
srps = Float.valueOf(imsrpv);
}
if(qty!=null&&!qty.isEmpty()){
qtys = Integer.valueOf(qty);
}
Like I said, if these values have a plus or minus sign and it is important for Your needs, You should use the parse method. Also, You don´t need a new Integer or Float type, so more correct is using parse() method.
Related
hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.
First of all, here is my code:
startRandomizing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> values = new ArrayList<>();
int idList[] = new int[]{R.id.textBox1,R.id.textBox2,R.id.textBox3,
R.id.textBox4,R.id.textBox5,R.id.textBox6};
for(int id : idList){
if (findViewById(id) != null) {
values.add(((EditText) findViewById(id)).getText().toString());
}
}
String[] myItems = values.toArray(new String[values.size()]);
What I want to do is get rid of all the null values so that the length (myItems.length) of the array will depend on the value inside the text boxes 1 - 6.
(E.x - I have a string "Hello" in textBox1 and "World" in textBox2, and the rest empty. My desired output for myItems.length should be 2 since the remaining textBoxes do not have a value.)
This code outputs 6 (counts all the text boxes). Where have I gone wrong?
Change your code in the for loop as follows:
String s = ((EditText) findViewById(id)).getText().toString();
if(!TextUtils.isEmpty(s)){
values.add(s);
}
I want to get the product of the inputted values in two editTexts.
For example I will input [1,2,3,4,5] in xValues then I will input also [6,7,8,9,10] in freqValues then it will multiply (1*6),(2*7),(3*8),(4*9),(5*10). How will i do that? Please help me. Thank you in advance:)
final AutoCompleteTextView xValues = (AutoCompleteTextView) findViewById(R.id.x_Values);
final AutoCompleteTextView freqValues = (AutoCompleteTextView) findViewById(R.id.frequency_Values);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int[]convertedx=new int[x.length];
int[]convertedfreq=new int[freq.length];
}
});
You'll have to do some error catching to make sure only numbers are inputted but once you get that figured out, do something like this:
...
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int product = 0;
for(int i = 0; i < x.length(); i++) {
int tempX = Integer.parseInt(x[i]);
int tempFreq = Integer.parseInt(freq[i]);
product += (tempX * tempFreq);
}
Assuming that the arrays are split correctly and only contain integers, this loop will grab the first int from X[] and Freq[] and then multiply them together, and add it to product, then grab the 2nd int from these arrays, parse the string into an int, and then multiply those and loop through until the end of the array.
My app has 4-5 EditTexts on each activity and I have 10 or so activities. I need to parse each of these to a double. So I figured I want to create a method in which I enter an EditText Array and it returns a double array with the parsed numbers.
One of the EditTexts will always be empty so I would need that specific position in the array of Doubles that are supposed to be returned to 0.
This is what I have been fiddling around with (without success so far).
public double[] parser(EditText[] editArray) {
EditText toBeParsed[] = null;
double parsed[] = null;
for (int i = 0; i < editArray.length; i++) {
try {
parsed[i] = Double.parseDouble(toBeParsed[i].getText().toString());
} catch (Exception e) {
parsed[i] = 0;}
}
Ho do i need to set this up?
Next in one of my activities I have this where I call the method (from a MiscMethods.java file)
EditText inputs[] = {i1,i2,i3,i4}
Double parsed[];
for (int i = 0; i < inputs.length; i++) {
parsed[i] = MiscMethods.parser(inputs);
}
But get a type mismatch... Why? the method returns an array of doubles and should put them into the double parsed[] array.?
It seems like you are using toBeParsed array in stead of your editArray
so
parsed[i] = Double.parseDouble(toBeParsed[i].getText().toString());
should be
parsed[i] = Double.parseDouble(editArray[i].getText().toString());
Is it possible to do that in a more convenient way than handling it in the OnScrollListener event? Pity it doesn't have a step size attribute...
The NumberPicker in Android has a method called setDisplayedValues.
You can use this one to show custom values (it takes an array of Strings) and then map them when you need the value.
So if you need steps of 5 in an minute picker, for example, you can create an array like this:
String[] minuteValues = new String[12];
for (int i = 0; i < minuteValues.length; i++) {
String number = Integer.toString(i*5);
minuteValues[i] = number.length() < 2 ? "0" + number : number;
}
minutePicker.setDisplayedValues(minuteValues);
And then when you get the value in the OnValueChangeListener, you just need to cast it back to an integer:
Integer.parseInt(minuteValues[newVal]);
To set a step count of '5' for example, use the NumberPicker.Formatter:
NumberPicker.Formatter formatter = new NumberPicker.Formatter() {
#Override
public String format(int value) {
int temp = value * 5;
return "" + temp;
}
};
numberPicker.setFormatter(formatter);
Why not just add an OnValueChangeListener Something like:
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
picker.setValue((newVal < oldVal)?oldVal-5:oldVal+5);
}
});
The NumberPicker in Android has a method called setDisplayedValues. You can use this one to show custom values (it takes an array of Strings) and then map them when you need the value.
For example, you can create a function like this:
public String[] getArrayWithSteps (int iMinValue, int iMaxValue, int iStep)
{
int iStepsArray = (iMaxValue-iMinValue) / iStep+1; //get the lenght array that will return
String[] arrayValues= new String[iStepsArray]; //Create array with length of iStepsArray
for(int i = 0; i < iStepsArray; i++)
{
arrayValues[i] = String.valueOf(iMinValue + (i * iStep));
}
return arrayValues;
}
So, you should call the method> NumberPicker.setDisplayedValues, for example:
int min = 5;
int max = 180;
int step = 10;
String[] myValues = getArrayWithSteps(min, max, step); //get the values with steps... Normally
//Setting the NumberPick (myNumberPick)
myNumberPick.setMinValue(0);
myNumberPick.setMaxValue((max-step) / min + 1); //Like iStepsArray in the function
//Because the Min and Max Value should be the range that will show.
//For example, Min = 0 and Max = 2, so the NumberPick will display the first three strings in the array String (myValues);
myNumberPick.setDisplayedValues(myValues);//put on NumberPicker
For get the Value in the NumberPick:
String sValue = String.valueOf(10+(myNumberPick.getValue()*5)); //->> (iMinValue + (myNumberPick.getValue()*iStep))
When using methods described above, one needs to be aware that the picker allows user not only to select a value by scrolling, but also by entering it with keyboard.
By default, the input type of the input field is set to TYPE_CLASS_NUMBER, and therefore user is presented with numerical keyboard. It seems that when you use setDisplayedValues the picker changes the type to TYPE_CLASS_TEXT, however, when you use setFormatter the input type is not changed.
Therefore using formatter in this case may lead to unexpected behavior. Let's say you want the user to be able to pick only the values "0" or "5". You may have code like this:
NumberPicker numberPicker = (NumberPicker) findViewById(R.id.my_number_picker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(1);
numberPicker.setFormatter(v -> v == 0 ? "0" : "5");
However, in this scenario the user is presented with the numerical keyboard, but is able only to enter only "0" or "1".
If you use instead:
numberPicker.setDisplayedValues(new String[] { "0", "5" });
the user will see the text keyboard, but will be able to enter "0" or "5" as expected.
If you are bothered with the text keyboard you can use reflection to access the private field and set the input type back to number (which is of course not recommended unless really necessary). The field is called "mInputText", or "mText" if you target oldies goldies like Gingerbread.
try {
Field inputField = NumberPicker.class.getDeclaredField("mInputText");
inputField.setAccessible(true);
EditText inputText = (EditText) inputField.get(numberPicker);
inputText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
} catch (ClassCastException e) {
// Just ignore this exception and do nothing.
} catch (IllegalAccessException e) {
// Just ignore this exception and do nothing.
} catch (NoSuchFieldException e) {
// Just ignore this exception and do nothing.
}
This is better approach for ajpolt solution
with any predefined step size, it support for custom value set via keyboard.
final NumberPicker np = (NumberPicker) dialogView.findViewById(R.id.numberPicker1);
np.setMaxValue(1000); // max value 1000
np.setMinValue(0); // min value 0
np.setValue(defValue);
np.setWrapSelectorWheel(false);
final int m_oldFocus = np.getDescendantFocusability();
np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
np.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
np.setDescendantFocusability(m_oldFocus);
return false;
}
});
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int oldVal, int newVal) {
int stepSize = 10;
if(newVal%stepSize !=0){
if(newVal < oldVal){
numberPicker.setValue(((int)(newVal/stepSize)) *stepSize);
}else{
numberPicker.setValue((((int)(newVal/stepSize)) *stepSize ) +stepSize );
}
}else{
numberPicker.setValue(newVal);
}
}
});
*I know this is 5 years old Question, but might be useful for somebody