Transfer data between Activitys

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; 

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值