When user click the button , the age is 50. After that, when sending data using nfc,the value of age is 0.0. Help! How I can solve it ?
public class MainActivity extends Activity{
String mone;
InputStream is =null;
double age;
double app=50.00,water=60.88,ban=35.55;
boolean app_b=true, water_b=true, ban_b=true;
private ViewFlipper viewFlipper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
String te = new String(msg.getRecords()[0].getPayload());
mone=te;
Log.e("value 2 ","val"+age); //age is 0.0
}
}
public void onNewIntent(Intent intent) {
setIntent(intent);
}
public void onClick(View v) {
if (v.getId() == R.id.apple)
app_b=false;
else if (v.getId() == R.id.watermelon)
water_b=false;
else if (v.getId() == R.id.banana)
ban_b=false;
}
public void aniStart(){
// Next screen comes in from right.
viewFlipper.setInAnimation(this, R.anim.slide_in_from_right);
// Current screen goes out from left.
viewFlipper.setOutAnimation(this, R.anim.slide_out_to_left);
// Display previous screen.
viewFlipper.showPrevious();
}
public void submit(View v){
if(v.getId() == R.id.button && (!app_b || !water_b || !ban_b)){
if (!app_b)
age=app;
else if (!water_b)
age=water;
else if (!ban_b)
age=ban;
aniStart();
Log.e("Value","age:"+age); //age=50;
}
else {
Toast.makeText(getApplicationContext(),"please select your fruit",Toast.LENGTH_LONG).show();
}
}
}
Why age is 0.0 ?
UPDATE :
This app is actually receive data from another phone via NFC. Before tapping the phone , I click on the button and get the value 50. After that , I receive data from another phone and hold the string value in "te".
Currently your variable is getting updated when button is clicked but if you want to assign a value to age when checking intent then you can pass a double in the Intent that started this activity using putExtra(String key, double value) in that intent.
uhm onCreate gets called first and age has no value assigned.
Age is showing up as 0.0 because:
This is the default value given to an unassigned double in java(double age; // age = 0.0)
The onCreate() method runs as soon as your activity 'starts up' (before you can click your button) so the log statement will always print whatever value you initialize the age variable to (in this case that's 0.0).
Put this code in onClick():
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Log.e("nfc","insidenfc"+age); //age is 0.0
}
Related
I am making this eCommerce app,
And, i wanted this behaviour in it.
Which is-
At the opening, there will be pitures in the MainActivity.
And a search box.
When you click the picture it will take you to MainActivity2 and there is an ImageView in this activity which will change to become the same picture as the picture I clicked in MainActivity.
And
When you search something in the search box in the MainActivity,
if your searched text matches with the string object of the arraylist in the MainActivity2,
it will change the ImageView of MainActivity2 with the corresponding image of the string object of the arraylist.
I hope, i made minimum grammatical mistakes to make you understand my problem. 😅
Anyways,
For the first case-
I tried to make this work by using On touchListeners, Intenets and booleans.
As you can see in the code below,
touching my ImageView(iBtn1) will trigger Intent intent1, make boolean i1
=true and then send the boolean to next activity in the name "t1".
And ,
For the second case-
I tried using OnClickListeners, Intenets, arraylists and booleans.
First,
I changed the Edittext(input) into string.
For clicking the search Button(igo),
it will trigger Intent intent,
Then it will send the string Data of the input as "eText" and send boolean data x=true, as "x".
public class MainActivity extends AppCompatActivity {
EditText input;
ImageView iBtn1;
TextView tName, tPrice, tDescription;
ImageView iImage;
Button igo;
String eText;
boolean i1,x;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i1=false;
x=false;
igo=findViewById(R.id.go);
iBtn1=findViewById(R.id.Btn1);
input=findViewById(R.id.edittext);
eText=input.getText().toString();
igo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x=true;
Intent intent=new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("eText",eText);
intent.putExtra("x",x);
startActivity(intent);
}
});
iBtn1.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
iBtn1.setBackground(ContextCompat.getDrawable(getApplicationContext(),R.drawable.ectangle_31_1));
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
iBtn1.setBackground(ContextCompat.getDrawable(getApplicationContext(),R.drawable.ectangle_31));
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
i1=true;
Intent intent1=new Intent(MainActivity.this,MainActivity2.class);
intent1.putExtra("t1",i1);
startActivity(intent1);
v.performClick();
v.setPressed(false);
return false;
} else {
return false;
}
});
In the next activity-
For my first case-
My target ImageView is iImage.
But at first, what i did was, get the (boolean) data from the previous Intent intent1 to the current Intent I1.
Then i have declared a variable(x1) containing the value of that boolean data.
Then i have implemented an if condition,
If x1 is true, it will change the image resource of the ImageView iImage.
Else, nothing happens.
And, for my 2nd case-
I have this arraylist made up. It contained string data as xName and imageId as xImageId.
Anyways,
First i got the string data from "eText" and boolean data using getIntent.
Then implementating if condition, i tried to compare the string data with the string of arraylist.
If it is equal.
Then i told the programm to change the ImageView just like the case-1
And, i got the data
public class MainActivity2 extends AppCompatActivity {
String eName;
boolean bx;
ImageView iImage;
TextView iname;
Intent I1,intent;
ArrayList<x> xList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
iImage=findViewById(R.id.xblock);
iname=findViewById(R.id.xname);
xList=new ArrayList<>();
xList.add(new x("engineer",R.drawable.ectangle_32));
xList.add(new x("Artists", R.drawable.ectangle_31));
xList.add(new x("Singers",R.drawable.ectangle_33));
xList.add(new x("Lawyer",R.drawable.ectangle_37));
xList.add(new x("Writters",R.drawable.ectangle_38));
xList.add(new x("developer",R.drawable.ectangle_36));
I1=getIntent();
intent=getIntent();
eName = intent.getStringExtra("eText");
bx = intent.getBooleanExtra("x",false);
if (bx=true) {
String yname = eName.toLowerCase();
for (x yList : xList) {
String xname = yList.getxName().toLowerCase();
if (xname.equals(yname)) {
iname.setText(yList.getxName());
iImage.setImageResource(yList.getxImageId());
}
}
}
boolean x1= intent.getBooleanExtra("t1",false);
if (x1=true){
iImage.setImageResource(R.drawable.ectangle_31);
}
else{x1 = false;}
}
}
But, my app crashes,
It can't get to MainActivity2,
And when check the problem in MainActivity2, it say that my variable is not assigned.
What is the problem here?
Thanks a lot for reading, all this gibberish writing.
Please let me know if i hade made any mistakes.
I think the problem is in getting boolean bx
It shouldbe like this
boolean bx = getIntent().getBooleanExtra(x);
try it if it works
I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}
I am trying to make a simple android app in which 2 text fields are there.input range is 0 to 15. If the number is in range than addition is performed.
i have implemented input varification so now if the edit text is empty it shows empty field warning. but calculation is not done. what i want is if the field is empty is should show the error but also do the addition by take default value as 0.
here is my code
public class MainActivity extends AppCompatActivity {
private EditText check,check2;
private TextView textView;
private TextInputLayout checkLay,checkLay2;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgets();
initializeListeners();
}
private void initializeWidgets(){
check=findViewById(R.id.check);
check2=findViewById(R.id.check2);
checkLay2=findViewById(R.id.checkLay2);
checkLay=findViewById(R.id.checkLay);
button=findViewById(R.id.button);
textView=findViewById(R.id.textView);
}
private void initializeListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signUp();
}
});
}
private void signUp(){
boolean isVailed=true;
int a1,a2;
String one=check.getText().toString();
String two=check2.getText().toString();
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
else {
if (one.length() > 0)
{
a1=Integer.parseInt(one);
if(a1> 15){
checkLay.setError("quiz marks must be less than 15");
isVailed=false;
}
else if(a1 <=15)
{
checkLay.setErrorEnabled(false);
isVailed=true;
}
}
}
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
isVailed=false;
}
else{
if (two.length() > 0)
{
a2=Integer.parseInt(two);
if(a2 > 15)
{ checkLay2.setError("quiz marks must be less than 15");
isVailed=false;
}
else
if(a2 <=15)
{
checkLay2.setErrorEnabled(false);
isVailed=true;
}
}
if(isVailed)
{
int total;
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
total=a1+a2;
textView.setText(String.valueOf(total));
}
}
I would do it differently but for your specific question
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
Change to
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1=0;
}
Same for the two.isEmpty()
If a field is empty you set isVailed to false and thus say not to add the numbers. Instead you want to set the corresponding number to zero and let isVailed be true:
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1 = 0;
}
and
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
a2 = 0;
}
Also throw off the lines
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
You already convert inputs to a1 and a2 earlier.
A piece of advice: you have doubled code. It's better to use functions for such pieces of codes.
add this line in your initializeWidgets function
yourEditText.setText(0);
follow link for more help: duplicate
You can create a convenience method to get value from your edittext. The following code will return 0 if edittext is empty else the value from the edittext
private int getIntFromEditText(EditText editText) {
return editText.getText().length()>0 ? Integer.parseInt(editText.getText().toString()):0;
}
Call it by passing EditText as a parameter, e-g
a1=getIntFromEditText(check)
I have been trying to build a simple calculator in android studio. Everything is fine but i have a problem, when i run the calculator and i press the dot button, it shows in the textview "." instead "0."
Also, i need to check the existence of two decimal points in a single numeric value.
here is an image:
it shows "."
and i want:
how can i change this??, here is my code:
private int cont=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display=(TextView)findViewById(R.id.display);
text="";
}
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
display.setText(text);
}
public void dot(View view){ /*This is not finished*/
display.setText{"0."}
}
I was thinking in creating another method for the dot button, but the content of the text value disappears when i press another button, how to fix this?
try this
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
if(text.substring(0,1).equals("."))
text="0"+text;
display.setText(text);
}
try this way
public void dot(View view){ /*This is not finished*/
String str=display.getText().toString().trim();
if(str.length()>0){
display.seText(str+".")
}else{
display.setText("0.")
}
}
Use a string builder and append all the text entered to already existing string. Before display, just use the toString() method on the string builder.
Create a class that represents your character sequence to be displayed and process the incoming characters.
For example:
class Display {
boolean hasPoint = false;
StringBuilder mSequence;
public Display() {
mSequence = new StringBuilder();
mSequence.append('0');
}
public void add(char pChar) {
// avoiding multiple floating points
if(pChar == '.'){
if(hasPoint){
return;
}else {
hasPoint = true;
}
}
// avoiding multiple starting zeros
if(!hasPoint && mSequence.charAt(0) == '0' && pChar == '0'){
return;
}
// adding character to the sequence
mSequence.append(pChar);
}
// Return the sequence as a string
// Integer numbers get trailing dot
public String toShow(){
if(!hasPoint)
return mSequence.toString() + ".";
else
return mSequence.toString();
}
}
Set such a click listener to your numeric and "point/dot" buttons:
class ClickListener implements View.OnClickListener{
#Override
public void onClick(View view) {
// getting char by name of a button
char aChar = ((Button) view).getText().charAt(0);
// trying to add the char
mDisplay.add(aChar);
// displaying the result in the TextView
tvDisplay.setText(mDisplay.toShow());
}
}
Initialize the display in onCreate() of your activity:
mDisplay = new Display();
tvDisplay.setText(mDisplay.toShow());
I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.
Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)
if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.
test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.