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

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

Related

Android Studio access files

want to open up text documents as text in an android app. I am working in Android Studio using Java. I have permissions set to allowed an I request user permissions, I researched a lot and could not find anything more than what I have. An error comes up that permission is not granted. I am using an android 7 or higher. Please help!
My code in MainActivity is:
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
//for asking permission
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu (menu);
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.open_note){
//get txt from file and send as text to textEditor action
//pick the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(
Intent.createChooser(intent, "Choose a file"),
8778
);
}
if (item.getItemId() == R.id.new_note){
//New Note
Intent intent = new Intent (getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
//get the file path as string
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8778 && resultCode == Activity.RESULT_OK){
checkPermissions();
if (ContextCompat.checkSelfPermission(
MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
//build the uri
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
verifyStoragePermissions(MainActivity.this);
String baseDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
StringBuilder text = new StringBuilder();
//request permission
final int REQUEST_CODE_ASK_PERMISSIONS = 1;
final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
try {
BufferedReader br = new BufferedReader(new
FileReader(("/storage/emulated/0/download/paperclip.txt")));
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage("YAY").show();
String line=br.readLine();
while (!((line).equals(null))) {
text.append(line);
text.append('\n');
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage(line + "great").show();
}
br.close();
} catch (IOException e) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("File
Name").setMessage("In the catch!" + e).show();
}
String result = text.toString();
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("File Info")
.setMessage(result + "result")
.show();
// You can use the API that requires the permission.
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("File
Name").setMessage("GRANTED").show();
//performAction(...);
}
}
}
protected void checkPermissions() {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("File Name").setMessage("In
Check Permissions").show();
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listVeiw);
SharedPreferences sharedPreferences =
getApplicationContext().getSharedPreferences("com.example.notepadr", Context.MODE_PRIVATE);
//Dealing with saving and stuff!!!!!
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set==null){
notes.add("Example note");
}else{
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
My xml in activity_main.xml is:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="-16dp"
tools:layout_editor_absoluteY="-69dp">
<Button
android:id="#+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Storage"
android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_centerHorizontal="true"/>
<ListView
android:id="#+id/listVeiw"
android:layout_width="400dp"
android:layout_height="732dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="false"
android:layout_marginTop="3dp"
android:layout_marginEnd="7dp"
android:layout_marginBottom="-3dp"
android:scrollbarSize="5dp"
android:scrollbarStyle="outsideInset" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Code in AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notepadr">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.NotePadR">
<activity android:name=".NoteEditorActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
enter code here <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Image not save in the device when click the button

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

Take image from camera or gallery and show in activity

I want to write a module where on a click of a button, the camera opens and I can click and capture an image. If I don't like the image, I can delete it and click one more image, and then select the image and it should return back and display that image in the activity.
The problem comes when I took a picture the camera application gets crashed and when I took a picture from the gallery the pic doesn't show in image view.
This is the script I wrote:
public class MainpageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
Toolbar toolbar = findViewById(R.id.toolbar);
imageView = (ImageView)this.findViewById(R.id.imageView1);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_camera_alt_black_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ RxPermissions rxPermissions = new RxPermissions(MainpageActivity.this);
rxPermissions
.request(Manifest.permission.CAMERA) // ask single or multiple permission once
.subscribe(granted -> {
if (granted) {
selectImage();
} else {
Toast.makeText(MainpageActivity.this, "Permission of camera is denied", Toast.LENGTH_SHORT).show();
}
});
}
});
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainpageActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
imageView.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
imageView.setBackgroundDrawable(drawable);
}
}
}
}
#Uma : Please follow this steps and change your code.
Step 1 - add both two line in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And also add this properties in application tag in manifest file:
android:largeHeap="true"
android:hardwareAccelerated="false"
Step - 2 - import lib in build.gradle file
implementation 'com.karumi:dexter:4.2.0' // for handling runtime permissions
Step - 3 - In your MainpageActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
this.fab = (FloatingActionButton) this.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CheckPermission();
}
});
}
private void CheckPermission(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
selectImage();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// permission is denied permenantly, navigate user to app settings
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
})
.onSameThread()
.check();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}}
Hope it helps you.
I think you should try to add this "android:required="true".
<uses-feature android:name="android.hardware.camera"
android:required="true" />
First of all, you need to handle with permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
After this, you can use this for opening gallery with button
//opening image chooser option
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
And with this function, you can show the image on UI
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//getting image from gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
image.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Also, you can convert image to bitmap64:
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

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

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