如何显示从mysql数据库获取的图像到imageview

How to show image fetched from mysqldatabase to imageview

这是我必须设置成功登录用户图像的布局

并且我已将图像的 url 保存在 table 中,用户的所有详细信息都在那里....

所以我尝试的是从数据库中获取图像的 url,然后尝试将其设置到 imageview 中。我已经检查过 url 正在进入变量...

所以正如您在上图中看到的那样,它没有在 imageview 中设置图像,但是当我在定义变量时首先将 url 分配给 imgurl 变量然后它工作正常...

我不知道为什么会这样……我是不是做错了什么或者有其他方法可以做到这一点吗?

这是文件的代码...

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Dashboard extends AppCompatActivity {
    TextView usrname;
    ImageView profileimg;
    public static String imgurl = "";//here

    /**
     * Shared Preferences
     **/
    SharedPreferences sharedPreferences;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";

    /**
     * Shared Preferences
     **/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        profileimg = findViewById(R.id.iv_display_image);
        usrname = findViewById(R.id.tv_username);
        /**Shared Preferences**/
        sharedPreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        /**Shared Preferences**/
        //fetching session data
        String name = sharedPreferences.getString(Name, "0");
        usrname.setText(name);
        fetchimg(name);
        LoadImage loadImage = new LoadImage(profileimg);
        Log.d("Oncreate img url", imgurl);
        loadImage.execute(imgurl);
    }

    private void fetchimg(String name) {

        StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if (response.startsWith("Here")) {
                    String urlstr = getUrl(response, "Here ");
                    seturl(urlstr);
                    Log.d("urlstr value:", urlstr);
                } else {
                    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                    Log.d("vOLLEY ERROR", response.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("vOLLEY ERROR", error.getMessage().toString());
            }
        }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("login_name", "xxxxx");
                params.put("login_pass", "xxxxx");
                return params;
            }
        };

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

    private void seturl(String urlstr) {
        this.imgurl = urlstr;
        Log.d("Image url set inside seturl", imgurl);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.dashboardmenu, menu);
        return true;
    }

    public void openeditprofile(View view) {
        startActivity(new Intent(this, EditProfileActivity.class));
    }

    private class LoadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView imageView;

        public LoadImage(ImageView profileimg) {
            this.imageView = profileimg;
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            String urlLink = strings[0];
            Bitmap bitmap = null;
            try {
                InputStream inputStream = new java.net.URL(urlLink).openStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            profileimg.setImageBitmap(bitmap);
        }
    }

    public static String getUrl(String string, String word) {

        // Check if the word is present in string
        // If found, remove it using removeAll()
        if (string.contains(word)) {

            // To cover the case
            // if the word is at the
            // beginning of the string
            // or anywhere in the middle
            String tempWord = word + " ";
            string = string.replaceAll(tempWord, "");

            // To cover the edge case
            // if the word is at the
            // end of the string
            tempWord = " " + word;
            string = string.replaceAll(tempWord, "");
        }

        // Return the resultant string
        return string;
    }
}

您正在异步获取图像,您的 Asynctask 执行将使用空 imgUrl 调用,因为它尚未获取,将 AsyncTask 执行代码移至 onResponse 的获取

private void fetchimg(String name) {

        StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if (response.startsWith("Here")) {
                    String urlstr = getUrl(response, "Here ");
                    seturl(urlstr);
       

                   //here the url is ready to consume
                    Log.d("urlstr value:", urlstr);
                    //load the image now
                    LoadImage loadImage = new LoadImage(profileimg);
                    Log.d("Oncreate img url", imgurl);
                    loadImage.execute(imgurl);
                } else {
                    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                    Log.d("vOLLEY ERROR", response.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("vOLLEY ERROR", error.getMessage().toString());
            }
        }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("login_name", "xxxxx");
                params.put("login_pass", "xxxxx");
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
        requestQueue.add(request);
    }
use **Glide** to display Image from Url into image view.

You have to add glide lib in app-level build.gradle file.

implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'

        Glide.with(this).load(url)
        .transform(CenterCrop(), RoundedCorners(radius))
        .placeholder(R.drawable.drawable_image_placeholder)
        .error(R.drawable.drawable_image_placeholder)
        .into(ivProfile)

drawable_image_placeholder is the default imageview that displays
when getting the error to load the image. ivProfile is imageview .