android - 如何从mysql数据库加载图像并在android的imageview中显示?
问题描述
我想在数据库中上传用户个人资料图片,然后在片段中显示所有用户的列表。为了将图像资源设置为 imageview,我使用 Glide,当上传到数据库时,我在 base64 中对图像进行编码,我可以从数据库中获取图像路径,但是当设置为 imageview 时不显示任何内容。并且没有显示错误。从数据库检索后是否需要解码?
private void ChooseFile(){
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select picture"),1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode== RESULT_OK && data!=null && data.getData()!=null){
Uri filepath=data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),filepath);
profile_image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
UploadPicture(getID,getStringimage(bitmap));
}
}
private void UploadPicture(final String id, final String photo){
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Uploading your Image");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
String uRlP = "http://192.168.8.193:80/worker/Userupload.php";
StringRequest request = new StringRequest(Request.Method.POST, uRlP, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Login", "Connected");
try {
JSONObject jsonObject=new JSONObject(response);
progressDialog.dismiss();
if(!jsonObject.getBoolean("error")){
String getp=jsonObject.getString("photo");
Log.d("Omag", getp);
usersession.setImage(getp);
Toast.makeText(getContext(),"Upload Successfully",Toast.LENGTH_LONG).show();
Log.d("UploadImg", "Sucess");
}else{
Toast.makeText(getContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getContext(),"Try Again!",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> param = new HashMap<>();
param.put("id",id);
param.put("photo",photo);
return param;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(getContext()).addToRequestQueue(request);
}
public String getStringimage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream= new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imageByteArray=byteArrayOutputStream.toByteArray();
String econdeImage= Base64.encodeToString(imageByteArray,Base64.DEFAULT);
return econdeImage;
}
并且此代码从数据库中检索并在 imageview 中设置。
private void getAllData() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Reading your details");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
//progressDialog.show();
String uRl = "http://192.168.8.193:80/worker/getWorkers.php";
StringRequest request = new StringRequest(Request.Method.GET, uRl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// progressDialog.dismiss();
Log.d("HomeLogin", "Connected");
if(!response.equals("error")) {
try {
JSONArray array = new JSONArray(response);
Log.d("Home", array.getString(1));
for (int i = 0; i < array.length(); i++) {
Log.d("responess", i+" ");
JSONObject object = array.getJSONObject(i);
int id = object.getInt("id");
String name = object.getString("name");
String email = object.getString("email");
String gender = object.getString("gender");
String mobile = object.getString("mobile");
String image = object.getString("photo");
Log.d("photo", image);
// String rate = String.valueOf(rating);
//float newRate = Float.valueOf(rate);
float rate = 1.2f;
UserData user_data = new UserData(id, name, email, mobile, gender, image, rate);
User_Data.add(user_data);
}
} catch (Exception e) {
Toast.makeText(getContext(),response+""+e,Toast.LENGTH_LONG).show();
Log.d("ErrorH", response+""+e);
}
mAdapter = new RecyclerAdapter(getContext(), User_Data);
recyclerView.setAdapter(mAdapter);
}else {
Toast.makeText(getContext(),response,Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getContext(), error.toString(),Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(newDefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(getContext()).addToRequestQueue(request);
}
我的回收站视图适配器类,(在 imageview 中设置)
@Override
public void onBindViewHolder(@NonNull RecyclerAdapter.MyViewHolder holder, int position) {
UserData userInfo = userData.get(position);
holder.mPrice.setText("Phone: "+userInfo.getMobile());
holder.mRate.setRating(userInfo.getRating());
holder.mTitle.setText(userInfo.getName());
Glide.with(mContext).load(userInfo.getImage()).into(holder.mImageView);
holder.mContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,DetailActivity.class);
intent.putExtra("name",userInfo.getName());
intent.putExtra("image",userInfo.getImage());
intent.putExtra("rate",userInfo.getRating());
intent.putExtra("phone",userInfo.getMobile());
mContext.startActivity(intent);
}
});
}
but nothing displayed. is it need to decode again the image? when retrieved from the database?
解决方案
您可以将文件路径而不是文件存储在数据库中,您可以使用此方法从新 android 和旧版本的 uri 中获取文件
fun getFileFromUri(uri: Uri): File? {
if (uri.path == null) {
return null
}
var realPath = String()
val databaseUri: Uri
val selection: String?
val selectionArgs: Array<String>?
if (uri.path!!.contains("/document/image:")) {
databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
selection = "_id=?"
selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
} else {
databaseUri = uri
selection = null
selectionArgs = null
}
try {
val column = "_data"
val projection = arrayOf(column)
val cursor = context.contentResolver.query(
databaseUri,
projection,
selection,
selectionArgs,
null
)
cursor?.let {
if (it.moveToFirst()) {
val columnIndex = cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)
}
cursor.close()
}
} catch (e: Exception) {
Log.i("GetFileUri Exception:", e.message ?: "")
}
val path = if (realPath.isNotEmpty()) realPath else {
when {
uri.path!!.contains("/document/raw:") -> uri.path!!.replace(
"/document/raw:",
""
)
uri.path!!.contains("/document/primary:") -> uri.path!!.replace(
"/document/primary:",
"/storage/emulated/0/"
)
else -> return null
}
}
return File(path)}