我试图将用户输入值从一个活动传递到另一个活动。在第二个活动中,Iam对数据进行一些操作并显示最终值。但它给出了一个nullpointerexception。
我的代码中有什么错误?
第一项活动:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fourth);
final EditText et;
final Button b;
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
Intent intent = new Intent(Fourth.this, Fifth.class);
intent.putExtra("thetext", et.getText().toString());
startActivity(intent);
Intent intentnew = new Intent(Fourth.this, Sixth.class);
intentnew.putExtra("thetext", et.getText().toString());
startActivity(intentnew);
}
接收和显示数据的下一个活动。(代码段)
TextView tvr = (TextView) findViewById(R.id.finalremark);
double wto=Double.parseDouble(getIntent().getExtras().getString("the text"));
double z=wto*0.75;
String weight= Double.toString(z);
tvr.setText(weight);
logcat
09-03 11:11:06.069: E/AndroidRuntime(30262): FATAL EXCEPTION: main
09-03 11:11:06.069: E/AndroidRuntime(30262): java.lang.NullPointerException
09-03 11:11:06.069: E/AndroidRuntime(30262): at com.example.footforthought.Sixth$2.handleMessage(Sixth.java:380)
09-03 11:11:06.069: E/AndroidRuntime(30262): at android.os.Handler.dispatchMessage(Handler.java:99)
09-03 11:11:06.069: E/AndroidRuntime(30262): at android.os.Looper.loop(Looper.java:137)
09-03 11:11:06.069: E/AndroidRuntime(30262): at android.app.ActivityThread.main(ActivityThread.java:4517)
09-03 11:11:06.069: E/AndroidRuntime(30262): at java.lang.reflect.Method.invokeNative(Native Method)
09-03 11:11:06.069: E/AndroidRuntime(30262): at java.lang.reflect.Method.invoke(Method.java:511)
09-03 11:11:06.069: E/AndroidRuntime(30262): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
09-03 11:11:06.069: E/AndroidRuntime(30262): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
09-03 11:11:06.069: E/AndroidRuntime(30262): at dalvik.system.NativeStart.main(Native Method)
09-03 11:11:17.969: I/Process(30262): Sending signal. PID: 30262 SIG: 9
答案 0 :(得分:2)
'文本' ..你在两者之间添加了空格..删除空间
double wto=Double.parseDouble(getIntent().getExtras().getString("thetext"));//here remove the space in name 'thetext'
double z=wto*0.75;
String weight= Double.toString(z);
tvr.setText(weight);
答案 1 :(得分:2)
检索数据时,您提供了错误的键值。 保存键值对时,请注意键 -
intent.putExtra(" thetext ",et.getText()。toString());
在检索键值对时,请注意键(有一个额外的空格。)
double wto = Double.parseDouble(getIntent()。getExtras()。getString(" 文本"));
将以上行更改为
double wto=Double.parseDouble(getIntent().getExtras().getString("thetext"));
它应该可以正常工作。