how to get the name of a selected image from gallery of images android studio

Viewed 27

I have an app which after registering through facebook (through an app button) redirects to a user profile view where the facebook user profile image, name and email are loaded. user (url) is stored in a sqlite database, I also have a button with which you can change the profile image for an image from the external memory of the smartphone, after selecting the image, its uri overwrites the url of the facebook profile image. The problem arises when I change the facebook profile image for one from the image gallery (which loads perfectly) and then I close the session, when I log in it continues to show me the facebook profile image and not the one selected in the gallery. I have the slight suspicion that with the code that I will show next I am not reaching the path where the selected image is stored since when I print the path it gives me a strange value, being that according to my e emulator the path of the images are stored in :/storage/emulated/0/DCIM/Camera/image.jpg. If I could get the name of the image I'm sure I could save the image correctly in the database and then read it at the time of login. I leave my code below:

perfil_user extends Fragment  {
    GoogleSignInClient mGoogleSignInClient;
    ImageView image_user,image_ok,image_edit;
    TextView name_user,email,tag_date;
    EditText alias;
    Button buttonSelectImage,buttonChangeAlias;
    public String name,facebook_firstname,facebook_lastname,email_facebook,facebook_user_name,str_datefb,str_datejoinedfb,last_season,string_Uri_gmail ;
    public String date_now,date_joined,last_date,alias_facebook,alias_perfil,get_alias,request_date,alias_perfil_gmail,personGivenName,personFamilyName,personName,personEmail,str_dategmail,str_datejoinedgmail,alias_name,compare_username,alias_gmail;
    private static int RESULT_LOAD_IMAGE = 1;
    public static String name_aux,alias_aux;
    public boolean click;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.perfil_user,container,false);
        image_user=view.findViewById(R.id.image_user);
        name_user=view.findViewById(R.id.NameUser);
        email=view.findViewById(R.id.setmail);
        alias=view.findViewById(R.id.setAlias);
        buttonSelectImage=view.findViewById(R.id.change_image);
        buttonChangeAlias = view.findViewById(R.id.change_alias);
        tag_date=view.findViewById(R.id.last_season_date);
        DateTimeFormatter datetime_formatter = DateTimeFormatter.ofPattern("HH:mm:ss dd/MM/YYYY");
        LocalDateTime now = LocalDateTime.now();
        date_now = datetime_formatter.format(now);
        ConexionSQliteHelper conn=new ConexionSQliteHelper(getContext(),"lala",null,1);
        buttonSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent,3);


            }
        })
        
        if ( accessToken != null && !accessToken.isExpired()){
            GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            try {
                                facebook_firstname=object.getString("first_name");
                                facebook_lastname =object.getString("last_name");
                                facebook_user_name=object.getString("name");
                                email_facebook = object.getString("email");
                                
                                String url_perfil_facebook=object.getJSONObject("picture").getJSONObject("data").getString("url");
                                if (url_perfil_facebook.equals("")){
                                    url_perfil_facebook = "https://cdn.computerhoy.com/sites/navi.axelspringer.es/public/styles/1200/public/media/image/2017/08/252649-modo-incognito-no-es-seguro-ni-privado.jpg";
                                }
                                else{
                                    //pass
                                }
                                Picasso.get().load(url_perfil_facebook).into(image_user);
                                name_user.setText(facebook_user_name);
                                email.setText(email_facebook);
                                str_datefb = date_now;
                                str_datejoinedfb = date_now;
                                tag_date.setText(str_datefb);
                                boolean exist_user = conn.verifyIfUserExists(email_facebook);
                                if (exist_user) {
                                    String url_photo = conn.loadImage(facebook_user_name);
                                    Uri myUri = Uri.parse(url_photo);
                                    image_user.setImageURI(myUri);
                                    alias_perfil = conn.getUserName(email_facebook);
                                    alias_facebook = conn.requestAlias(alias_perfil);
                                    alias.setText(alias_facebook);
                                    String last_season =  conn.getLastDateofConnection(facebook_user_name);
                                    tag_date.setText(last_season);
                                    conn.overwriteDate(date_now,facebook_user_name);
                                    String last_season_2 =  conn.getLastDateofConnection(facebook_user_name);
                                    //Toast.makeText(getContext(), "La nueva fecha es"+last_season_2, Toast.LENGTH_SHORT).show();
                                }

                                else {
                                    alias_name= generateAliasRandom();
                                    conn.insertUser(facebook_user_name,facebook_firstname,facebook_lastname,str_datefb,str_datejoinedfb,alias_name,email_facebook,null,url_perfil_facebook);
                                }
                                name_aux = name_user.getText().toString();
                                alias_aux = alias.getText().toString();



                            } catch (JSONException  e) {
                                e.printStackTrace();
                            }
                        }
                    });

            Bundle parameters = new Bundle();
            parameters.putString("fields","id,first_name,last_name,name,email,link,picture.type(large)");
            request.setParameters(parameters);
            request.executeAsync();

        }

       
        buttonChangeAlias.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alias.setFocusableInTouchMode(true);
                alias.setText("");
                alias.setEnabled(true);
                click = true;
                alias.setOnKeyListener(new View.OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            alias.setCursorVisible(false);
                            alias.setEnabled(false);
                            alias.setTextColor(Color.BLACK);
                            int id = conn.requestId(name_user.getText().toString());
                            conn.overwriteAlias(alias.getText().toString(),id);
                            return true;
                        }
                        return false;
                    }

                });
            }
        });



        return  view;

    }

    private String generateAliasRandom(){
        String chars = "0123456789abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder name_alias = new StringBuilder(10);
        for (int i = 0; i < 10; i++){
            name_alias.append(chars.charAt(random.nextInt(chars.length())));
        }
        alias.setText(name_alias);
        return String.valueOf(name_alias);
    }


    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ConexionSQliteHelper conn=new ConexionSQliteHelper(getContext(),"lala",null,1);
        if(resultCode == RESULT_OK && data != null){
            Uri selectedImage = data.getData();
            image_user.setImageURI(selectedImage);
            String stringUri = selectedImage.toString();
            int id_user = conn.requestId(name_user.getText().toString());
            conn.overWriteImage(stringUri,id_user);
          

        }
    }



}


1 Answers

String fileName= getFileName(mActivity, selectedImage);

 public static String getFileName(Context context, Uri uri) {
    String result = null;
    if (uri.getScheme().equals("content")) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    if (result == null) {
        result = uri.getPath();
        int cut = result.lastIndexOf(File.separator);
        if (cut != -1) {
            result = result.substring(cut + 1);
        }
    }
    return result;
}
Related