Issue
I'm trying to create an app that checks which number out of 2 numbers you input, is the bigger one, and display the result in another activity.
I tried to use getIntExtra() too but it didn't work and there is no error its just not working.
Main Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button check=findViewById(R.id.checkButton);
check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent Check=new Intent(getApplicationContext(), BiggerNum.class);
EditText N1EditText=findViewById(R.id.editTextN1);
int num1=Integer.parseInt(N1EditText.getText().toString());
EditText N2EditText=findViewById(R.id.editTextN2);
int num2=Integer.parseInt(N2EditText.getText().toString());
Check.putExtra("com.example.testapp.num1",num1);
Check.putExtra("com.example.testapp.num2",num2);
startActivity(Check);
}
});
}
}
Second Activity:
public class BiggerNum extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (getIntent().hasExtra("com.example.testapp.num1")){
int num1=getIntent().getExtras().getInt("num1");
int num2=getIntent().getExtras().getInt("num2");
TextView bigger=findViewById(R.id.biggerNView);
bigger.setText((Math.max(num1,num2)));
}
}
}
Edit: The problem in my code was as forpas explained. Anyways, the better way to use keys is to create the keys as static finals in the class you would pass them to, and then use them:
public class BiggerNum extends AppCompatActivity {
public static final String FIRST_NUM_KEY = "num1";
public static final String SECOND_NUM_KEY= "num2";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
int num1= 0;
int num2 = 0;
if (getIntent().hasExtra(FIRST_NUM_KEY)){
int num1 = getIntent().getExtras().getInt(FIRST_NUM_KEY);
}
if (getIntent().hasExtra(SECOND_NUM_KEY)){
int num1 = getIntent().getExtras().getInt(SECOND_NUM_KEY);
}
TextView bigger=findViewById(R.id.biggerNView);
bigger.setText((Math.max(num1,num2)));
}
}
Solution
The keys of the 2 extras are "com.example.testapp.num1"
and "com.example.testapp.num2"
, so you must use these to retrieve them and not "num1"
and "num2"
:
if (getIntent().hasExtra("com.example.testapp.num1") && getIntent().hasExtra("com.example.testapp.num2")){
int num1=getIntent().getExtras().getInt("com.example.testapp.num1");
int num2=getIntent().getExtras().getInt("com.example.testapp.num2");
TextView bigger=findViewById(R.id.biggerNView);
bigger.setText(String.valueOf(Math.max(num1,num2)));
}
Answered By - forpas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.