0

I am want to upload user profile images in database and then shows list of all users in fragments. for setting image res to imageview I user Glide, and when Uploaded to database I incode image in base64, I could get the image path from database but when set to imageview not display anything. and no error displayed. Is it need to decode back after retriving from database?

  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;
}

and this code retrieves back from the database and set in 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);


}

My Recycler view Adapter Class,(Setting in 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?
Mina
  • 47
  • 1
  • 9
  • when you call api in "getAllData()" what you get in "object.getString("photo")" ? Image url something else? – pratik vekariya Jul 22 '21 at 05:48
  • I get this link of image: http://192.168.155.193/worker/profile_image/7.jpeg – Mina Jul 22 '21 at 05:56
  • you can direct load this image url using glide. If this not load then first check in adapter whether you are getting image URL or not. If you are getting image url in adapter then open URL in browser. If none of these works then decode saved image and convert it to bimap and then set. – pratik vekariya Jul 22 '21 at 06:12
  • Do you have any sample code for converting?? When I browsed the image URL I got the image. – Mina Jul 22 '21 at 07:26
  • Hey, I found the problem. it is showing this.:W/Glide: Load failed for http://192.168.155.193/worker/profile_image/13.jpeg with size [510x450] class com.bumptech.glide.load.engine.GlideException: Failed to load resource There was 1 root cause: it means the problem is with size of image. how to solve this?? – Mina Jul 22 '21 at 08:22
  • in glide there is a way to resize image. see https://stackoverflow.com/questions/46114603/resize-images-with-glide-in-a-imageview-android – pratik vekariya Jul 22 '21 at 08:44

1 Answers1

0

You can store the file path instead of file in data base, you can use this method for get file from uri in new android and older

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)}
Mahdi Zareei
  • 1,299
  • 11
  • 18
  • Do you mean to store the image itself in the database column?? not in the profile_image folder? – Mina Jul 22 '21 at 05:58
  • I mean just store the file uri in database, not whole file in a place or database or something else, just work with the image uri – Mahdi Zareei Jul 22 '21 at 06:03
  • Ok will try that. the path is the problem?? – Mina Jul 22 '21 at 06:34
  • i just suggested another solution to you, because i felt you dont have to save the file in the database, and better way is store image uri in database – Mahdi Zareei Jul 22 '21 at 06:42
  • Yes I need image url. what is the problem of this code? any idea? i can get the image URL form database: http://172.16.204.105/worker/profile_image/7.jpeg. when I pass to recyclerview adapter and set to imageview nothing shown – Mina Jul 22 '21 at 07:32