It is necessary to transfer data to ShareActionProvider (to be able to implement the share button) But the data taken from onCreate() not visible in the external method

How to implement a transfer with EditText ?

Activity code:

 public class MainActivity extends ActionBarActivity { private ShareActionProvider mShareActionProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText editText = (EditText)findViewById(R.id.editText1); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); MenuItem menuItem = menu.findItem(R.id.action_share); EditText editText = (EditText)findViewById(R.id.editText); mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem); mShareActionProvider.setShareIntent(createShareIntent()); return true; } private Intent createShareIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); // не видит параметр editText c onCreate() shareIntent.putExtra(Intent.EXTRA_TEXT, editText); return shareIntent; } 

Markup:

 <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" /> 
  • I apologize for the formatting of the code I can not understand how to insert the code on stackoverflow so that it appears normally - mtb

2 answers 2

First , you can make editText private field of the MainActivity class:

 class MainActivity extends Activity { private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText)findViewById(R.id.editText1); } // ... } 

Secondly , you can call findViewById immediately in the createShareIntent method:

 private Intent createShareIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); EditText editText = (EditText)findViewById(R.id.editText); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, editText.getText().toString()); return shareIntent; } 
  • Why make it private? private EditText editText; - mtb

Create a field:

 private ShareActionProvider mShareActionProvider; private EditText edittext = null; //вот это поле 

Now in onCreate :

 editText = (EditText)findViewById(R.id.editText1); 

And now in createShareIntent

 shareIntent.putExtra(Intent.EXTRA_TEXT, editText.getText.toString());