Search code examples
javaandroideclipseandroid-arrayadapter

How can I share the content of an Adapter?


I want to share the full content of an adapter when the user press on the positive button of a dialog. Tried this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

adapter.add("String1");
adapter.add("String2");
adapter.add("String3");
adapter.add("String4");

dialog.setPositiveButton("Share", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            Intent intent = new Intent ();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            for(int i = 0; i <= adapter.getCount(); i++){
                intent.putExtra(Intent.EXTRA_TEXT, adapter.getItem(i));
            }
            startActivity(Intent.createChooser(intent, "Share via")
            );
        }
    });

It doesn't work. It makes the app to crash when the Share button is pressed. Any ideas?

edit: Thanks for all the help. this is the final solution:

StringBuilder sb = new StringBuilder();
for(int i = 0; i < adapter.getCount(); i++){
    sb.append(adapter.getItem(i)).append("\n");
}
intent.putExtra(Intent.EXTRA_TEXT, (CharSequence) sb );

Solution

  • Try this:

    for(int i = 0; i < adapter.getCount(); i++){
        intent.putExtra(Intent.EXTRA_TEXT, adapter.getItem(i));
    }
    

    This will solve your problem.