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;
}
Related
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.
I have created a profile. Now, I can save a profile pic but I don't know how to retrieve an image. I have tried but didn't get any solution?
I have made some changes now after uploading an image when I visit profile again the image view gets invisible. please review my code, where did I have mistake?
I have tried to get image from shared preferences still doesn't work properly...
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my__profile);
edt_btn = findViewById(R.id.edt_btn);
user_pname = findViewById(R.id.user_profile_name);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
loadProfileDefault();
ImagePicker.clearCache(this);
sharedPreferenceClass = new SharedPreferenceClass(this);
sharedPreferenceClass = new SharedPreferenceClass(My_Profile.this);
user_id = sharedPreferenceClass.getValue_string("user_id");
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
edt_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(My_Profile.this,Editprofile.class);
startActivity(intent);
}
});
sharedPreferences=getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
final String name=sharedPreferenceClass.getName();
user_pname.setText(name);
String profileImage = sharedPreferences.getString("profile_image", "");
bitmap = decodeToBase64(profileImage);
imgProfile.setImageBitmap(bitmap);
}
private void loadProfile(String url) {
Log.d(TAG, "Image cache path: " + url);
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(url));
imgProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Glide.with(this).load(url)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
upload();
}
private void upload() {
sharedPreferences = getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
final byte[][] imageBytes = {baos.toByteArray()};
final String imgProfile1 = Base64.encodeToString(imageBytes[0], Base64.DEFAULT);
Log.d("converted to string",imgProfile1);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.khaokamao.in/ndokan/api/profile_pic.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("msg");
Log.i("Message",message);
Toast.makeText(getApplicationContext(), status + message + " ", Toast.LENGTH_LONG).show();
if (status.equalsIgnoreCase("Success")) {
Log.i("response",response);
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
imageBytes[0] = Base64.decode(imgProfile1, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes[0], 0, imageBytes[0].length);
imgProfile.setImageBitmap(decodedImage);
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(My_Profile.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_image",imgProfile1);
editor.commit();
Log.d("put_img","put_image");
editor.apply();
} else {
Toast.makeText(My_Profile.this, "Please Try Again..", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id",user_id);
params.put(KEY_PROFILE,imgProfile1);
return params;
}
};
stringRequest.setShouldCache(false);
int socketTimeout = 60000; // 30 seconds. You can change it
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(My_Profile.this);
requestQueue.add(stringRequest);
}
private void loadProfileDefault() {
Glide.with(this).load(bitmap)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String profileImage = sharedPreferences.getString("profile_image", "");
bitmap = decodeToBase64(profileImage);
imgProfile.setImageBitmap(bitmap);
}
#OnClick({R.id.img_profile})
void onProfileImageClick() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
showImagePickerOptions();
}
if (report.isAnyPermissionPermanentlyDenied()) {
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private void showImagePickerOptions() {
ImagePicker.showImagePickerOptions(this, new ImagePicker.PickerOptionListener() {
#Override
public void onTakeCameraSelected() {
launchCameraIntent();
}
#Override
public void onChooseGallerySelected() {
launchGalleryIntent();
}
});
}
private void launchCameraIntent() {
Intent intent = new Intent(My_Profile.this, ImagePicker.class);
intent.putExtra(ImagePicker.INTENT_IMAGE_PICKER_OPTION, ImagePicker.REQUEST_IMAGE_CAPTURE);
// setting aspect ratio
intent.putExtra(ImagePicker.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_Y, 1);
// setting maximum bitmap width and height
intent.putExtra(ImagePicker.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
intent.putExtra(ImagePicker.INTENT_BITMAP_MAX_WIDTH, 1000);
intent.putExtra(ImagePicker.INTENT_BITMAP_MAX_HEIGHT, 1000);
startActivityForResult(intent, REQUEST_IMAGE);
}
private void launchGalleryIntent() {
Intent intent = new Intent(My_Profile.this, ImagePicker.class);
intent.putExtra(ImagePicker.INTENT_IMAGE_PICKER_OPTION, ImagePicker.REQUEST_GALLERY_IMAGE);
// setting aspect ratio
intent.putExtra(ImagePicker.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_Y, 1);
startActivityForResult(intent, REQUEST_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
// You can update this bitmap to your server
// loading profile image from local cache
loadProfile(uri.toString());
}
}
}
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(My_Profile.this);
builder.setTitle(getString(R.string.dialog_permission_title));
builder.setMessage(getString(R.string.dialog_permission_message));
builder.setPositiveButton(getString(R.string.go_to_settings), (dialog, which) -> {
dialog.cancel();
openSettings();
});
builder.setNegativeButton(getString(android.R.string.cancel), (dialog, which) -> dialog.cancel());
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
here is my xml code
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/img_profile"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#drawable/useree1"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"
android:elevation="10dp"
android:scaleType="centerCrop"
android:layout_below="#+id/header_cover_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="-80dp"/>
<de.hdodenhof.circleimageview.CircleImageView
try this way :
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String profileImage = sharedPreferences.getString("profile_image", "");
Bitmap bitmap = decodeToBase64(profileImage);
public static Bitmap decodeToBase64(String str) {
byte[] decodedByte = Base64.decode(str, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
I'd recommend the Glide image handling library...
Makes this a lot easier...
https://github.com/bumptech/glide
ImageView imgView = findViewById(R.id.imageview);
Glide
.with(context)
.load(imageBytes)
.centerCrop()
.into(imgView);
I'm very new to this coding thing and I hope that anyone of you can help me out on this. Basically I have three different buttons with different image view and I would like to upload them to my MySQL. However when I press all three button at different times, it will only affect the 1 of the image views. Appreciate if you could help.
public static final int resultloadimage = 1;
private static final int RESULT_OK = -1;
Button btnupadloadnric, btnuploaddl, btnuploadvl,updateButton;
ImageView ivnric,ivdl,ivvl;
EditText fullanme, telephone;
String encodedimage;
ConnectionClass connectionClass;
String filename = null;
byte[] image = null;
private byte[] byteArray;
public Profile() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_profile, container, false);
btnupadloadnric = v.findViewById(R.id.btnAdminUploadNRICFragment);
btnuploaddl = v.findViewById(R.id.btnAdminUploadDLFragment);
btnuploadvl = v.findViewById(R.id.btnAdminUploadVCLFragment);
ivdl = v.findViewById(R.id.ivadminprofiledl);
ivnric = v.findViewById(R.id.ivadminprofilenric);
ivvl = v.findViewById(R.id.ivadminprofilevl);
fullanme = v.findViewById(R.id.etAdminFullNameProfileFragment);
telephone = v.findViewById(R.id.etAdminPhoneNumberProfileFragment);
updateButton = v.findViewById(R.id.btnAdminUpdateProfileFragment);
connectionClass = new ConnectionClass();
btnuploadvl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, resultloadimage);
}
});
btnuploaddl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, resultloadimage);
}
});
btnupadloadnric.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, resultloadimage);
}
});
updateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
UploadImage uploadImage = new UploadImage();
uploadImage.execute("");
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultcode, Intent data)
{
super.onActivityResult(requestCode,resultcode,data);
if (requestCode == resultloadimage && resultcode == RESULT_OK && null !=data){
Bitmap originbitmap = null;
Uri selectedImage = data.getData();
InputStream imagestream;
try {
imagestream = getActivity().getContentResolver().openInputStream(selectedImage);
originbitmap = BitmapFactory.decodeStream(imagestream);
}catch (FileNotFoundException e)
{
Toast.makeText(getActivity(),"Done",Toast.LENGTH_LONG).show();
}
if (originbitmap!=null){
this.ivdl.setImageBitmap(originbitmap);
Log.w("Image in", "Done");
try {
Bitmap image = ((BitmapDrawable)ivdl.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 90 , byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
encodedimage = Base64.encodeToString(byteArray,Base64.DEFAULT);
UploadImage uploadImage = new UploadImage();
uploadImage.execute("");
}catch (Exception e){
Log.w("asd", "Exception");
}
Toast.makeText(getActivity(),"Done",Toast.LENGTH_LONG).show();
}
}
else{
System.out.println("Error Occured");
}
}
public class UploadImage extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... strings) {
try {
Connection con = connectionClass.CONN();
if (con==null) {
Toast.makeText(getActivity(),"Check Internet", Toast.LENGTH_LONG).show();
}else{
String command = "Insert into driverprofile (DrivingL, Username, Password) values('" + encodedimage + "', 'Admin1', '12345')";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(command);
if (rs.next()){}
}
} catch (Exception ex) {
ex.getMessage();
}
return null;
}
}
}
I think you should change request codes for each gallery intent on each button click.
btnuploadvl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, "request code for btnuploadvl");
}
});
btnuploaddl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, "request code for btnuploaddl");
}
});
btnupadloadnric.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, "request code for btnupadloadnric");
}
});
And then check request code detecting which button is clicked on onActivityResult.
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;
}
}
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);
}