Android: passing data back and forth using intent setResults

android, android-intent

Solution

You do not need an intent for a specific component. You only need an empty intent. So replace

Intent result = new Intent(LocNames.this, Main.class);

with

Intent intent = new Intent();

Problem

I am creating a GPS based app for Android and there are 2 activities Main and LocNames. Main shows my map and LocNames is to get source and destination that user wants. I want to start LocNames when user selected it from menu, user enters names in boxes and I want result to be send back to Main. But I am getting exceptions in doing so. Here is how my Main calls LocNames: ``` public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.showMyLocation: showCurrentLocation(); break; case R.id.showRoute: Intent getLocationsIntent = new Intent(Main.this, LocNames.class); startActivityForResult(getLocationsIntent, 1); break; } ``` Here is how I am trying to set results in onClick of LocNames: ``` public void onClick(View v) { // TODO Auto-generated method stub source = sourceText.getText().toString(); destination = destinationText.getText().toString(); Intent result = new Intent(LocNames.this, Main.class); result.putExtra("src", source); result.putExtra("dest", destination); setResult(RESULT_OK, result); } ``` But my application crashed when I try to use result returned by LocNames ``` protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 1 && resultCode == RESULT_OK) { source = data.getStringExtra("src"); destination = data.getStringExtra("destination"); } } ``` I have no prior experience in using setResults but documentation says it takes an int and an intent as argument so I am creating intent for that but I get NullPointerException in OnClick of LocNames. Regards

Original source