Can't to sum array elements? - java

I'm very new in Android programming, and i'm trying to sum all char elements from datepicker, but with no success.
here is code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = (TextView)findViewById(R.id.textView1);
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
final int day = dp.getDayOfMonth();
final int month = dp.getMonth();
final int year = dp.getYear();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = 0;
String sdate = String.valueOf(month) + String.valueOf(day) + String.valueOf(year);
char[] c = sdate.toCharArray();
for(int i=0; i<c.length;i++)
{
num+=Integer.valueOf(c[i]);
}
tv.setText(String.valueOf(num));
}
});
}
and output is: 355.
Real sum must to be 20, i want to sum like this 17/06/2013,
so example 1+7+0+6+2+0+1+3 = 20

use Character.getNumericValue
for(int i=0; i<c.length;i++) {
num+=Character.getNumericValue(c[i]);
}

This will work
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = (TextView)findViewById(R.id.textView1);
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
final int day = dp.getDayOfMonth();
final int month = dp.getMonth();
final int year = dp.getYear();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = 0;
String sdate = String.valueOf(month) + String.valueOf(day) + String.valueOf(year);
int[] ee=new int[sdate.length()];
String[] dd=new String[sdate.length()];
for(int i=0;i<sdate.length();i++){
dd[i]=sdate.substring(i,i+1);
ee[i]=Integer.parseInt(dd[i]);
num+=ee[i];
}
tv.setText(String.valueOf(num));
}
});
}

Change from Integer.valueOf() to Character.valueOf() Integer.valueOf(int) takes integer, your char is being cast to int and gives ASCII value.

Related

Java/Android : First tiny app answer always "false"

I try to create my first tiny app but i have a problem.
My tiny math app always say my answer is false.I don't understand why.
This is my first app, i don't know where i'm wrong.
private TextView problem;
private EditText question;
private Button button;
private TextView reponse;
private int aleatoire = new Random().nextInt(61) + 20;
private int aleatoire2 = new Random().nextInt(48) + 20;
private int result = aleatoire + aleatoire2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
problem = (TextView) findViewById(R.id.problem);
question = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
reponse = (TextView)findViewById(R.id.resultat);
problem.setText("Result = "+aleatoire+"+"+aleatoire2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str=question.getText().toString();
if (str.equals(result)) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}
}
});
Answer always "False"
I'm a new student in the dev world.
The problem with code is that you are comparing string with integer, that's why it always returns false as java is strictly typed language.
problem code:
if(str.equals(result)){...}
possible solutions:
if( str.equals(""+result)){...}
or
str.equals(String.valueof(result)) // best solution
or
if(result==Integer.parseInt(str)){...}
Here is corrected code:
private TextView problem;
private EditText question;
private Button button;
private TextView reponse;
private int aleatoire = new Random().nextInt(61) + 20;
private int aleatoire2 = new Random().nextInt(48) + 20;
private int result = aleatoire + aleatoire2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
problem = (TextView) findViewById(R.id.problem);
question = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
reponse = (TextView)findViewById(R.id.resultat);
problem.setText("Result = "+aleatoire+"+"+aleatoire2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str=question.getText().toString();
if (str.equals(""+result)) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}
}
});
As azurefrog comment says, you're comparing a String to an int. You will need to transform str to an int or result to a String. You can for example do:
String str=question.getText().toString();
if (str.equals(String.valueOf(result))) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}

how do I add a method in android studio?

Here is my code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtFirstNum = (EditText) findViewById(R.id.txtFirstNum);
final EditText txtSecondNum = (EditText) findViewById(R.id.txtSecondNum);
final TextView txtResult = (TextView) findViewById(R.id.lblResult);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int num1 = Integer.parseInt(txtFirstNum.getText().toString());
int num2 = Integer.parseInt(txtSecondNum.getText().toString());
int result = num1 + num2;
txtResult.setText(result + "");
}
});
Button btnSub = (Button) findViewById(R.id.btnSub);
btnSub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int num1 = Integer.parseInt(txtFirstNum.getText().toString());
int num2 = Integer.parseInt(txtSecondNum.getText().toString());
int result = num1 - num2;
txtResult.setText(result + "");
}
});
}
}
what I essentially want to do is use a method which I can call instead of repeating the same lines of code kind of like this (which does not work):
int num1;
int num2;
btnAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
getNumbers();
int result = num1 + num2;
txtResult.setText(result + "");
}
});
...
private void getNumbers()
{
num1 = Integer.parseInt(txtFirstNum.getText().toString());
num2 = Integer.parseInt(txtSecondNum.getText().toString());
}
Why don't you create two similar to getNumber methods but not void
private int getFirstNumber()
{
return Integer.parseInt(txtFirstNum.getText().toString());
}
private int getSecondNumber()
{
return Integer.parseInt(txtFirstNum.getText().toString());
}
and use them in:
#Override
public void onClick(View v)
{
int result = getFirstNumber() + getSecondNumber();
txtResult.setText(result + "");
}
you have to make num1 et num2 properties of the class

Application Crashed when trying to input on an edittext that has an TextChangedListener

I was trying to create an application that automatically calculate the percentage. the Percentage value will be shown in a TextView. The value that will be shown in the textview will be based on the inputted value of the user in an edittext.
I've finished creating my codes for this program but, it keeps crashing every time i tried to input some numbers in the edittext.
I hope you understand what am i saying.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample__table);
btnAdd = (Button)findViewById(R.id.btnAdd);
//btn Function
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AddRow();
}
});
//end of btn function
//text changed
tl = (TableLayout) findViewById(R.id.tl);
row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
fruit = new EditText(this);
freq = new EditText(this);
perc = new TextView(this);
freq.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ReCalculate();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
//text changed end
}
private void AddRow(){
row.addView(fruit);
row.addView(freq);
row.addView(perc);
tl.addView(row);
}
private void ReCalculate(){
float sum = 0f;
int rows = tl.getChildCount();
// Get the total
for (int i = 0; i < rows; i++) {
TableRow elem = (TableRow) tl.getChildAt(i);
sum+= Integer.parseInt(((EditText)elem.getChildAt(1)).getText().toString());
}
// Recalculate every row percent
for (int i = 0; i < rows; i++) {
TableRow elem = (TableRow) tl.getChildAt(i);
int amount​ = Integer.parseInt(((TextView)elem.getChildAt(1)).getText().toString());
((TextView)elem.getChildAt(1)).setText(String.valueOf(amount​/sum*100));
}
}
}
If you want to detect your text's change, you can use onKeyListener:
EditText edtText = (EditText)findViewById(R.id.editText);
edtText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
Toast.makeText(MainActivity.this, "Text changed!", Toast.LENGTH_SHORT).show();
return false;
}
});
it worked for me, hope it helps.

Spinner value is not captured

Please, do not mark this as duplicate if you are not sure
I have three spinners and a botton. When the botton is clicked, the program makes a calculation depending on the value of the three spinners. Then this value passes two another activity and it shows in an editText. Here is my code:
Main
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
capturarTexto();
}
private void capturarTexto() {
Button button_calc = (Button) findViewById(R.id.button_calc);
button_calc.setOnClickListener(get_edit_view_button_listener);
}
private Button.OnClickListener get_edit_view_button_listener = new Button.OnClickListener() {
public void onClick(View v) {
EditText edit_text = (EditText) findViewById(R.id.textBox1);
String edit_text_value = edit_text.getText().toString();
StringTokenizer st = new StringTokenizer(edit_text_value);
int num_words = st.countTokens();
Spinner espec = (Spinner) findViewById(R.id.espec);
String espec_value = espec.getSelectedItem().toString();
Spinner lengor = (Spinner) findViewById(R.id.lista_origen);
String lengor_value = lengor.getSelectedItem().toString();
Spinner lengdest = (Spinner) findViewById(R.id.lista_destino);
String lengdest_value = lengdest.getSelectedItem().toString();
double precio = 0;
if(espec_value .equals("Medicina")){
if (lengor_value .equals("ES") && lengdest_value .equals("EN")){
precio = num_words * 0.12;
}
if (lengor_value .equals("ES") && lengdest_value .equals("FR")){
precio = num_words * 0.12;
}
if (lengor_value .equals("ES") && lengdest_value .equals("DE")){
precio = num_words * 0.12;
}
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("precio",precio);
startActivity(intent);
}
};
}
Main2
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent=getIntent();
int precio =(int) intent.getExtras().getInt("precio");
TextView txtCambio = (TextView) findViewById(R.id.textView4);
txtCambio.setText("Precio Total: "+ precio + " €");
}
After testing it, the value passed in this line of code:
intent.putExtra("precio",precio)
is allways 0. But if I change it to this:
intent.putExtra("precio",num_words)
it passes correctly the total number of words. This makes me think that the script is not entering in the first if(espec_value .equals("Medicina")) and then, it is not making any calculation.
Does anyone have an idea of how to solve this problem?
Thank you for your time
You are sending Double value and accessing Integer value.
Change the line in Main3Activity.
double precio = intent.getExtras().getDouble("precio");
If you want to parse double value to int then add one more line
int p = (int) precio;

android application crash after launch

public class Game extends AppCompatActivity {
static int i = 0;
static int p = 0;
String porc0;
TextView tvporc;
Button btn;
TextView tvresult;
String mutqbar;
char generacvac;
char mutq;
int mutqitiv;
int generacvacitiv;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Random random = new Random();
btn = (Button) findViewById(R.id.button4);
tvporc=(TextView) findViewById(R.id.tvPorc);
tvresult=(TextView) findViewById(R.id.result);
generacvac=(char)(random.nextInt(26)+'a');
tvresult.setText(generacvac);
generacvacitiv = (int) generacvac;
et=(EditText) findViewById(R.id.editText2);
tvresult.setText(generacvac);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mutqbar = et.getText().toString();
try {
mutq = mutqbar.charAt(0);
mutqitiv = (int) mutq;
if (mutqitiv<97 || mutqitiv>122){
tvporc.setText("Մուտքագրեք տառ");
}
int abs = Math.abs(mutqitiv-generacvacitiv);
if (abs>0 && abs<5) tvresult.setText("Դու շատ մոտ ես!");
else if (abs>=5 && abs<10) tvresult.setText("Դու մոտ ես~");
else if(abs>=10) tvresult.setText("Դու հեռու ես~");
} catch (Exception e1) {
tvresult.setText("Դաշտը դատարկ է");
}
}
});
}}
I have this code, but when I run it, it returns error java.lang.RuntimeException: Unable to start activity ComponentInfo{com.guessit.guessit/com.guessit.guessit.Game}: android.content.res.Resources$NotFoundException: String resource ID #0x66. and crush on device.Already 1 hour I'm trying to find the problem. please help me
Thanks I already find the solution. I writed tvresult.setText(generacvac); but it cast to int, and I need to write tvresult.setText(generacvac+"")

Categories