App não executa ao colocar uma imagem externa em um ImageView. (Android Studio)

Estou com problema ao tentar executar uma activity em que eu coloco uma imagem externa (uma imagem não padrão do Android Studio) em um ImageView e o emulador não executar o app com o erro “O app foi parado!”, pois se eu uso uma imagem padrão do Android Studio como a “@dawable/ic_launcher_background” o app roda normalmente.

Alguém poderia me ajudar??

Agradeço desde já a ajuda!!

applications – ImageView inside cardView not showing image only show cardview

I displaying vector assets using ImageView. I placed ImageView inside CardView.

code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
tools:context=".MainActivity">

<androidx.cardview.widget.CardView
    android:id="@+id/cv_solid_close"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:selectableItemBackgroundBorderless"
    app:cardCornerRadius="360dp"
    app:cardElevation="5dp">

    <ImageView
        android:id="@+id/img_solid_close"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:layout_gravity="center"
        android:src="https://android.stackexchange.com/@drawable/ic_baseline_" />

</androidx.cardview.widget.CardView>

this code working perfectly on android pie and the above version but in android marshmallow and below version it’s not showing imageview it’s only showing cardview.

on android 9 and above:

enter image description here

on android 7 and below:
enter image description here

so

android – ImageView e Firebase

Gostaria de saber como eu posso pegar uma imagem que está no firebase e colocar ela num banco de dados proprio criado pelo sqlite para exibir numa imageview. Eu tenho a tela de criar e editar anime e quando eu crio o anime eu escolho a imagem e envio e ao abrir a tela de editar anime, as informações do anime q foram gravadas no banco de dados ela retorna contudo a imagem não vem, como eu posso está criando essa coluna imagem no banco de dados e está buscando a imagem de lá do firebase, tem como fazer isso? eu estou usando um nome randomico para criar o nome do arquivo. alem disso na hora de criar o anime a pessoa pode colocar a foto q quiser pois estará salva no celular dela, ela so tem q clicar na imageview, selecionar a foto e apertar em salvar anime q a imagem é salva e mandada la pro firebase, mas como disse, como eu posso está pegando a imagem q foi para lá e está mostrando ela de volta na imageview do anime escolhido. se alguem poder ajudar e souber qual a melhor maneira de fazer isso e se é possivel fazer isso, eu agradeço, pois estou perdido aqui.

Convertir ImageView a Bitmap despues a String Base64

con esto obtengo la imagen dela galeria

            Uri path = data.getData();
            ImageViewUri.setImageURI(path);

Obtengo el bitmap de la imagen puesta en la imageview


            ImageViewUri.invalidate();
            BitmapDrawable drawable = (BitmapDrawable)ImageViewUri.getDrawable();
            Bitmap bitmap = drawable.getBitmap();

llamo un decodificador para convertirla a base64 string


    String Base64 = convert(bitmap);

    public String convert(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 70, outputStream);
        return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
    }

subo mi string ami servidor con web service en mi mysql con el campo Texto
despues descargo el string base64 y lo convierto en bitmap

    private static Bitmap convertBase64ToBitmap(String  b64) {
        byte() imageAsBytes = Base64.decode(b64, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
    }

por alguna razon la imagen se muestra a medias y he visto que el problema es cuando se convierte el bitmap a string base64 no se si es el convertidor de bitmap a string

introducir la descripción de la imagen aquí

o cuando convierto la imagen en bitmap solo obtiene a medias la imagen


            ImageViewUri.invalidate();
            BitmapDrawable drawable = (BitmapDrawable)ImageViewUri.getDrawable();
            Bitmap bitmap = drawable.getBitmap();

nesecito resolver el problema que al obtener el bitmap de la imagen solo me obtiene la imagen a medias

java – How do I volleyrequest to see if data does not exist in mysql table? I want to set an x drawable in an imageview if an entry does not exist

I am making an app that has users complete a survey. They are given a grade that is time based. This means if you complete the survey (called the monthly check in) within 5 days you get an A, 8 days you get a B, and so on.

Using Volley, I am able to determine the grade and set my drawable image to check. What I am struggling with is setting my drawable to X and the grade to 0 if the monthly check in has been missed. Right now, the activity only reads the information when it exists.

Can anyone see why this else if statement does not work (!object.toString().contains(“TimeofCompletion”) && today.isAfter(FGrade))? TimeofCompletion is a time stamped that is saved when the user completes the survey. If it doesn’t exist, it means the user didn’t complete the survey and gets an x and 0 grade if today is after F grade date.

I have put my java and php files below.

Java

 public void getCompletionDate1() {


        sessionManager = new SessionManager(this);
        sessionManager.checkLogin();
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        //StringRequest stringRequest = new StringRequest(Request.Method.POST,"http://10.0.2.2/readMCICompletion.php", new Response.Listener<String>(){
       StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ReadCompletionDate,
               new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        Log.i(TAG, response.toString());

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            JSONArray jsonArray = jsonObject.getJSONArray("read");

                            if (success.equals("1")) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject object = jsonArray.getJSONObject(i);

                                    String MCIdate = object.getString("start_date").trim();

                                    org.threeten.bp.LocalDate MCIAvailable = org.threeten.bp.LocalDate.parse(MCIdate, dateFormatter);
                                    org.threeten.bp.LocalDate AGrade = MCIAvailable.plusDays(5);
                                    org.threeten.bp.LocalDate BGrade = MCIAvailable.plusDays(8);
                                    org.threeten.bp.LocalDate CGrade = MCIAvailable.plusDays(11);
                                    org.threeten.bp.LocalDate DGrade = MCIAvailable.plusDays(15);
                                    org.threeten.bp.LocalDate FGrade = MCIAvailable.plusDays(20);

                                    String DOC = object.getString("TimeofCompletion").trim();

                                    org.threeten.bp.LocalDate TOC = org.threeten.bp.LocalDate.parse(DOC, dateFormatter);
                                    DOC1.setText("Completed on " + DOC);
                                    int MCIGrade1Value;

                                  if (TOC.isBefore(AGrade)){
                                          MCIGrade1.setText("%100");
                                          MCIGrade1Value = 100;
                                          Drawable check;
                                          check = getResources().getDrawable(R.drawable.ic_cloud_done_black_24dp);
                                          warning1.setImageDrawable(check);
                                      } else if (TOC.isBefore(BGrade) && TOC.isAfter(AGrade)) {
                                          MCIGrade1.setText("%85");
                                          MCIGrade1Value = 85;
                                          Drawable check;
                                          check = getResources().getDrawable(R.drawable.ic_cloud_done_black_24dp);
                                          warning1.setImageDrawable(check);
                                      } else if (TOC.isBefore(CGrade) && TOC.isAfter(BGrade)) {
                                          MCIGrade1.setText("%75");
                                          MCIGrade1Value = 75;
                                          Drawable check;
                                          check = getResources().getDrawable(R.drawable.ic_cloud_done_black_24dp);
                                          warning1.setImageDrawable(check);
                                      } else if (TOC.isBefore(DGrade) && TOC.isAfter(CGrade)) {
                                          MCIGrade1.setText("%65");
                                          MCIGrade1Value = 65;
                                          Drawable check;
                                          check = getResources().getDrawable(R.drawable.ic_cloud_done_black_24dp);
                                          warning1.setImageDrawable(check);
                                      } else if (TOC.isAfter(DGrade)) {
                                          MCIGrade1.setText("%55");
                                          MCIGrade1Value = 55;
                                          Drawable check;
                                          check = getResources().getDrawable(R.drawable.ic_cloud_done_black_24dp);
                                      warning1.setImageDrawable(check);
                                    }else if (!object.toString().contains("TimeofCompletion") && today.isAfter(FGrade)){
                                        Drawable x;
                                        x = getResources().getDrawable(R.drawable.ic_clear_white_24dp);
                                        warning1.setImageDrawable(x);
                                        MCIGrade1Value = 0;
                                    }else {
                                      Drawable assignment;
                                      assignment = getResources().getDrawable(R.drawable.ic_assignment_black_24dp);
                                      warning1.setImageDrawable(assignment);
                                      MCIGrade1.setText("Grade");
                                      DOC1.setText("To be completed");
                                  }
                            }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            progressDialog.dismiss();

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();


                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("id", getId);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

PHP

<?php

if ($_SERVER('REQUEST_METHOD')=='POST') {

    $id = $_POST('id');

    $conn = mysqli_connect("localhost", "root", "", "users");

    $sql = "SELECT u.start_date, m.TimeofCompletion FROM users_table AS u JOIN mci_table AS m ON u.id = m.id WHERE u.id = '$id'";
   // $sql = "SELECT mci_table.*, users_table.id, users_table.start_date, users_table.end_date FROM mci_table JOIN users_table where  mci_table.id='$id' && mci_table.id=users_table.id ";

    $response = mysqli_query($conn, $sql);



    $result = array();
   $result('read') = array();

    if( mysqli_num_rows($response) === 1 ) {

        if ($row = mysqli_fetch_assoc($response)) {



               $h('start_date')        = $row('start_date') ;
                      $h('TimeofCompletion')        = $row('TimeofCompletion') ;






           array_push($result("read"), $h);

                       $result("success") = "1";
                       echo json_encode($result);
                  }

             }

           }else {

               $result("success") = "0";
               $result("message") = "Error!";
               echo json_encode($result);

               mysqli_close($conn);
           }

           ?>

Can’t Load ImageView from MediaStore Camera Android

I have an ImageView inside an alertdialog,I would like to show the picture that was taken by the camera in the ImageView with the height and width that I gave to to it and Not as a thumbnail.

I don’t get an error inside the logcat just see a blank square for my ImageView where there was a default Image and not the picture that was taken by the camera in this imageview.

Further more I am able to load images from gallery.

Any suggestions?

Here is my code.

XML

   <ImageView
        android:padding="5dp"
        android:id="@+id/image_to_set"
        android:src="https://stackoverflow.com/@drawable/picture"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true">
    </ImageView>

Files Dir

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="external_files"
        path="."/>

</paths>

Manifest

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.musicplayer.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/files_dir"/>
        </provider>

Main Activity

cameraButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        file=new File(Environment.getExternalStorageDirectory(),"pic.jpg");
                        imageUri = FileProvider.getUriForFile(MainActivity.this
                                , "com.example.musicplayer.provider", file);
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                        startActivityForResult(intent,CAMERA_REQUEST_CODE);
                    }
                });

I tried several ways to load the picture was taken by the camera into the image view
Glide/picasso

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==CAMERA_REQUEST_CODE&&resultCode==RESULT_OK){
            ImageView imageViewToSet=v.findViewById(R.id.image_to_set);
            Picasso.get().load(file.getAbsolutePath()).fit().centerCrop().into(imageViewToSet);
            v.requestLayout();
            v.invalidate();
        }

java – Changing ImageView position based on angle of rotation

I am trying to make an ImageView change its position based on the direction it is facing.

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class Demo extends Application {

    public void start(Stage window) {
        window.setTitle("Changing ImageView position based on angle of rotation");

        int speed = 10; // You can modify the speed here

        ImageView imageView = new ImageView(new Image("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTBJoRKh1UKimWTSLdabW2b8RSLDeSgMfSqqg&usqp=CAU"));
        imageView.setX(100);
        imageView.setY(100);

        imageView.setRotate(65); // This is where you can change the angle of rotation

        Group root = new Group();
        root.getChildren().add(imageView);
        Scene scene = new Scene(root);
        window.setScene(scene);

        final long() lastNanoTime = {System.nanoTime()};

        new AnimationTimer() {
            @Override
            public void handle(long currentTime) {
                double elapsedTime = (currentTime - lastNanoTime(0)) / 1000000000.0;
                lastNanoTime(0) = currentTime;

                imageView.setX(imageView.getX() + Math.sin(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
                imageView.setY(imageView.getY() + Math.cos(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);

            }
        }.start();

        window.show();
    }


    public static void main(String() args) {
        launch(args);
    }
}

The above code is based on the code I am using. You can adjust the degrees accordingly to see the issue. The ImageView does not move in the direction it is facing. Note: I found a random .png file online for the purpose of this demo. You can substitute with a different image in you own code in order to better visualize the problem.

The issue is, the ImageView does not move in the direction it is facing. When oriented vertically (0° or 180°) the ImageView moves backward, but when oriented horizontally (90° or 270°) it moves straight ahead like it should. When oriented diagonally, it moves somewhere in between.

What am I doing wrong and how do I fix it?

android – ImageView zoom with double tap

I am trying to enlarge and reduce an image on Android, but I have the following problem:

I had the onDoubleTap method so that:
@Override
public boolean onDoubleTap (MotionEvent e) {

    float origScale = saveScale;
    float mScaleFactor;
    if (saveScale == maxScale) {
        saveScale = minScale;
        mScaleFactor = minScale / origScale;
    } else {
        saveScale = maxScale;
        mScaleFactor = maxScale / origScale;
    }
    matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
    fixTrans();
    return false;
}

And everything was perfect, but I realized that the change was very abrupt and decided to do an animation:

@Override
public boolean onDoubleTap(MotionEvent e) {
    // Double tap is detected
    ILog.d(TAG, "Double tap detected");

    float origScale = saveScale;
    float mScaleFactor;
    ObjectAnimator animatorX;
    ObjectAnimator animatorY;
    this.setScaleType(ScaleType.CENTER_INSIDE);
    if (saveScale == maxScale) {
        saveScale = minScale;
        mScaleFactor = minScale / origScale;
        animatorX = ObjectAnimator.ofFloat(this, "scaleX", this.getScaleX(), 1);
        animatorY = ObjectAnimator.ofFloat(this, "scaleY", this.getScaleY(), 1);
    } else {
        saveScale = maxScale;
        mScaleFactor = maxScale / origScale;
        animatorX = ObjectAnimator.ofFloat(this, "scaleX", this.getScaleX(), 2);
        animatorY = ObjectAnimator.ofFloat(this, "scaleY", this.getScaleY(), 2);
    }
    animatorX.setDuration(getContext().getResources().getInteger(R.integer.short_anim_duration));
    animatorY.setDuration(getContext().getResources().getInteger(R.integer.short_anim_duration));
    animatorX.start();
    animatorY.start();
    matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2, viewHeight / 2);
    fixTrans();

    return false;
}

And it happens to me that the DRAG mode is eliminated and I can't move around the image when applying it.

xcode – ImageView Swift error

Hey guys …

I'm developing an app, but it has an optional bug (I think this is the bug). I have the following scenario: An "A" button and a "B" button in a main ViewController (1), if you click the "A" button you would need a second ViewController (2) with the image " Open X "and open the same ViewController (2) by clicking the" B "button, but load the" Y "picture. If there is no image, the ViewController (2) opens normally.

Syntax for loading the image that I think is correct:

@IBOutlet weak var fundo: UIImageView!
@IBAction func botaAcao(_ sender: Any) {
        let imagem = UIImage(named: "imagem1.jpg")!
        fundo.image = imagem

    }

Because if you place an ImageView in the main ViewController (1), the image will load normally, but not when you try to open it in the second ViewController (2).

Enter the following error:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value