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);
}
Related
I am an android noobie. What I am trying to do is to make this String an ArrayList. This is done. When i Print it On (with tv.setText) , the result is what i need but in this if i have right below i cannot find the "1".
The result i want to have is to store the text between the noumbers inside another ArrayList but to go there i have to be able to read the strings from the ArrayList.
public class MainActivity extends AppCompatActivity {
String text = "1Hello12People22Paul22Jackie21Anna12Fofo2";
TextView tv;
List<String> chars = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
PrinThemNow();
}
public void PrinThemNow(){
chars = Arrays.asList(text.split(""));
tv.setText(toString().valueOf(chars));
for(int i=0;i<chars.size();i++){
if(toString().valueOf(chars.get(i)) == " 1"){
Toast.makeText(this,"I found One",Toast.LENGTH_LONG).show();
//This if is not working while the TV's text shows " 1"
}
}
}
}
First, just a tip, from string to char[] you can use
char[] chars = myString.toCharArray();
because it has no sense to save a char array as a string ArrayList
but now the problem. you have your string and you wanna print the text between the numbers.
It's not really clear what is your goal but lets try.
I will suppose you used the char[] because it's 10 times better and easier
case 1) you wanna print text betweens "1"s
//lets loop the chars
bool firstOneFound = false;
int firstOccurrence = -1;
int secondOccurrence = -1;
int i = 0;
for(char c : chars){
//is it equals to 1?
if(c.equals('1')){
//check if we are already after the first 1
if(firstOneFound){
//if yes, we found the final one
secondOccurrence = i;
break;
}
else{
//this is the first occurrence
firstOccurrence = i;
firstOneFound = true;
}
}
i++;
}
if(firstOccurrence != -1 && secondOccurrence != -1){
String myFinalString = myString.subString(firstOccurrence, secondOccurrence);
}
case 2) you wanna print all text except numbers (maybe with a space instead)
for(char c : chars){
//check if it's a number
if(c >= '0' && c <= '9'){
//replace the number with anything else
c = ' '; //if you wanna have it as a space
}
}
//print the final string
String myFinalString = new String(chars);
NOTE:
You can also use ArrayList of string, just replace ' with "
hope it helps
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.
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mul=0;
sum=0;
for(j=0;j<=a-1;j++){
Log.d("TAG","a ko value inside calc "+a);
et_grade_grabber=(EditText) findViewById(grade[j]);
int grade= Integer.parseInt(et_grade_grabber.getText().toString());
Log.d("TAG","Grade Value of Grade"+j+ " is "+grade);
et_credit_grabber=(EditText) findViewById(credit[j]);
int credit=Integer.parseInt(et_credit_grabber.getText().toString());
Log.d("TAG","Credit Value of Credit "+j+" is "+credit);
tot_credit= credit+tot_credit;
Log.d("TAG","Total Credit = "+tot_credit);
mul=credit*grade;
sum= sum + mul;
Log.d("Sum Inside Loop ",""+sum);
}
Log.d("TAG","Sum"+sum);
Toast.makeText(getApplicationContext(),""+sum,Toast.LENGTH_SHORT).show();
sgpa= sum/tot_credit;
tv_sgpa= new TextView(MainActivity.this);
tv_sgpa.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT));
tv_sgpa.setText("Your SGPA is "+sgpa);
tv_sgpa.setTextSize(40);
LinearLayout ll_sgpa = new LinearLayout(MainActivity.this);
ll_sgpa.setLayoutParams(new ActionBar.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
ll_sgpa.addView(tv_sgpa);
LinearLayout linear = (LinearLayout) findViewById(R.id.ll_spga);
linear.addView(ll_sgpa);
}
});
}
I have successfully create EditText fields using a for(i=0;i<4-1;i++) loop from java file and assign id by setid(Array[i]) inside a loop.
Now again I have retrive the values by method getText().toString() inside a loop for(j=0;j<4-1;j++)
When I input the values in edit text everything works fine except it only retrieves the first value of edit text to all array.
If I understood your question correctly, you should use
for(int i = 0; i < arrayOfEditTexts.size(); i++){
//if you need only some of Ids, just check conditions with `if`statement. example:
if(!((EditText)arrayOfEditTexts.get(i)).getText().toString().equalsIgnoreCase("")){
arrayOfEditTexts.get(i).getId(); // and do whatever you want
}
}
I have managed to extract the first letters on a sentence and store that into a variable.
String[] result = matches.toString().split("\\s+");
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++){
// Grab the first character of this entry
char c = result[i].charAt(0);
// If its a number, add the whole number
if (c >= '0' && c <= '9'){
abbrev += result[i];
}
// If its not a number, just append the character
else{
abbrev += c;
}
}
I then store the values into a Final String Array;
List<String> list = Arrays.asList(abbrev);
final String[] cs12 = list.toArray(new String[list.size()]);
I then set the values into a alert dialog as follows:
builder2.setItems(cs12[0].toString().split(","), new DialogInterface.OnClickListener(){
My next task is when the user selects one of the items for it to go into the text view. However it doesn't let me do this.
public void onClick(DialogInterface dialog, int item) {
TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
speechText.setText(Arrays.toString(cs12));
// TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
// speechText.setText(matches.get(item).toString());
However for my other parts matches.get works fine but I cant seem to get cs12.get.
Any Ideas?
Thanks
Use cs12[0].toString().split(",")[item] to show selected item in TextView:
String[] strArr= cs12[0].toString().split(",");
speechText.setText(strArr[item]);
I have a list view, in that list view, I have 30 items with edit text in which I manually put the value and after that I calculate the total of value set on edit text for 30 items. But problems is it calculate the total of only visible list items which are almost 10 and I need all 30 values of edit text.after 10 items view become null.
How to resolve this problem.
totalpoints.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*for (int i = 0; i < summaryList.size(); i++)
{
summaryList.get();
}*/
for (int i = 0; i < listView_subCategory.getCount(); i++) {
view = listView_subCategory.getChildAt(i);
if (view == null) {
} else {
try {
EditText text = (EditText) view
.findViewById(R.id.et_date);
TextView tv_productname=(TextView) view.findViewById(R.id.textView_userName);
String points = text.getText().toString().trim();
String productname=tv_productname.getText().toString().trim();
int point = Integer.valueOf(points);
count_summary = count_summary + point;
String truetotal = Integer.toString(count_summary);
et_total.setText(truetotal);
} catch (Exception e) {
Toast toast1 = Toast.makeText(getActivity(),
"Fill Value First", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.CENTER, 0, 0);
toast1.show();
}
}
}
count = 0;
}
});
I guess you should think fo a better approach than iterating over the EditTexts with getChildAt() to collect all the value.
I take it that the user can change the values in the EditTexts, you can have an Array of size 30 of Values and everytime the user enters / changes a value you change the according value in the Array. Use a listener that changes the values in your Array like this.