java.lang.String android.os.Bundle.getString(java.lang.String)

时间:2017-08-09 03:45:26

标签: java android nullpointerexception

我的MainActivity.class通过setOnClickListener调用putExtra到SecondActivity.class

- name: create the VM
  hosts: localhost
  connection: local
  vars_files:
  - myvars.yml
  tasks:
  - vmware_guest:
      hostname: "myhost"
      username: "administrator@vsphere.local"
      password: "password"
      datacenter: dc1     
      name: 
      - name: "{{item.value.vmhost}}"   
      disk:
      - size_gb: 4
        type: thin
        datastore: Datastore1          
      networks:
      - name: VM Network
        ip: "{{item.value.vmip}}"
        netmask: 255.255.255.0
      template: rhel7_base_template    
    with_dict:
      - "{{myvms}}"
    register: deploy

SecondActivity.class setOnClickListener

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("sentString", stringName);
startActivity(intent);

ThirdActivity.class setOnClickListener

//    Recieve the extra sent from MainActivity.class
Intent SecondActivityIntent = getIntent();
String mString = SecondActivityIntent .getExtras().getString("sentString");

//    Send extra to another activity ThirdActivity.class
SecondActivityIntent.putExtra("sentString", mString);
startActivity(SecondActivityIntent); 

ThirdActivity.class正在导致

  对空引用引用

'java.lang.String android.os.Bundle.getString(java.lang.String)'

这个错误是什么意思?是因为SecondActivity.class期望从任何调用活动获得额外的?我不打算把它放在ThirdActivity上,或者我强迫它。怎么解决这个问题?

3 个答案:

答案 0 :(得分:1)

  

是因为SecondActivity.class期望从任何调用活动获得额外的东西吗?

是。

  

如何解决这个问题?

设置默认值和空检查

//    Receive the extra sent from MainActivity.class
Bundle extras = getIntent().getExtras();
String mString = "default";

if (extras != null) {
    mString = extras.getString("sentString");
}

答案 1 :(得分:1)

将其改为这样 FirstActivity

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("sentString", stringName);
startActivity(intent);

在SecondActivity中

//    Recieve the extra sent from MainActivity.class
Intent SecondActivityIntent = getIntent();
String mString = SecondActivityIntent .getStringExtra("sentString");
//    Send extra to another activity ThirdActivity.class
Intent thirdIntent = new Intent(SecondActivity.this, ThirdActivity.class);
thirdIntent.putExtra("sentString", mString);
startActivity(thirdIntent); 

The ThirdActivity

//    Recieve extra from SecondActivity.class
Intent thirdActivityintent = getIntent();
String mString = thirdActivityintent.getStringExtra("sentString");
//    Just finish Activity
finish();

答案 2 :(得分:0)

更改

.getExtras().getString("sentString");

.getExtras().getString("sentString", "defaultValue");