开发者

Bundle extras returning null

I'm having some problems.

In a class "A" I have the code:

Bundle extras = getIntent().getExtras();
    if ( extras == null ){
        Log.e("extras", "Extra NULL");
    }
    String arrayWatt = extras.getString("valoresWatt");
    String arrayHorario = extras.getString("valoresHorario");


Bundle extras = getIntent().getExtras();  --> this is returning NULL`
开发者_开发百科

This method throws NUllPointerException. What is the problem here? Syntax?

---EDIT---- So sorry, I forgot this code:

(This code is from another class that starts the activity)

 Intent i = new Intent();
        i.setClassName("org.me.android",
                    "org.me.android.GraphViewDemo");
        i.putExtra("valoresWatt", watt);
        i.putExtra("valoresHorario", hora);
        startActivity(i);


If you want to get the extras, this is what I would do:

Intent i = getIntent();
String arrayWatt = i.getStringExtra("valoresWatt");
String arrayHorario = i.getStringExtra("valoresHorario");


Where is the code you listed for getting the Extras located? Are you overriding the onCreate method? If so, make sure you call super.onCreate(bundleVariableName) before trying to work with the Extras. So...

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myLayout);
    // ...
    Bundle data = getIntent().getExtras();
    if (data != null ) {
        // should actually verify that the key exists, so:
        // if (data.containsKey("valoresWatt")) {
        // ... do something with the value
        String watt = data.getString("valoresWatt");
        String horario = data.getString("valoresHorario");
    }
    // ...
}


In your original code, you say that this first line is returning null:

Bundle extras = getIntent().getExtras();  // --> this is returning NULL

From the Android docs for Intent, it seems that the getExtras() method will return null if no extras have been added yet.

In that case, you may have to add your String extras by calling .putExtra(key, value) on the Intent object directly, rather than on its Map of extras, which doesn't exist yet.


For the NPE crash

Bundle extras = getIntent().getExtras();
if ( extras == null ){
    Log.e("extras", "Extra NULL");
} else {
   String arrayWatt = extras.getString("valoresWatt");
   String arrayHorario = extras.getString("valoresHorario");
}

Instead of

i.putExtra("valoresWatt", watt);
i.putExtra("valoresHorario", hora);

try

i.putStringArrayListExtra("valoresWatt", watt);
i.putStringArrayListExtra("valoresHorario", hora);

if it is an arraylist of strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜