我正在尝试在两个活动之间发送一个意图值,尽管在阅读本文后,似乎在我的第二个活动中,收到的意图为空;在运行时嵌入了NPE。
这背后的预期功能是:"用户扫描活动 A 中的代码"->"接收并打包到意图中的真实值">"活动 B 打开、解压缩意图并检查意图值是否为真">"如果为真,则活动中 ImageView 的高度将减少设定的数量"。
因此,我不确定为什么我的意图在活动 B 中被接收为空,因为我希望进行此检查,以便在活动打开时更新高度?
活动 A:
//do the handling of the scanned code being true and display
//a dialog message on screen to confirm this
@Override
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Activity Complete!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//the user has pressed the OK button
@Override
public void onClick(DialogInterface dialog, int which) {
scannerView.resumeCameraPreview(QRActivity.this);
//pack the intent and open our Activity B
Intent intent = new Intent(QRActivity.this, ActivityTank.class);
intent.putExtra("QRMethod", "readComplete");
startActivity(intent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
活动二:
// in onCreate, I check that the bundled intent is true
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tank);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
//then the extras bundle is null, and nothing needs to be called here
}
else {
String method = extras.getString("QRmethod");
if (method.equals("readComplete")) {
updateTank();
}
}
}
}
//this is the method that is called when the intent check is true
public int tHeight = 350;
public void updateTank() {
ImageView tankH = (ImageView)findViewById(R.id.tankHeight);
ViewGroup.LayoutParams params = tankH.getLayoutParams();
params.height = tHeight - 35;
tankH.setLayoutParams(params);
}
在活动 B 中,您在从 Intent 附加内容中提取 QRMethod 时出现拼写错误。您在使用"QRMethod"设置额外内容时正在使用QRmethod
。
您可以使用:
在第一个活动中("主要活动"页
(Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("QRmethod","readComplete" );
then you can get it from your second activity by :
在第二个活动中("第二个活动"页
(Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("QRmethod");
您可以在第二个活动中使用intent.getStringExtra()
这样的方法获取字符串值。
if (getIntent() != null){
getIntent().getStringExtra("QRmethod") //this s your "readComplete" value
}