I am trying to open camera intent in my app.But I just need to make sure that the image doesn't get saved in either the SD Card or in the Internal Storage.Also the image should get displayed in the app when the picture is clicked.
public class FBCheckInActivity extends Activity{
private CallbackManager callbackManager;
private LoginManager loginManager;
private File mFileTemp;
public static final int REQUEST_CODE_TAKE_PICTURE = 2;
public String path;
Bitmap sharingPhoto;
String caption="";
ImageView chooseImage;
EditText captionText;
Button postFacebook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_sharing);
printHashKey();
sharingPhoto= BitmapFactory.decodeResource(this.getResources(), R.drawable.no_image);
FacebookSdk.sdkInitialize(getApplicationContext());
fbSharing(sharingPhoto);
}
private void fbSharing(Bitmap sharingPhoto) {
chooseImage=(ImageView) findViewById(R.id.share_image);
chooseImage.setImageBitmap(sharingPhoto);
captionText=(EditText) findViewById(R.id.caption_text);
postFacebook=(Button) findViewById(R.id.buttonPost);
postFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginFaceBook();
}
});
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCamera();
}
});
captionText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
caption = captionText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
protected void onResume() {
super.onResume();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if(requestCode==REQUEST_CODE_TAKE_PICTURE){
Log.d("zambo","after selecting pic");
path = mFileTemp.getPath();
Log.d("zambo", path);
sharingPhoto = BitmapFactory.decodeFile(path);
chooseImage.setImageBitmap(sharingPhoto);
fbSharing(sharingPhoto);
}
else {
Log.d("zambo","callback manager for facebook sharing");
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
public void printHashKey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.urbanwand",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
public void loginFaceBook(){
callbackManager = CallbackManager.Factory.create();
List<String> permissionNeeds = Arrays.asList("publish_actions");
loginManager = LoginManager.getInstance();
loginManager.logInWithPublishPermissions(FBCheckInActivity.this, permissionNeeds);
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
graphApi(accessToken);
}
#Override
public void onCancel() {
Toast.makeText(FBCheckInActivity.this, "cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(FBCheckInActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
}
public void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
Uri mImageCaptureUri = null;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mFileTemp = new File(Environment
.getExternalStorageDirectory(), "IMG_"
+ ".jpg");
mImageCaptureUri = Uri.fromFile(mFileTemp);
} else {
/*
* The solution is taken from here:
* http://stackoverflow.com/questions
* /10042695/how-to-get-camera-result-as-a-uri-in-data-folder
*/
mFileTemp = new File(getFilesDir(), "IMG_"
+ ".jpg");
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
//Log.d("User_Photo", "cannot take picture", e);
}
}
public void graphApi(AccessToken accessToken){
GraphRequest request = GraphRequest.newUploadPhotoRequest(accessToken, "me/photos", sharingPhoto, caption, null, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.d("zambo","On Completed Callback");
AlertDialog.Builder completeDialog = new AlertDialog.Builder(FBCheckInActivity.this);
completeDialog.setMessage("Thank you for sharing your happiness!!");
completeDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(FBCheckInActivity.this, DinerHotSellers.class));
overridePendingTransition(0, 0);
}
});
completeDialog.create();
completeDialog.show();
}
});
request.executeAsync();
}
This is what i have implemnted till now. But it doesn't give me the image back in the activity if it is stored in SD Card. Also the image is getting saved. Is is possible not to save the image in the storage media?
Thanks
A simple demo:
maim.xml
<button android:id="#+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="TakePhoto" button="">
<imageview android:id="#+id/imageView1" android:layout_gravity="center_horizontal" android:layout_height="wrap_content" android:layout_width="wrap_content"></imageview></button>
MainActivity.java(not all)
public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
private Button takePhotoBn;
private ImageView showImage;
private Uri imageUri;
private String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhotoBn = (Button) findViewById(R.id.button1);
showImage = (ImageView) findViewById(R.id.imageView1);
takePhotoBn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat(yyyyMMddHHmmss);
Date date = new Date(System.currentTimeMillis());
filename = format.format(date);
//File outputImage = new File(Environment.getExternalStorageDirectory(),test.jpg);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File outputImage = new File(path,filename+.jpg);
try {
if(outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch(IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent(android.media.action.IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,TAKE_PHOTO);
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
Toast.makeText(MainActivity.this, ActivityResult resultCode error, Toast.LENGTH_SHORT).show();
return;
}
switch(requestCode) {
case TAKE_PHOTO:
Intent intent = new Intent(com.android.camera.action.CROP); //cut
intent.setDataAndType(imageUri, image/*);
intent.putExtra(scale, true);
intent.putExtra(aspectX, 1);
intent.putExtra(aspectY, 1);
intent.putExtra(outputX, 340);
intent.putExtra(outputY, 340);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
Toast.makeText(MainActivity.this, " ", Toast.LENGTH_SHORT).show();
//flush
Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intentBc.setData(imageUri);
this.sendBroadcast(intentBc);
startActivityForResult(intent, CROP_PHOTO);
break;
case CROP_PHOTO:
try {
Bitmap bitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(imageUri));
Toast.makeText(MainActivity.this, imageUri.toString(), Toast.LENGTH_SHORT).show();
showImage.setImageBitmap(bitmap); //show image
} catch(FileNotFoundException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
you need add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.CAMERA"> </uses-permission></uses-permission>
Related
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 am taking image from camera as well as from gallery,after getting the image, I want to show the image in imageview.
Image that is captured by camera successfully is shown in imageview but when I want to select it from gallery it does not show the image and it also does not show any error. It was working properly but later I add camera feature in activity, it's not working well.
public class DoReport extends AppCompatActivity {
private EditText subject,detail;
private ImageView pic;
private ImageView iv;
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;
static final int REQUEST_IMAGE_CAPTURE = 1;
String userChoosenTask;
#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);
iv=(ImageView)findViewById(R.id.ImgView);
}
public void onBackClick(View v) {
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(this,UserView.class);
startActivity(intent);
finish();
}
//to pic the image from galery
//this is new <code>
public void imgBtn(View v) {
selectImage();
}
private void updateSelectedPicture(Uri uri) {
try {
imageUri = uri;
InputStream imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
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);
}
/*//////////////////////////////////////////////////////////////////////////////////////////
code for selecting image from camera or gallery
*////////////////////////////////////////////////////////////////////////////////////////
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
}
///////////////it will show the dialogue box
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(DoReport.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(DoReport.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
dispatchTakePictureIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
gallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void gallery() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
}
}
only change onActivityResult method remove else if block form id condition like below code...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode== REQUEST_IMAGE_CAPTURE) {
try {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
image = encode(imageBitmap);//this line is added to encode
}
}
catch (Exception e){ Toast.makeText(DoReport.this, e.toString(), Toast.LENGTH_LONG).show();}
}
else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
}
selectedImage = BitmapFactory.decodeStream(imageStream);
You should check if selectedImage -the bitmap- is null.
I bet selectedImage==null.
This happens if the bitmap would become too big for available memory.
You should scale it down while loading from stream.
Remember: from the camera you only obtain a thumbnail. Thats the difference.
Here's my code to set a rounding photo from gallery or camera into ImageButton and it works perfectly :
public class EditProfileActivity extends AppCompatActivity {
ImageButton btnValidate,btnCancel,imgProfile;
TextView tvEditPhoto;
RoundImage roundedImage;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnCancel = findViewById(R.id.toolbar_back_btn);
btnValidate = findViewById(R.id.toolbar_validate_btn);
imgProfile = findViewById(R.id.user_profile_photo_edit);
tvEditPhoto = findViewById(R.id.user_profile_name_edit);
//Rounding image
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.profile);
roundedImage = new RoundImage(bm);
imgProfile.setImageDrawable(roundedImage);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
tvEditPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PictureUtility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
Toast.makeText(EditProfileActivity.this, "Oups ! vous n'avez pas la permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result= PictureUtility.checkPermission(EditProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//resize picture
Bitmap bmw = Bitmap.createScaledBitmap(thumbnail, 120, 120, false);
//rounding picture
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap bmw = Bitmap.createScaledBitmap(bm, 120, 120, false);
roundedImage = new RoundImage(bmw);
imgProfile.setImageDrawable(roundedImage);
}
}
In your code, try to add createScaledBitmap to resize your photo like this:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
//add this line and use the new bitmap resized
Bitmap imageBitmapResized = Bitmap.createScaledBitmap(imageBitmap , 120, 120, false);
iv.setImageBitmap(imageBitmapResized );
image = encode(imageBitmapResized );//this line is added to encode
} else if (requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK) {
updateSelectedPicture(data.getData());
}
I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.
Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.