Image not save in the device when click the button - java

Currently, I am using the Picasso library to download images and save it in the device when I press the button. the problem is when I press the button the image not download and just shown the message "Image Downloaded" , so how can i fix it? Here is my code
PicassoDisplayImageAdapter.java
/*
* This class for display the image when clicking on it
* It gets the data from the class have the images "Images in ArrayList"
* Also It is for download images
*/
public class PicassoDisplayImageAdapter extends AppCompatActivity {
public static final int PERMISSION_WRITE = 0;
String fileUri;
Button download_image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
/* Display the data in the ImageView with Picasso "ImageView that insert in he activity" */
final ImageView imageView = findViewById(R.id.image_display);
final Intent intent = getIntent();
if (intent.hasExtra("imageUrl")){
String url = intent.getStringExtra("imageUrl");
Picasso.with(this)
.load(url)
.fit() // to resize the image to imageView
.placeholder(R.drawable.progress_animation)
.error(R.drawable.error)
.into(imageView);
}
/* button to download the image */
download_image = findViewById(R.id.button_download);
checkPermission();
download_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
});
}
/* method to save image*/
private void SaveImage(String url) {
Picasso.with(getApplicationContext()).load(url).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File mydir = new File(Environment.getExternalStorageDirectory() + "/11zon");
if (!mydir.exists()) {
mydir.mkdirs();
}
fileUri = mydir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
FileOutputStream outputStream = new FileOutputStream(fileUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Image Downloaded", Toast.LENGTH_LONG).show();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
/* runtime storage permission */
public boolean checkPermission() {
int READ_EXTERNAL_PERMISSION = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if((READ_EXTERNAL_PERMISSION != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_WRITE);
return false;
}
return true;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==PERMISSION_WRITE && grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//do somethings
}
}
}
ImagesRamadanActivity.java That has the data
/*
* This Activity for display the ramadan images
* This class has the data of images
*/
public class ImagesRamadanActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ramadan_images);
/* ArrayList for RamadanImages */
final String[] RamadanImages = {
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
};
/* make new object and find the view "GridView" */
GridView gridView2 = findViewById(R.id.gridview_image_ramadan);
// display all the images from Array on it
gridView2.setAdapter(new PicassoImagesAdapter(ImagesRamadanActivity.this, RamadanImages));
/* display the image when click on it */
// we made a class for this method "the class called PicassoDisplayImageAdapter"
gridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the image
String image = RamadanImages[position];
Intent intent = new Intent(ImagesRamadanActivity.this, PicassoDisplayImageAdapter.class);
intent.putExtra("imageUrl", image);
ImagesRamadanActivity.this.startActivity(intent);
}
});
activity_image_display.xml activity to display the photo and has the button to download the image
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image_display"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageView>
<Button
android:id="#+id/button_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="download the image"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp" />
</RelativeLayout>

Inside,
onCreate(){
setContentView(..);
// requestPermission. ask for permission when app starts.
}
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
// kind of this, add this block to your existing code.
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to save files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
// make sure Manifest has all the permission defined

Related

In my app I can't transfer the picture I took from the Camera to the app

I made an automobile management application.
I made a vehicle image adding system in the application.
When the Image is selected I want to upload it to firebase and view it.
When I select a picture from the gallery, I can upload and view it, it works without any problems.
At the same time, when I select Camera, I ask for permission and access the camera, but this is the part that doesn't work. After I take the picture from the camera, I return to the application, but the picture I took is not visible. I don't know how to do this.
And.. I don't know how to code.
I'm trying to watch video lessons and adapt them the way I want to make the applications in my head.
This application is the last point I came to.
As far as I saw the answers to the previous questions and the videos, I could not answer this question.
I know it will be difficult, but can you show this ignorant the correct method?
`
public class UploadActivity extends AppCompatActivity {
Uri imageData;
ActivityResultLauncher<Intent> activityResultLauncher;
ActivityResultLauncher<String> permissionLauncher;
private ActivityUploadBinding binding;
private FirebaseStorage firebaseStorage;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Burada Yazan kod ustteki standart titleyi kaldirmak icin.
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
// Burada Bitiyor.
binding = ActivityUploadBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
registerLauncher();
//Firebase fireStorage icin
firebaseStorage = FirebaseStorage.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
storageReference = firebaseStorage.getReference();
`
`
public void selectImage(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Resim Seciniz");
builder.setMessage("Resim Kaynagini Seciniz");
builder.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
/* if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE); */
if (ContextCompat.checkSelfPermission(UploadActivity.this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(UploadActivity.this,Manifest.permission.CAMERA)) {
Snackbar.make(view,"Kameraniza Erismek icin izin gereklidir.",Snackbar.LENGTH_INDEFINITE).setAction("izin Ver", new View.OnClickListener() {
#Override
public void onClick(View view) {
permissionLauncher.launch(Manifest.permission.CAMERA);
}
}).show();
} else {
permissionLauncher.launch(Manifest.permission.CAMERA);
}
} else {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activityResultLauncher.launch(takePicture);
}
dialogInterface.dismiss();
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(ContextCompat.checkSelfPermission(UploadActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(UploadActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)) {
Snackbar.make(view,"Galerinize erişmek için izin gereklidir.",Snackbar.LENGTH_INDEFINITE).setAction("İzin Ver", new View.OnClickListener() {
#Override
public void onClick(View v) {
//izin isteyecegiz.
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
}
}).show();
} else {
//Ekstra izin isteyecegiz.
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
}
} else {
// Zaten izin verilmis ise.
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(pickPhoto);
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void registerLauncher() {
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
Intent intentFromResult = result.getData();
if(intentFromResult != null) {
imageData = intentFromResult.getData();
binding.addCarPicture.setImageURI(imageData);
}
}
}
});
permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
#Override
public void onActivityResult(Boolean result) {
if(result) {
Intent intentToGallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(intentToGallery);
} else {
Toast.makeText(UploadActivity.this,"iznine ihtiyacimiz var",Toast.LENGTH_LONG).show();
}
}
});
}
`
A couple of things.
You should use request codes, so you can check for it in you activity result method and use some logic to distinguish between taking a picture and selecting a photo from the gallery. Because the Gallery and Camera return different different things.
Second, the image taken from the camera isn't saved. It doesn't have a URI location, because it's just in memory.
if(intentFromResult != null) {
imageData = intentFromResult.getData();
Bitmap img = (Bitmap)(data.getExtras().get()'data'));
//Upload img to Database
//Set imageView from Database
}
Here is the documentation on the way you are trying to implement it:
https://developer.android.com/training/camera-deprecated/photobasics
Here is the current documentation on how it should be implemented:
https://developer.android.com/guide/topics/media/camera
And one last bit to think about. It might be better to use a library so you don't have to write a whole new implementation.
I've used https://github.com/Dhaval2404/ImagePicker before, it's ok. There might be a better one out there that suits your needs. Take your time and look around.

Stripe Android - Attach Card To Customer After Setup Intent

I'm working with stripe integration. To add and save card. For entering card details i'm using stripe's default AddPaymentMethodActivityStarter . After setup intent my card is not attached to the customer and it is not not displayed in stripe console as well.
Is there any way to automatically attach card after setup intent (stripe.confirmSetupIntent) ?
Also i'm adding a footer layout to AddPaymentMethodActivityStarter. and the footer layout has a checkbox. is there any way to get the checkbox checked,unchecked value. Even after initialization, i always get null
StripeActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stripe_latest);
initMethod();
findElements();
// Get ephemeralKey
CustomerSession.initCustomerSession(this, (s, ephemeralKeyUpdateListener) -> getEphemeralKey(ephemeralKeyUpdateListener, s));
// Use the publishable key from the server to initialize the Stripe instance.
stripe = new Stripe(getApplicationContext(), getString(R.string.stripe_publishable_key));
// launch stripe add card ui
new AddPaymentMethodActivityStarter(StripeAddCardActivityDup.this).startForResult(
new AddPaymentMethodActivityStarter.Args.Builder()
.setAddPaymentMethodFooter(R.layout.footer_layout) // --> get the value of checkbox
.build());
// initialize the checkbox, in footer layout
saveCard = findViewById(R.id.saveCard);
if(saveCard !=null){
if(saveCard.isChecked()){
Toast.makeText(this, "checkbox is checked", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "checkbox is not checked", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(this, "checkbox is null", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
messageHandler.lock(StripeAddCardActivityDup.this);
if (requestCode == AddPaymentMethodActivityStarter.REQUEST_CODE) { // result of AddPaymentMethodActivityStarter. get payment id and send to setupintent
final AddPaymentMethodActivityStarter.Result result =
AddPaymentMethodActivityStarter.Result.fromIntent(data);
if (result instanceof AddPaymentMethodActivityStarter.Result.Success) {
final AddPaymentMethodActivityStarter.Result.Success successResult =
(AddPaymentMethodActivityStarter.Result.Success) result;
setUpIntent(successResult.getPaymentMethod().id);
}
} else if (requestCode == 50001) { // result of setup intent
WeakReference<Activity> weakActivity = new WeakReference<>(this);
// Handle the result of stripe.confirmSetupIntent
stripe.onSetupResult(requestCode, data, new ApiResultCallback<SetupIntentResult>() {
#Override
public void onSuccess(#NonNull SetupIntentResult result) {
SetupIntent setupIntent = result.getIntent();
SetupIntent.Status status = setupIntent.getStatus();
if (status == SetupIntent.Status.Succeeded) {
// Setup completed successfully
runOnUiThread(() -> {
if (weakActivity.get() != null) {
attachCustomer(setupIntent.getPaymentMethodId()); // --> manually attaching the card to customer after setup intent using "attachPaymentMethod"
}
});
} else if (status == SetupIntent.Status.RequiresPaymentMethod) {
// Setup failed – allow retrying using a different payment method
runOnUiThread(() -> {
Activity activity = weakActivity.get();
if (activity != null) {
stripeErrorAlert(setupIntent.getLastSetupError().getMessage());
}
});
}
}
#Override
public void onError(#NonNull Exception e) {
// Setup request failed – allow retrying using the same payment method
runOnUiThread(() -> {
Activity activity = weakActivity.get();
if (activity != null) {
stripeErrorAlert(e.toString());
}
});
}
});
}
}
// method to confirm setup intent
public void setUpIntent(String paymentMethodId) {
BackgroundExecutor.execute(new BackgroundExecutor.Task("", 0, "") {
#Override
public void execute() {
try {
messageHandler.lock(StripeAddCardActivityDup.this);
// retrofit WS to get client secret
SetupIntentModel intentModel = driverService.getSetupIntent(new StripeSetupIntentRequest(getString(R.string.stripe_customer_id)));
runOnUiThread(() -> {
ConfirmSetupIntentParams confirmParams = ConfirmSetupIntentParams.create(paymentMethodId, intentModel.getClientSecret(),"redirect://stripe");
stripe.confirmSetupIntent(StripeAddCardActivityDup.this, confirmParams);
});
} catch (Exception e) {
Logger.logError(AppConstants.GENERAL_TAG, e);
}
}
});
}
// attach card to customer
private void attachCustomer(String paymentId){
CustomerSession.getInstance().attachPaymentMethod(paymentId, new CustomerSession.PaymentMethodRetrievalListener() {
#Override
public void onPaymentMethodRetrieved(#NotNull PaymentMethod paymentMethod) {
messageHandler.showAlert(getString(R.string.card_was_successful_added), getString(R.string.ok), "", v -> finish(),null);
}
#Override
public void onError(int i, #NotNull String s, #org.jetbrains.annotations.Nullable StripeError stripeError) {
String errorMsg = getString(R.string.card_wasnt_successful_added)+"-"+stripeError.toString();
messageHandler.showAlert(errorMsg, getString(R.string.ok), "", v -> finish(),null);
}
});
}
footer_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#color/white"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/saveCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:text="save card" />
</LinearLayout>

How to make a RecylerView like WhatsApp Chat activity?

I building an app which should have a layout almost identical to the one used in WhatsApp in the chat activity. it should have a text input, camera & video recording option. Items should be centered inside the recycler and when the dataset is changed the recycler should scroll to the last item added. when the user clicks on the Editext keyboard should resize the view moving recycler up and focus on the last item in the Dataset.
For the scrolling part, I have used SmoothScrollToPosiotion but when an item, which contains an image or a video, the view gets chopped, auto scroll also stops working. a weird bug is when I open the keyboard by clicking on editText the recycler scrolls almost to the last item but not completely, only if reopen the keyboard multiple times it shows the item completely.
already tried solutions found on google, and here with not expected results :(
EDIT: almost solved, I have just moved SmoothScrollToposition inside the onClickListener of every button. Now it does not scroll to the last item it just scrolls to the item before the last but completely :D
here some code:
(if needed full code at https://github.com/MikeSys/ChatApp)
MainActivity Layout
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:background="#drawable/sfondo"
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintTop_toTopOf="parent"
/>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="55dp"
app:layout_constraintBottom_toBottomOf="parent"
android:orientation="horizontal">
<EditText
android:layout_gravity="center_vertical"
android:id="#+id/editText"
android:layout_width="255dp"
android:layout_height="55dp"
android:background="#0003A9F4"
android:hint="Scrivi"
android:padding="10dp" />
<Button
android:layout_gravity="center_vertical"
android:id="#+id/camera"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/camera"
/>
<Button
android:layout_gravity="center_vertical"
android:id="#+id/video"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/video"
/>
<Button
android:id="#+id/send"
android:layout_width="55dp"
android:layout_height="55dp"
android:background="#drawable/send" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
MainActivity Code
public class MainActivity extends AppCompatActivity {
private ArrayList<ModelloDati> dati = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private static final String VIDEO_DIRECTORY = "/Chat";
private myAdapter adapter;
public Uri passUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Variables-----------------------------------------
final RecyclerView recyclerView = findViewById(R.id.recyclerView);
Button video = findViewById(R.id.video);
Button camera = findViewById(R.id.camera);
Button send = findViewById(R.id.send);
final EditText editText = findViewById(R.id.editText);
// Layout Manager------------------------------------------------
linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
// Adapter-----------------------------------------
if(dati.size()> 1){
adapter = new myAdapter(dati, this);
//Removed SmoothScroll form here
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
else{
Collections.reverse(dati);
adapter = new myAdapter(dati,this);
recyclerView.setAdapter(adapter);
}
// Click Listener Video button---------------------------------------------
video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent,0);
//Added here SmotthScroll
recyclerView.smoothScrollToPosition(dati.size());
}
});
// Click Listener Camera button--------------------------------------------
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,1);
//Added here SmotthScroll
recyclerView.smoothScrollToPosition(dati.size());
}
});
// Click Listener Send button----------------------------------------------
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = editText.getText().toString();
dati.add(new ModelloDati(0,string));
editText.getText().clear();
//Added here SmotthScroll
recyclerView.smoothScrollToPosition(dati.size());
closeKeyboard();
}
});
}
private void closeKeyboard() {
View view = getCurrentFocus();
if(view != null){
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 0:
try {
Uri contentURI = data.getData();
passUri = contentURI;
String recordedVideoPath = getPath(contentURI);
Log.d("frrr", recordedVideoPath);
saveVideoToInternalStorage(recordedVideoPath);
dati.add(new ModelloDati(2, contentURI));
}catch (Throwable o){Log.i("CAM","User aborted action");}
case 1:
try {
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
dati.add(new ModelloDati(1,bitmap));
}catch(Throwable o){
Log.i("CAM","User aborted action");
}
}
}
private void saveVideoToInternalStorage (String filePath) {
File new file;
try {
File currentFile = new File(filePath);
File wallpaperDirectory = new
File(Environment.getExternalStorageDirectory() + VIDEO_DIRECTORY);
newfile = new File(wallpaperDirectory,
Calendar.getInstance().getTimeInMillis() + ".mp4");
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v("vii", "Video file saved successfully.");
}else{
Log.v("vii", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
Solved by Moving smoothScrollToPosition inside onClickListerner (video/camera button I had to move it inside onActivityResult).
Updated Main
public class MainActivity extends AppCompatActivity {
private ArrayList<ModelloDati> dati = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private static final String VIDEO_DIRECTORY = "/Chat";
private myAdapter adapter;
private RecyclerView recyclerView;
private VideoView videoView;
public Uri passUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Variables-----------------------------------------
recyclerView = findViewById(R.id.recyclerView);
Button video = findViewById(R.id.video);
Button camera = findViewById(R.id.camera);
Button send = findViewById(R.id.send);
final EditText editText = findViewById(R.id.editText);
// Layout Manager------------------------------------------------
linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setStackFromEnd(true);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(itemAnimator);
// Adapter-----------------------------------------
//adapter.notifyDataSetChanged();
adapter = new myAdapter(dati, this);
recyclerView.setAdapter(adapter);
// Click Listener Video button----------------------------------------------
video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent,0);
}
});
// Click Listener Camera button----------------------------------------------
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,1);
}
});
// Click Listener Send button------------------------------------------------
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = editText.getText().toString();
dati.add(new ModelloDati(0,string));
adapter.notifyItemInserted(dati.size());
editText.getText().clear();
recyclerView.smoothScrollToPosition(dati.size());
closeKeyboard();
}
});
}
private void closeKeyboard() {
View view = getCurrentFocus();
if(view != null){
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 0:
try {
Uri contentURI = data.getData();
passUri = contentURI;
String recordedVideoPath = getPath(contentURI);
saveVideoToInternalStorage(recordedVideoPath);
dati.add(new ModelloDati(2, contentURI));
adapter.notifyItemInserted(dati.size());
recyclerView.smoothScrollToPosition(dati.size());
}catch (Throwable o){Log.i("CAM","User aborted action");}
case 1:
try {
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
dati.add(new ModelloDati(1,bitmap));
adapter.notifyItemInserted(dati.size());
recyclerView.smoothScrollToPosition(dati.size());
}catch(Throwable o){
Log.i("CAM","User aborted action");
}
}
}
private void saveVideoToInternalStorage (String filePath) {
File newfile;
try {
File currentFile = new File(filePath);
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() +
VIDEO_DIRECTORY);
newfile = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis()
+ ".mp4");
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v("vii", "Video file saved successfully.");
}else{
Log.v("vii", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}

mp3 share via whatsapp (this file is not supported) error

when i click created share button i took the file is not supported error
i did try a lot of answers about this issue in stackoverflow but i cannot access success
thank you so much aldready
Button btnShare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShare=(Button) findViewById(R.id.button);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File f=new File("R.raw.sound3");
Uri uri = Uri.parse("file://"+f.getAbsolutePath());
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(share, "Share audio File"));
}
});
}
}
manifest permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
There are two things you need to do. Firstly check if you have granted permission and check if your raw data in external storage.Let's give example :
We have a simple button on main xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Paylas" />
</RelativeLayout>
Check if you have permisson :
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("","Permission is granted");
return true;
} else {
Log.v("","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("","Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v("","Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
Copy your raw data into external storage :
private String copyFiletoExternalStorage(int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pathSDCard;
}
and the main code should be like this :
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isStoragePermissionGranted()) {
String rout = copyFiletoExternalStorage(R.raw.guitar,"guitar.mp3");
Uri uri = Uri.parse(rout);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM,uri);
try {
startActivity(share);
}catch (android.content.ActivityNotFoundException ex){
Toast.makeText(getApplicationContext(),"Please, install Whatsapp", Toast.LENGTH_LONG).show();
}
}
}
});
Also may you want to check full source code here is github

Take picture and Save picture after button is pressed

Need help on creating a method that will capture a picture, and a method that will save it if a button is pressed.
Currently, the camera is being displayed inside a TextureView as soon as the app starts and I am struggling to find a way to capture and save pictures.
It doesn't really matter if it captures from screen or from the actual phone camera.
Github: https://github.com/Chalikov/group26/tree/experimental
Thank you.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CAMERA_PERMISSION = 200;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "AndroidCameraApi";
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
protected CameraDevice cameraDevice;
protected CameraCaptureSession cameraCaptureSessions;
protected CaptureRequest.Builder captureRequestBuilder;
private Button takePictureButton;
private Button retryButton;
private Button acceptButton;
private TextureView textureView;
private String cameraId;
private Size imageDimension;
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//open your camera here
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Transform you image captured size according to the surface width and height
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};
private ImageReader imageReader;
private Uri file;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
#Override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
private HandlerThread mBackgroundThread;
private View view;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
textureView = (TextureView) findViewById(R.id.texture);
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
takePictureButton = (Button) findViewById(R.id.btn_takepicture);
assert takePictureButton != null;
takePictureButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
takePicture();
takePictureButton.setVisibility(View.INVISIBLE);
retryButton = (Button) findViewById(R.id.btn_retry);
acceptButton = (Button) findViewById(R.id.btn_analyze);
retryButton.setVisibility(View.VISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
retryButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
createCameraPreview();
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
}
});
retryButton.setVisibility(View.VISIBLE); //SHOW the button
acceptButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
createCameraPreview();
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
}
});
acceptButton.setVisibility(View.VISIBLE); //SHOW the button
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void takePicture() {
}
protected void savePicture() {
}
// private static File getOutputMediaFile(){
// File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES), "CameraDemo");
//
// if (!mediaStorageDir.exists()){
// if (!mediaStorageDir.mkdirs()){
// return null;
// }
// }
//
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// return new File(mediaStorageDir.getPath() + File.separator +
// "IMG_"+ timeStamp + ".jpg");
// }
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
texture.setDefaultBufferSize(height, width);
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Log.e(TAG, "openCamera X");
}
protected void updatePreview() {
if(null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
// close the app
Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onResume() {
takePictureButton.setVisibility(View.VISIBLE);
super.onResume();
Log.e(TAG, "onResume");
startBackgroundThread();
if (textureView.isAvailable()) {
openCamera();
} else {
textureView.setSurfaceTextureListener(textureListener);
}
}
#Override
protected void onPause() {
retryButton.setVisibility(View.INVISIBLE);
acceptButton.setVisibility(View.INVISIBLE);
Log.e(TAG, "onPause");
stopBackgroundThread();
super.onPause();
closeCamera();
}
}
The XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.project26.MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextureView
android:id="#+id/texture"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/btn_takepicture"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="80dp"
android:background="#drawable/camera_button"
android:visibility="visible"/>
<Button
android:id="#+id/btn_retry"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="left|bottom"
android:layout_marginBottom="80dp"
android:layout_marginLeft="60dp"
android:background="#drawable/retry"
android:visibility="invisible" />
<Button
android:id="#+id/btn_analyze"
android:layout_width="79dp"
android:layout_height="79dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="right|bottom"
android:layout_marginBottom="80dp"
android:layout_marginRight="60dp"
android:background="#drawable/analyze"
android:visibility="invisible" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical|bottom"
android:background="#4D000000"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ffffff"
android:text="Gallery"
android:textColor="#fff"
android:textSize="12sp"/>
<Button
android:id="#+id/camera_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#00ffffff"
android:text="Camera"
android:textColor="#fff"
android:textSize="12sp"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
//Modify Id and names according to your project.
//below onclick listener takes pic
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
//override onPictureTaken method, write the below code that saves it to a file.
File pictureFile = PATHOFYOURLOCATION;
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
Log.d(TAG, "written");
Toast.makeText(getApplicationContext(), "image saved in "+pictureFile, Toast.LENGTH_SHORT).show();
fos.close();

Categories