TransWikia.com

Access a view within an AlertDialog from the inflating activity

Stack Overflow Asked by Roberto Funes on December 17, 2020

I am trying to access an ImageView inside an AlertDialog but I get NullPointerException when I try to put an image to it

I try to access from onActivityResult in the activity that invokes the method. But this gives me error. And the datelle that I can only do it from onActivityResult since I must wait for the image of the activity of the camera

This is my code:

Activity.Java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImageUri = null;
    Uri selectedImage;
    //Comprobamos que la foto se a realizado
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK) {
        //Creamos un bitmap con la imagen recientemente
        //almacenada en la memoria
        filePathPicTemp = 
        Environment.getExternalStorageDirectory()+Variables.tempsPictures+"foto.jpg";
        Bitmap bMap = BitmapFactory.decodeFile(filePathPicTemp);
        //Añadimos el bitmap al imageView para
        //mostrarlo por pantalla
        bMap = resizeImage(getApplicationContext(),bMap,640,480);

        ((ImageView) findViewById(R.id.ivModalComment)).setImageBitmap(bMap);
       // bMap = BitmapFactory.decodeResource(getResources(),ivModalComment.getId());
        try { // Try to Save #2
            FileOutputStream out = new FileOutputStream(filePathPicTemp);
            bMap.compress(Bitmap.CompressFormat.PNG, 50, out);
            out.flush();
            out.close();
            imageComment = new File(filePathPicTemp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

GenericMethods.Java (This is used to repeated functions)

public static void addCommentDialog(final String idRoute, File imageComment, AppCompatActivity 
    mContext, ViewGroup viewGroup) {
    //Se infla la vista
    View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment, 
        mContext.findViewById(android.R.id.content), false);

    //Se instancia el builder
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

    //Se asigna el dialogo al builder
    builder.setView(dialogView);

    //Se crea y se muestra la alerta
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
    UserSessionManager userSessionManager = new UserSessionManager(mContext);
    Button btnExitComments = dialogView.findViewById(R.id.btnExitComments);
    Button btnUploadPhoto = dialogView.findViewById(R.id.btnUploadPhoto);
    Button btnTakePic = dialogView.findViewById(R.id.btnTakePic);
    Button btnSendComment= dialogView.findViewById(R.id.btnSendComment);
    CircleImageView cvUserIcon= dialogView.findViewById(R.id.cvUserIcon);

    ImageView ivModalComment  =  dialogView.findViewById(R.id.ivModalComment);

    final EditText taComment = dialogView.findViewById(R.id.taComment);
    final RatingBar rbComment  = dialogView.findViewById(R.id.rbComment);

    Glide.with(mContext)
    .load(Variables.URL_GENERAL+"fotos_usuarios/"+userSessionManager.getUrlperfilImage())
            .diskCacheStrategy(DiskCacheStrategy.NONE)
    .error(R.drawable.user_icon).into(cvUserIcon);

    //Boton de salir
    btnExitComments.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.hide();
        }
    });

    //Boton para acceder a la galeria y obtener una imagen
    btnUploadPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            mContext.startActivityForResult(Intent.createChooser(intent, "Seleccione una imagen"),2);
        }
    });

    //Boton para abrir la camara y tomar la foto
    btnTakePic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1) {// Marshmallow+
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA)!= 
                    PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, 
                        Manifest.permission.CAMERA)) {
                        // Show an expanation to the user *asynchronously* -- don't block
                        // this thread waiting for the user's response! After the user
                        // sees the explanation, try again to request the permission.
                    } else {
                        ActivityCompat.requestPermissions(mContext, new String[] 
                        {Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMARA);
                        // MY_PERMISSIONS_REQUEST_CAMARA es una constante definida en la app. El 
                        método callback obtiene el resultado de la petición.
                    }
                }else{ //have permissions
                    abrirCamara(mContext);
                }
            }else{ // Pre-Marshmallow
                abrirCamara (mContext);
            }
        }
    });

    //Boton de enviar comentario
    btnSendComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UserSessionManager userSessionManager = new UserSessionManager(mContext);
            //progressDialog.show();
            sendComment(idRoute, imageComment, taComment.getText().toString(), 
            userSessionManager.getIdUser(), rbComment.getRating(), alertDialog, 0, mContext);
        }
    });
}

XML file that is inflated in method:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="18dp">
        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/user_icon"
            android:id="@+id/cvUserIcon"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textView15"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Usuario" />

                <TextView
                    android:id="@+id/textView19"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Tu comentario sera publico, por favor lee nuestras normas de 
                                     comunidad aqui"
                    android:textSize="10sp" />

            </LinearLayout>


            <Button
                android:id="@+id/btnExitComments"
                style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center|end"

                app:icon="@drawable/ic_back_arrow_black"
                app:iconGravity="textStart"
                app:iconPadding="0dp" />

        </LinearLayout>

    </LinearLayout>
    <RatingBar
        android:id="@+id/rbComment"
        style="@android:style/Widget.Material.Light.RatingBar.Indicator"
        android:isIndicator="false"
        android:clickable="true"
        android:focusable="true"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:numStars="5"
        android:stepSize="0.5"/>
    <com.google.android.material.textfield.TextInputLayout
        android:layout_margin="6dp"
        android:id="@+id/outlinedTextField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Puntue y escriba un comentario"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">



        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/taComment"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:inputType="textMultiLine"
            android:ems="10"
            />


    </com.google.android.material.textfield.TextInputLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/common_google_signin_btn_text_dark_disabled"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnUploadPhoto"
            style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            app:icon="@drawable/ic_file_atach"
            android:layout_weight="1"
            app:iconGravity="textEnd" />

        <Button
            android:id="@+id/btnTakePic"
            style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:icon="@drawable/ic_menu_camera"
            app:iconGravity="textEnd" />
        <ImageView
            android:id="@+id/ivModalComment"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            />

        <Button
            android:id="@+id/btnSendComment"
            style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|end"
            android:layout_weight="10"
            android:gravity="center|end"

            android:text="Enviar"
            app:icon="@drawable/ic_menu_send"
            app:iconGravity="end" />
    </LinearLayout>
</LinearLayout>
</ScrollView>

One Answer

Have you tried this?

    AlertDialog.Builder builder= new AlertDialog.Builder(this);
    LayoutInflater inflater= getLayoutInflater();
    final View myView= inflater.inflate(R.layout.alert_dialog_text_entry, null);
    builder.setTitle("About");
    builder.setMessage("Test");
    builder.setView(myView);
    AlertDialog alert= builder.create();
    TextView stateful= (TextView)myView.findViewById(R.id.TextView01);
    stateful.setText("More Testing");
    Log.d(Utilities.TAG,stateful.toString());
    alert.show();

You can use myView.findViewById() to get the view of any component that you wish. Try it and I am sure that it will work for you.

Answered by Leo Bowers on December 17, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP