How to save an image using CircleImageView Android Studio - java

I wrote a program where a user can click a TextView (editPhoto) and select an image (profile picture) and display on the profile and also save it on my database with the rest of the profile details, but as soon as I leave the page the picture disappears from the CircleImageView although it's still saved on my database. I am able to save the rest of the users information on the profile like name, username, email etc using .setText() so how can I do the same with the CircleImageView for the profile picture? Thanks in advance
CODE:
private TextView editPhoto;
CircleImageView profilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
profilePic = findViewById(R.id.profilepic);
editPhoto = findViewById(R.id.txtEditPP);
editPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseFile();
}
});
}
private void chooseFile(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose Photo"),1);
}
#Override
protected 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(getContentResolver(), filepath);
profilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
UploadPicture(getId, getStringImage(bitmap));
}
}
//UPLOAD PROFILE PICTURE
private void UploadPicture(final String id, final String photo) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(EditProfile.this, "Photo Uploaded", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(EditProfile.this, "Error Uploading Image!", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EditProfile.this, "Error Uploading Image!", Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("photo", photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArr = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArr, Base64.DEFAULT);
return encodedImage;
}

In onResume can you reload imageView using bitmap object?
Also make bitmap object as class variable reloading image will work for you in this case.

Related

I want to send base64 image string into Url using volley

I want to send base64 string of image to the server using volley library android studio. It works in postman and give me response perfecty as it is shown in this image as it is shown in this image
I try many times in the android studio but it always show me 500 code error and cant get the result any one help me.View postman response in image that i have attached with this post. I also attached my code with it.
This is image button click listener event :
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 22);
}
});
Now start activity for result code is here :
#Override
public void onActivityResult(int requestCode, final int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 22 && resultCode == RESULT_OK && data != null){
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContext().getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
profile_image.setImageBitmap(selectedImage);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded4 = Base64.encodeToString(byteArray, Base64.DEFAULT);
String encoded22 = "data:image/jpeg;base64,"+encoded4;
Toast.makeText(getContext(), encoded22, Toast.LENGTH_SHORT).show();
final ProgressDialog progress = new ProgressDialog(getContext());
progress.setTitle("Uploading Image");
progress.setMessage("Loading...");
progress.setCancelable(false);
progress.show();
RequestQueue queue = Volley.newRequestQueue(getContext());
final JSONObject jsonObject = new JSONObject();
jsonObject.put("base64image", encoded22);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, Utils.baseUrl +"/company/update-photo", jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progress.dismiss();
Toast.makeText(getContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progress.dismiss();
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization", bear + idCheck);
return params;
}
};
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
120000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonRequest);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "Problem is here", Toast.LENGTH_SHORT).show();
}
}
}
But it always shows me this error
" BasicNetwork.performRequest: Unexpected response code 500 for URL "

How to store 2mb above file size of image to database via Volley?

I have a code for uploading images from mobile to my phpmyadmin database via Volley. I can successfully upload images when it is in small ".jpg" format and also, the sizes don't exceed 2mb. Now when I choose a picture (specifically from camera pictures) that's more than that, it doesn't prompt any error and doesn't also add the picture to the database. How can I solve this and how can I store?
This is my settingsprofilefragment.java
public class SettingsFragment extends Fragment{
private static final String TAG = SettingsFragment.class.getSimpleName();
private Button btnUploadVerificationPic;
private ImageView verificationPic;
private Bitmap bitmap;
TextView logout;
private static final String URL_UPLOADPIC = "http://isalonbyageeks.000webhostapp.com/uploadVerificationPhoto.php";
SessionManager sessionManager;
String getId = "";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settingsprofile, container, false);
return view;
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState){
sessionManager = new SessionManager(getActivity());
sessionManager.checkLogin();
logout = (TextView) getView().findViewById(R.id.txtLogout);
btnUploadVerificationPic = (Button) getView().findViewById(R.id.uploadVeriPhoto);
verificationPic = (ImageView) getView().findViewById(R.id.verificationPic);
HashMap<String, String> user = sessionManager.getUserDetail();
getId = user.get(sessionManager.ID);
btnUploadVerificationPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseFile();
}
});
logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LogoutEffect.class);
sessionManager.logout();
startActivity(intent);
}
});
}
private void chooseFile(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Your Profile Picture"),1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data!= null && data.getData() != null){
Uri filepath = data.getData();
try {
bitmap = (Bitmap) MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(), filepath);
verificationPic.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(getActivity());
progressDialog.setMessage("Uploading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOADPIC,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Log.i(TAG, response);
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Intent intent = new Intent(getActivity(), ProfileActivity.class);
startActivity(intent);
Toast.makeText(getActivity(),"Success!",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
Toast.makeText(getActivity(),"Try Again! " + e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Try Again!" + error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id",id);
params.put("photo",photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,70 , byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
return encodedImage;
}
}

Sharing one image uploading multiple times

I am working on a Image sharing app. I can upload image to the sever but it uploading same image multiple times(3-4 times).
I have Images Fragment where i gave floating buttons to select camera or gallery.
Images Fragment
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_images, container, false);
floatcamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File imageFolder = new File(Environment.getExternalStorageDirectory(), "/My Children");
imageFolder.mkdir();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmdd_hhmmss");
String timestamp = simpleDateFormat.format(new Date());
File image = new File(imageFolder, timestamp+ ".jpg");
// Uri uriImage = Uri.fromFile(image);
camerauri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", image);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, camerauri);
startActivityForResult(intent, TAKE_PICTURE);
}
});
floatgallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_PICTURE);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == TAKE_PICTURE ) {
Intent i = new Intent(getContext(), Upload.class);
i.putExtra("image", camerauri.toString());
startActivity(i);
}
if (requestCode == SELECT_PICTURE) {
Intent i = new Intent(getContext() , Upload.class);
i.putExtra("image", data.getData().toString());
startActivity(i);
}
}catch (Exception e){
e.printStackTrace();
}
}
After Clicking or selecting image the resulting single image display on next Activity. And there is a button to upload it. I am using Custom Volley Request as Volley does not support Multipart.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
ImageView imageview = (ImageView) findViewById(R.id.imageview);
Intent intent = getIntent();
if (intent == null){
return;
}
final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Glide
.with(this)
.load(imageUri)
.apply(new RequestOptions().priority(Priority.HIGH).fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL))
.into(imageview);
progressDialog = new ProgressDialog(Upload.this);
progressDialog.setMessage("Uploading");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
caption = txtCaption.getText().toString();
uploadBitmap(bitmap);
}
});
}
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
progressDialog.show();
//our custom volley request
MultipartRequest volleyMultipartRequest = new MultipartRequest(Request.Method.POST, IMAGE_UPLOAD_URL,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
progressDialog.dismiss();
Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
userid = SharedPreferenceManager.getmInstance(Upload.this).getMobileno();
params.put("userid", userid);
params.put("caption", caption);
params.put("product","normal");
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, MultipartRequest.DataPart> getByteData() {
Map<String, MultipartRequest.DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("uploadedfile", new MultipartRequest.DataPart(imagename + ".jpeg", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
I Hope this will work for you
override this way
#Override
protected Map<String, MultipartRequest.DataPart> getByteData() {
Map<String, MultipartRequest.DataPart> params = new HashMap<>();
String imagename = imageUri.getLastPathSegment();
params.put("uploadedfile", new MultipartRequest.DataPart(imagename,getFileDataFromDrawable(bitmap)));
return params;
}

Code for inserting data into the database not working

I am storing a picture with some information in the database. I am taking an image. It is not inserting data, showing that int.java.lang.stringlength() invoke virtual method. It was working the last day but when I delete the history from Xammp database and then I run the code it shows the error.
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private Spinner depart;
private String depat,sub,det;
//for image
private Bitmap selectedImage;
public static String image;
private Uri imageUri;
public final static int PHOTO_FROM_MEMORY_REQUESTED = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_do_report);
subject = (EditText) findViewById(R.id.subject);
detail = (EditText) findViewById(R.id.detail);
depart = (Spinner) findViewById(R.id.Depat_Edit);
}
//to pic the image from galery
public void imgBtn(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK){
updateSelectedPicture(data.getData());
}
}
private void updateSelectedPicture(Uri uri){
try{
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
ImageView iv = (ImageView) findViewById(R.id.ImgView);
iv.setImageDrawable(new BitmapDrawable(selectedImage));
image=encode(selectedImage);
}catch(FileNotFoundException ex){
Log.e("File not found", "Cannot find background file under received URI");
}
}
public static String encode(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
public void submit(View v)
{
depat=depart.getSelectedItem().toString();
sub=subject.getText().toString();
det=detail.getText().toString();
if(sub.isEmpty())
{
subject.setError("subject is required");
}
else if(det.isEmpty())
{
detail.setError("subject is required");
}
else {
login_database(depat, sub, det, image);
}
}
private void login_database(final String depat, final String sub,final String det,final String pic) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, Static.user_connect,//changes required
new Response.Listener<String>() {
public void onResponse(String response) {
if ((response.contains("successful"))) {
Toast.makeText(DoReport.this, "Successful Submitted",Toast.LENGTH_LONG).show();
Intent i = new Intent (DoReport.this,UserView.class);
startActivity(i);
finish();
}
else {
Toast.makeText(DoReport.this, "Some error occured", Toast.LENGTH_LONG).show();//changes required
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DoReport.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.d("ERROR", toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("key", "3");//changes required
map.put("Depat", depat);
map.put("Detail", det);
map.put("Pic", pic);
map.put("Subject", sub);
map.put("U_id",Static.id);
return map;
}
};
queue.add(request);
}

For some reason the this in the code is underlined in red.How do I resolve this error?

Here is code for Main6Activity.java. I am getting some of that code underlined. Please suggest me what to do in this case:
public class Main6Activity extends AppCompatActivity {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL = "http://simplifiedcoding.16mb.com/VolleyUpload/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
private void uploadImage() { //Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) { //Disimissing the progress dialog
loading.dismiss(); //Showing toast message of the response
Toast.makeText(Main6Activity.this, s, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss(); //Showing toast
Toast.makeText(Main6Activity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap); //Getting Image Name
String name = editTextName.getText().toString().trim(); //Creating parameters
Map<String, String> params = new Hashtable<String, String>(); //Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name); //returning parameters
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadImage();
}
}
}
Thank you and help would be appreciated. For some reason the this is underlined in red. How do I resolve this?
Change the this in nested classes (such as in new Response.ErrorListener()) to:
Main6Activity.this

Categories

Resources