Today I finish the test I met at previous job interview: achieve a additon program. A simple program, only use 3 TextView, 2 Button and 2 EditView. But I got stuck in getting the results. Well now I know what problem is, the truth is that I can't get EditView's data while I don't konw wether it has been writen data in.
Wrong code:
JiaShu = (EditText)findViewById(R.id.editText2);
float J = Float.valueOf(JiaShu.getText().toString());//Sentence 1
To make this available, make a empty judgement is good.
if(!TextUtils.isEmpty(JiaShu.getText())){//Then do sentence 1}
A little summary:
1. Using Bundle
Code:
Intent backIntent = new Intent();
Bundle myBundle = new Bundle();
final float sum = Float.valueOf(beijiashu)+Float.valueOf(JiaShu.getText().toString());
myBundle.putString("sum",String.valueOf(sum));
backIntent.putExtras(myBundle);
2. Launch a specific Activity and returns the result
Using startActivityForResult(Intent intent, Int int) instead of startAcitvity(Intent intent),Then Override onActivityResult(...):
//In Acitvity A
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//REQUESTCODE is the Int arg in startActivityForResult(Intent intent, Int int)
if(requestCode==REQUESTCODE){
//resultCode is set in other Activities, use to response different actions
if(resultCode==1){
Beijiashu.setText("");
Bundle bundle = data.getExtras();
String result = bundle.getString("sum");//get the sum from Activity B
myTextView.setText("The sum is:"+result);
}
}
}
//In Activity B
//In button's click response
Intent intent = new Intent();
setResult(1,intent);//1 means resultsCode's value
finish();//kill this Activity
3. Some tips
When difine a global var(static), always ues key word final to make it unchangeable.
When difine Widgets or Text Fields, always difine it at the first line of the main class, like:
public class MainActivity extends AppCompatActivity {
private TextView myTextView;
private EditText Beijiashu;
...