OutOfMemoryError Bitmap to Base64 string - java

I have an error in Android, can someone help me?
my Activity code :
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(
Connect.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},CODE_GALLERY_REQUEST
);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Image"),CODE_GALLERY_REQUEST);
}else {
Toast.makeText(this," Pour créer une photo de profil merci de nous donner la permission",Toast.LENGTH_SHORT);
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CODE_GALLERY_REQUEST&&resultCode==RESULT_OK&&data!=null){
Uri filePath=data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imagedata = imageToString(bitmap);
profileImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void updateLabel() {
String myFormat = "yyyy-MM-dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
naissance.setText(sdf.format(myCalendar.getTime()));
}
public void inscription(View view){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_inscription,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if(response.equals("SUCCES")){
// Intent intent = new Intent(getApplicationContext(),Connexion.class);
// startActivity(intent);
}else {
Toast.makeText(Connect.this, response, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"verifier votre connexion internet et réessayer",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image",imagedata);
params.put("pseudo",pseudo.getText().toString());
params.put("nom",nom.getText().toString());
params.put("prenom",prenom.getText().toString());
params.put("password",password.getText().toString());
params.put("email",email.getText().toString());
params.put("naissance",naissance.getText().toString());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT);
return encoded;
}
}
Error Stack:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tn.events.events, PID: 16587
java.lang.OutOfMemoryError: Failed to allocate a 24551844 byte allocation with 8376560 free bytes and 14MB until OOM
at java.lang.StringFactory.newStringFromBytes(StringFactory.java:88)
at java.lang.StringFactory.newStringFromBytes(StringFactory.java:65)
at android.util.Base64.encodeToString(Base64.java:456)
at tn.events.events.Connect.imageToString(Connect.java:195)
at tn.events.events.Connect.onActivityResult(Connect.java:129)
at android.app.Activity.dispatchActivityResult(Activity.java:6674)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4009)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4056)
at android.app.ActivityThread.access$1400(ActivityThread.java:196)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1588)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5982)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)

Related

How to save an image using CircleImageView Android Studio

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.

How to retrieve saved image from database?

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

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

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