When I run the app it doesn't show up any layout just a blank page
This is my Java code:
public class MainActivity extends AppCompatActivity {
private boolean zoomOut = false;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
Button btnSelect;
LinearLayout root ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
Point point = null;
getWindowManager().getDefaultDisplay().getSize(point);
int width = point.x;
int height = point.y;
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.getLayoutParams().width = 20;
ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.MATCH_PARENT,
GridLayout.LayoutParams.WRAP_CONTENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut =false;
}else{
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
}
This is my xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp" >
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/SelectPhoto" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I've been advised that is was because onCreate wasn't placed properly but the I resolved that it's still not showing anything at all.
Please check your .Xml file name is matches with
setContentView(R.layout.activity_main);
Related
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);
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;
}
}
I have an application where I'm masking one image over the other. Now what I want is the bottom image should be fixed and I should be able to zoom or resize the above image which I want to mask. Any ideas/help would be great.
Here is the XML Code :-
<LinearLayout 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="wrap_content"
android:orientation="vertical"
tools:context="com.example.jervi.mytestapp2.EditCase">
<com.github.chrisbanes.photoview.PhotoView
android:id="#+id/zoom"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_gravity="center"
android:src="#drawable/iphonex" />
<Button
android:id="#+id/load_gallery"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Gallery" />
</LinearLayout>
Here is the Java Code :-
public class EditCase extends AppCompatActivity implements View.OnClickListener {
ImageView zoom;
private static final int PICK_IMAGE = 100;
Button gallery;
Uri imageUri;
Bitmap new_bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_case);
gallery = findViewById(R.id.load_gallery);
gallery.setOnClickListener(this);
zoom = findViewById(R.id.zoom);
PhotoViewAttacher photoView = new PhotoViewAttacher(zoom);
photoView.update();
}
//On click event for gallery
#Override
public void onClick(View v) {
if (v == gallery) {
openGallery();
}
}
//Opening the gallery
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
//On it's result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = data.getData();
zoom.setImageURI(imageUri);
try {
new_bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
makecustom_shapeImageScaleFit(zoom, new_bitmap);
}
}
//This is the masking method
public void makecustom_shapeImageScaleFit(ImageView mImageView, Bitmap bitmap) {
// Get custom_shape bitmap
//String getDevice = device_name;
Bitmap custom_shape = BitmapFactory.decodeResource(getResources(), R.drawable.iphonex);
//Scale imageView and it's bitmap to the size of the custom_shape
mImageView.getLayoutParams().width = custom_shape.getWidth();
mImageView.getLayoutParams().height = custom_shape.getHeight();
// Get bitmap from ImageView and store into 'original'
mImageView.setDrawingCacheEnabled(true);
mImageView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
mImageView.layout(0, 0, mImageView.getMeasuredWidth(), mImageView.getMeasuredHeight());
mImageView.buildDrawingCache(true);
//Bitmap original = BitmapFactory.decodeResource(getResources(), mContent);
// Scale that bitmap
Bitmap original_scaled = Bitmap.createScaledBitmap(bitmap, custom_shape.getWidth(), custom_shape.getHeight(), false);
mImageView.setImageBitmap(original_scaled);
mImageView.setDrawingCacheEnabled(false);
// Create result bitmap
Bitmap result = Bitmap.createBitmap(custom_shape.getWidth(), custom_shape.getHeight(), Bitmap.Config.ARGB_8888);
// Perform custom_shaping
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mCanvas.drawBitmap(original_scaled, 0, 0, null);
mCanvas.drawBitmap(custom_shape, 0, 0, paint);
paint.setXfermode(null);
// Set imageView to 'result' bitmap
mImageView.setImageBitmap(result);
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
// Make background transparent
mImageView.setBackgroundResource(android.R.color.transparent);
}
}
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();
Hi am trying to draw a sketch using Canvas over an ImageView in my activity where image is filled by taking picture on activity. I have specified Ontouchlistner to sketch over the image on touch position but am not getting my touch listener accurate. ie when i touch over the display the sketch is created over another place not at my touched position.
public class MainActivity extends AppCompatActivity implements SaveAction, View.OnTouchListener {
private ImageView image;
private static final int CAMERA_REQUEST = 1888;
final Context context = this;
Bitmap alterdbitmap;
Internet_checking mconnectionchecking;
AlertDialog ald;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "View Share";
private Uri fileUri;
FloatingActionButton fab,fab1;
Canvas canvas;
Paint paint;
Matrix matrix;
float downx = 0;
float downy = 0;
float upx = 0;
float upy = 0;
RelativeLayout rlayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.img);
rlayout = (RelativeLayout)findViewById(R.id.rltive1);
camera();
}
#Override
protected void onResume() {
super.onResume();
functionality();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
// Bitmap photo = (Bitmap) data.getExtras().get("data");
// image.setImageBitmap(photo);
previewimage();
} else if (resultCode == RESULT_CANCELED) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage("NO IMAGE FOUND");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
ald = alert.create();
ald.show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_LONG)
.show();
}
}
}
#TargetApi(23)
private void previewimage() {
try {
image.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
alterdbitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
canvas = new Canvas(alterdbitmap);
paint = new Paint();
paint.setColor(Color.parseColor("#FF5722"));
paint.setStrokeWidth(5);
matrix = new Matrix();
canvas.drawBitmap(bitmap, matrix, paint);
image.setImageBitmap(alterdbitmap);
image.setOnTouchListener(this);
// rlayout.setOnTouchListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
// #Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
private void functionality() {
fab1=(FloatingActionButton)findViewById(R.id.fab1);
fab = (FloatingActionButton)findViewById(R.id.fab);
// mbtn = (Button) findViewById(R.id.btn1);
mconnectionchecking = new Internet_checking(this);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mconnectionchecking.isNetworkAvailable() == true) {
final File photoFile = new File(getFilesDir(), String.valueOf(image));
Intent nt = new Intent(Intent.ACTION_SEND, Uri.fromFile(photoFile));
String title = getResources().getString(R.string.Share_Via);
Intent chooser = Intent.createChooser(nt, title);
startActivity(chooser);
} else {
AlertDialog.Builder at = new AlertDialog.Builder(context);
at.setTitle("Connection Error");
at.setCancelable(true);
at.setMessage("Internet connection required");
at.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_SETTINGS));
}
});
ald = at.create();
ald.show();
}
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
camera();
}
});
}
private void camera(){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
public void autosave() {
}
#Override
public boolean onTouch(View view, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
image.invalidate();
downx = upx;
downy = upy;
break;
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
canvas.drawLine(downx, downy, upx, upy, paint);
image.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e0080809"
tools:context="mypckage name.MainActivity">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/rltive1">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/img"
android:scaleType="fitXY"
android:layout_alignParentTop="true" />
<!--<Button-->
<!--android:layout_width="50dp"-->
<!--android:layout_height="50dp"-->
<!--android:id="#+id/btn1"-->
<!--android:layout_alignParentTop="true"-->
<!--android:layout_alignParentRight="true"-->
<!--android:layout_alignParentEnd="true"-->
<!--android:background="#drawable/share"/>-->
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
app:elevation="6dp"
app:backgroundTint="#color/colorAccent"
app:pressedTranslationZ="12dp"
android:src="#drawable/ic_share_white_24dp" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:elevation="6dp"
app:backgroundTint="#color/colorAccent"
app:pressedTranslationZ="12dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="4dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/ic_add_a_photo_white_24dp"
android:id="#+id/fab1"/>
</RelativeLayout>
</RelativeLayout>
In your activity class use custom imageview like this:
public class DrawImageView extends LinearLayout {
Paint paint = new Paint();
Point point = new Point();
Uri uri;
Context myContext;
public DrawImageView(Context context, Uri imageUri) {
super(context);
uri = imageUri;
myContext = context;
paint.setColor(Color.RED);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
try {
InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
this.setBackground(Drawable.createFromStream(inputStream, imageUri.toString()));
} catch (FileNotFoundException ignored) {
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(point.x - 10, point.y - 10, point.x + 10, point.y + 10, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
point.x = event.getX();
point.y = event.getY();
}
invalidate();
return true;
}
class Point {
float x, y;
}
}
this is just an example. in onDraw method realize your logic.