как я могу отправить несколько содержимого через намерение в студии Android

я хочу отправить текст и изображение как через намерение, но ничего не отправляется, код, который я использовал, упоминается здесь; я пытаюсь отправить информацию о вводе и нажатом изображении через намерение; пожалуйста, скажите мне, где это происходит не так, и есть ли другой способ отправить щелкнутое изображение?

MAINACTIVITY.JAVA:

public class MainActivity extends AppCompatActivity {
CheckBox cb1, cb2;
Button export, button;
//ImageView img;
Uri file;
EditText name, age, address, phone;
String genderr, namee, agee, addr, num;
private static final int CAMERA_REQUEST = 1888;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    export = findViewById(R.id.button);
    cb1 = findViewById(R.id.male);
    cb2 = findViewById(R.id.female);
    imageView = (ImageView) this.findViewById(R.id.imageView1);
    Button photoButton = (Button) this.findViewById(R.id.button1);
    photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
    export.setOnClickListener(new View.OnClickListener()
    {
            @Override
            public void onClick(View view) {
                name = findViewById(R.id.et_name);
                name.setTypeface(null, Typeface.BOLD);
                age = findViewById(R.id.et_age);
                age.setTypeface(null, Typeface.BOLD);
                address = findViewById(R.id.address);
                phone = findViewById(R.id.phone);
                if (cb1.isChecked()) {
                    cb2.setChecked(false);
                    genderr = cb1.getText().toString();
                } else if (cb2.isChecked()) {
                    cb1.setChecked(false);
                    genderr = cb2.getText().toString();
                }

                final String content = "NAME: " + name.getText().toString() + "\n AGE: " + age.getText().toString() + "\n Gender: " + genderr + "\n ADDRESS: " + address.getText().toString() + "\n Phone: " + phone.getText().toString()+"\n IMAGE:";
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setType("text/plain");
                sendIntent.putExtra(Intent.EXTRA_TEXT, content);
            sendIntent.putExtra(Intent.EXTRA_STREAM, (Parcelable) imageView);
              //  Intent sendIntent = new Intent(Intent.ACTION_PICK);
                sendIntent.setType("image/*");
              //  startActivityForResult(in, imageView);
                //  sendIntent.putExtra(Intent.EXTRA_TEXT, extraParams);
                startActivity(Intent.createChooser(sendIntent, "Send Using.."));
            }
        });
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQUEST) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);

АКТИВНОСТЬ_MAIN:

  <ScrollView
    android:id="@+id/scrollView2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="1dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/name"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

        <TextView
            android:id="@+id/textView2"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:text="@string/age"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/et_age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />

        <TextView
            android:id="@+id/textView3"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/gender"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <CheckBox
            android:id="@+id/male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:onClick="onCheckboxClicked"
            android:text="@string/m"
            android:textSize="24sp" />

        <CheckBox
            android:id="@+id/female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:onClick="onCheckboxClicked"
            android:text="@string/f"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/address"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPostalAddress" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="match_parent"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:text="@string/phone"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold" />

        <EditText
            android:id="@+id/phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/camera"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold"/>

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="281dp"
            android:layout_height="154dp"
            android:layout_above="@+id/button1"
            android:layout_alignParentTop="false"
            android:layout_gravity="center_horizontal"
            app:srcCompat="@drawable/ic_launcher_background" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="30dp"
            android:layout_marginBottom="24dp"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/img"
            android:textSize="24sp" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="30dp"
            android:layout_marginBottom="24dp"
            android:background="#72C8E8"
            android:padding="4sp"
            android:paddingLeft="4sp"
            android:paddingTop="4sp"
            android:paddingRight="4sp"
            android:paddingBottom="4sp"
            android:text="@string/export"
            android:textSize="24sp" />

    </LinearLayout>
</ScrollView>

МАНИФЕСТ:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission-sdk-23 android:name="android.permission.CAMERA"/>
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature
    android:name="android.hardware.camera"
    android:required="false"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


person Community    schedule 15.04.2020    source источник
comment
Отвечает ли это на ваш вопрос? Как совместно использовать изображение и текст с помощью ACTION_SEND в андроид?   -  person Ravi    schedule 15.04.2020
comment
да, это частично действительно проблема в том, что нужно отправить изображение, только что щелкнув, через само приложение   -  person    schedule 15.04.2020
comment
Вам нужно получить URI изображения и передать его через намерение,   -  person Ravi    schedule 15.04.2020
comment
Платформа, такая как Facebook, принимает только изображение, когда отправляется и изображение, и текст, поэтому попробуйте другое приложение, например WhatsApp.   -  person Ravi    schedule 15.04.2020
comment
я пытался получить uri, но при этом он показывает, что метаданные не существуют, можете ли вы помочь с тем, как получить uri для изображения   -  person    schedule 15.04.2020


Ответы (1)


В onActivityResult() проверьте код запроса и сохраните растровое изображение, чтобы получить его URI.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        imageView.setImageBitmap(photo);
        Uri imageUri = getImageUri(getApplicationContext(), photo);
        shareImageText(imageUri);
    }  
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

делиться изображением и текстом с помощью намерения, например

private vois shareImageText(Uri uri)  {
    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra(Intent.EXTRA_TEXT,"Dummy Text");
        intent.setType("image/*");
        startActivity(Intent.createChooser(intent,"Share"));
}

Надеюсь, это поможет.

person Ravi    schedule 15.04.2020
comment
@ayushisinha добавил это, пожалуйста, проверьте - person Ravi; 15.04.2020
comment
эй, в этом приложении происходит сбой после нажатия на изображение на устройстве вместо того, чтобы изображение отображалось в приложении, в то время как на эмуляторе оно работает нормально - person ; 17.04.2020
comment
Растровое фото = (Растровое изображение) data.getExtras().get(data); здесь для getExtras () он показывает исключение нулевого указателя ошибки, поэтому, когда я добавил object.requirenonull, ему требуется минимальный SDK 19, поэтому, если я сделаю его 19, приложение не работает на более старых версиях Android - person ; 17.04.2020
comment
это показанная ошибка: E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NoClassDefFoundError: java.util.Objects при добавлении: @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onActivityResult(int requestCode, int resultCode , Данные намерения) { super.onActivityResult (код запроса, код результата, данные); if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { Растровое фото = (Растровое изображение) (Objects.requireNonNull(data.getExtras())).get(data); imageView.setImageBitmap(фото); - person ; 17.04.2020
comment
эй, вы ответили на миниатюру, как мне отправить фактическое изображение через намерение - person ; 18.04.2020
comment
Bitmap — это 100% размер полученного изображения, рекомендуется сначала прочитать документацию камеры. - person Ravi; 21.04.2020