Photoshop image blending mode in Android - android

After a lot of searching now i am able to create Photoshop blending mode filter in android. Here is my working code for image blending mode in android it is working from android 2.1 to 4.4 enjoy and incase of any query feel free to ask :)
public class MainActivity extends Activity {
Button btnLoadImage1, btnLoadImage2;
TextView textSource1, textSource2;
Button btnProcessing;
ImageView imageResult;
final int RQS_IMAGE1 = 1;
final int RQS_IMAGE2 = 2;
int blendmode=1;
Uri source1, source2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage1 = (Button) findViewById(R.id.loadimage1);
btnLoadImage2 = (Button) findViewById(R.id.loadimage2);
textSource1 = (TextView) findViewById(R.id.sourceuri1);
textSource2 = (TextView) findViewById(R.id.sourceuri2);
btnProcessing = (Button) findViewById(R.id.processing);
imageResult = (ImageView) findViewById(R.id.result);
/*
SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.businnes);
Picture picture = svg.getPicture();
Drawable drawable = svg.createPictureDrawable();
imageResult.setImageDrawable(drawable);*/
btnLoadImage1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}
});
btnLoadImage2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE2);
}
});
btnProcessing.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (source1 != null && source2 != null) {
Bitmap processedBitmap = ProcessingBitmap(blendmode);
blendmode++;
if(blendmode>7)
blendmode=1;
if (processedBitmap != null) {
imageResult.setImageBitmap(processedBitmap);
/*Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_LONG).show();*/
} else {
Toast.makeText(getApplicationContext(),
"Something wrong in processing!",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(),
"Select both image!", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source1 = data.getData();
textSource1.setText(source1.toString());
break;
case RQS_IMAGE2:
source2 = data.getData();
textSource2.setText(source2.toString());
break;
}
}
}
#SuppressLint("NewApi")
private Bitmap ProcessingBitmap(int value) {
Bitmap bm1 = null;
Bitmap bm2 = null;
Bitmap newBitmap = null;
try {
bm1 = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(source1));
bm2 = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(source2));
int w;
if (bm1.getWidth() >= bm2.getWidth()) {
w = bm1.getWidth();
} else {
w = bm2.getWidth();
}
int h;
if (bm1.getHeight() >= bm2.getHeight()) {
h = bm1.getHeight();
} else {
h = bm2.getHeight();
}
Config config = bm1.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(w, h, config);
Canvas newCanvas = new Canvas(newBitmap);
newCanvas.drawBitmap(bm1, 0, 0, null);
Paint paint = new Paint();
switch (value) {
case Key.KEYS_BLEND_DARKEN:
Print_Toast("BLEND_DARKEN");
paint.setXfermode(new PorterDuffXfermode(Mode.DARKEN));
break;
case Key.KEYS_BLEND_MULTIPLY:
Print_Toast("BLEND_MULTIPLY");
paint.setXfermode(new PorterDuffXfermode(Mode.MULTIPLY));
break;
case Key.KEYS_BLEND_ADD:
Print_Toast("BLEND_ADD");
paint.setXfermode(new PorterDuffXfermode(Mode.ADD));
break;
case Key.KEYS_BLEND_DESOLVE:
Print_Toast("BLEND_DESOLVE");
paint.setXfermode(new PorterDuffXfermode(Mode.DST));
break;
case Key.KEYS_BLEND_DESOLVE_LIGHTEN:
Print_Toast("BLEND_LIGHTEN");
paint.setXfermode(new PorterDuffXfermode(Mode.LIGHTEN));
break;
case Key.KEYS_BLEND_DESOLVE_OVERLAY:
Print_Toast("BLEND_OVERLAY");
paint.setXfermode(new PorterDuffXfermode(Mode.OVERLAY));
break;
case Key.KEYS_BLEND_DESOLVE_SCREEN:
Print_Toast("BLEND_SCREEN");
paint.setXfermode(new PorterDuffXfermode(Mode.SCREEN));
break;
default:
break;
}
paint.setShader(new BitmapShader(bm2, TileMode.CLAMP, TileMode.CLAMP));
/*paint.setAlpha(128);
paint.setDither(true);
paint.setAntiAlias(true);*/
//paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));
newCanvas.drawRect(0, 0, bm2.getWidth(), bm2.getHeight(), paint);
//newCanvas.drawBitmap(bm2, 0, 0, paint);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newBitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void printlog(String tag,String value){
Log.d(tag, value);
}
void Print_Toast(String value){
Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
}
}
Here is Key class
public class Key {
final public static int KEYS_BLEND_DARKEN=1;
final public static int KEYS_BLEND_MULTIPLY=2;;
public static final int KEYS_BLEND_ADD = 3;
public static final int KEYS_BLEND_DESOLVE = 4;
public static final int KEYS_BLEND_DESOLVE_LIGHTEN = 5;
public static final int KEYS_BLEND_DESOLVE_OVERLAY = 6;
public static final int KEYS_BLEND_DESOLVE_SCREEN = 7;
}
xml file is activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/loadimage1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Load Image1" />
<TextView
android:id="#+id/sourceuri1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/loadimage1"
android:layout_below="#+id/loadimage1"
android:layout_marginLeft="62dp"
android:text="TextView" />
<Button
android:id="#+id/loadimage2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/loadimage1"
android:layout_below="#+id/sourceuri1"
android:text="Load Image2" />
<TextView
android:id="#+id/sourceuri2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/sourceuri1"
android:layout_below="#+id/loadimage2"
android:text="TextView" />
<Button
android:id="#+id/processing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/loadimage2"
android:layout_alignRight="#+id/loadimage2"
android:layout_below="#+id/sourceuri2"
android:text="Processing" />
<ImageView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/processing"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>

Related

CameraX - I/zygote: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>

I am developing a simple app based on the CameraX Jetpack support library through the provided getting started guide and a GitHub repo. Getting the error
I/zygote: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>:
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;
when I set the layout of the sample activity (CameraActivity). Tested the sample code on both the virtual and real devices on API level 26. The version of the CameraX library is 1.0.0-alpha03 which is the latest available version.
Here is the code of my layout:
<TextureView
android:id="#+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/btnCapture"
android:layout_width="72dp"
android:layout_height="72dp"
android:scaleType="fitCenter"
android:layout_margin="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#drawable/ic_camera_accent"
android:background="?selectableItemBackgroundBorderless" />
Here is the code of my activity:
public class CameraActivity extends AppCompatActivity {
private TextureView textureView;
private ImageButton btnCapture;
private int REQUEST_CODE_CAMERA_WRITE_EXT = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera); // this line throws the error
initComponents();
checkPermissions();
}
private void initComponents() {
textureView = findViewById(R.id.textureView);
btnCapture = findViewById(R.id.btnCapture);
}
private void checkPermissions() {
final String permissionCamera = Manifest.permission.CAMERA;
final String permissionWriteExtStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE;
boolean isPermissionGranted = PermissionUtil.checkForPermission(this, permissionCamera);
if (!isPermissionGranted) {
boolean rationale = ActivityCompat.shouldShowRequestPermissionRationale(
CameraActivity.this, permissionCamera);
if (rationale) {
AlertDialog.Builder builder = new AlertDialog.Builder(CameraActivity.this);
builder.setTitle("Camera Permission");
builder.setMessage("In order to take the photo of your vein, you need to grant camera permission.");
builder.setIcon(R.drawable.ic_info_accent);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(CameraActivity.this, new String[]{permissionCamera, permissionWriteExtStorage}, REQUEST_CODE_CAMERA_WRITE_EXT);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else
ActivityCompat.requestPermissions(CameraActivity.this, new String[]{permissionCamera, permissionWriteExtStorage}, REQUEST_CODE_CAMERA_WRITE_EXT);
} else
startCamera();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_CAMERA_WRITE_EXT) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
startCamera();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void startCamera() {
CameraX.unbindAll();
int aspRatioW = textureView.getWidth(); //get width of screen
int aspRatioH = textureView.getHeight(); //get height
Rational asp = new Rational(aspRatioW, aspRatioH); //aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //size of the screen
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview preview = new Preview(pConfig); //lets build it
preview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//to update the surface texture we have to destroy it first then re-add it
#Override
public void onUpdated(Preview.PreviewOutput output) {
ViewGroup parent = (ViewGroup) textureView.getParent();
parent.removeView(textureView);
parent.addView(textureView, 0);
textureView.setSurfaceTexture(output.getSurfaceTexture());
updateTransform();
}
});
ImageCaptureConfig imgCConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
.setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
final ImageCapture imgCap = new ImageCapture(imgCConfig);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContextWrapper contextWrapper = new ContextWrapper(CameraActivity.this);
String path = contextWrapper.getFilesDir().getPath();
File file = new File(path + "/" + System.currentTimeMillis() + ".jpg");
imgCap.takePicture(file, new ImageCapture.OnImageSavedListener() {
#Override
public void onImageSaved(#NonNull File file) {
String msg = "Photo capture succeeded: " + file.getAbsolutePath();
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onError(#NonNull ImageCapture.UseCaseError useCaseError, #NonNull String message, #Nullable Throwable cause) {
String msg = "Photo capture failed: " + message;
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
if (cause != null) {
cause.printStackTrace();
}
}
});
}
});
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
ImageAnalysis analysis = new ImageAnalysis(imgAConfig);
analysis.setAnalyzer(
new ImageAnalysis.Analyzer() {
#Override
public void analyze(ImageProxy image, int rotationDegrees) {
//y'all can add code to analyse stuff here idek go wild.
}
});
//bind to lifecycle:
CameraX.bindToLifecycle((LifecycleOwner) this, analysis, imgCap, preview);
}
private void updateTransform() {
//compensates the changes in orientation for the viewfinder, bc the rest of the layout stays in portrait mode.
//methinks :thonk:
Matrix mx = new Matrix();
float w = textureView.getMeasuredWidth();
float h = textureView.getMeasuredHeight();
float cX = w / 2f; //calc centre of the viewfinder
float cY = h / 2f;
int rotationDgr;
int rotation = (int) textureView.getRotation(); //cast to int bc switches don't like floats
switch (rotation) { //correct output to account for display rotation
case Surface.ROTATION_0:
rotationDgr = 0;
break;
case Surface.ROTATION_90:
rotationDgr = 90;
break;
case Surface.ROTATION_180:
rotationDgr = 180;
break;
case Surface.ROTATION_270:
rotationDgr = 270;
break;
default:
return;
}
mx.postRotate((float) rotationDgr, cX, cY);
textureView.setTransform(mx); //apply transformations to textureview
}
}
Solved the issue for me.
build.gradle (app level)
//Adding dependency
implementation 'androidx.core:core:1.5.0-alpha04'

How to set image in imageview in adapter and getting uri in another activity?

(This is my adapter)(I want to display image in the imageview ivReceiverSign The image url is saved in signature class displayed below.)
DbAdapter
package com.example.dhruvitpatel.deviceregistration.adapter;
public class DbAdapter extends RecyclerView.Adapter<DbAdapter.ViewHolder> {
List<RegisterDevice> registerDevice;
Context mCtx;
String rowAdded;
public DbAdapter(List<RegisterDevice> registerDevice, Context mCtx) {
this.registerDevice = registerDevice;
this.mCtx = mCtx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.rowlayout, parent, false);
return new DbAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final DbAdapter.ViewHolder holder, final int position) {
final RegisterDevice registerdetails = registerDevice.get(position);
holder.registerDate.setText("Register Date: " + registerdetails.getOutDate() + registerdetails.getOutTime());
holder.EmpName.setText("Name: " + registerdetails.getEmpName());
holder.Cable.setText("Cable: " + registerdetails.getCableName());
holder.Device.setText("Device: " + registerdetails.getDevName());
holder.ivUserSign.setImageURI(Uri.parse(registerdetails.getUserSign()));
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mCtx);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage("Are you sure, You want to submit Device?");
alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
holder.checkbox.setChecked(false);
final Dialog submitDialog = new Dialog(mCtx);
submitDialog.setContentView(R.layout.submitdevicedialog);
submitDialog.show();
TextView tvSubmittedTo = (TextView) submitDialog.findViewById(R.id.tvSubmittedTo);
final EditText etReceivedBy = (EditText) submitDialog.findViewById(R.id.etReceivedBy);
Button btnSubmitDevice = (Button) submitDialog.findViewById(R.id.btnSubmitDevice);
Button btnCancelSubmit = (Button) submitDialog.findViewById(R.id.btnCancelSubmit);
btnSubmitDevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String receiver = etReceivedBy.getText().toString();
if (receiver.isEmpty()) {
Toast.makeText(mCtx, "Enter receiver Name", Toast.LENGTH_SHORT).show();
} else {
Calendar cal = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("dd / MM / yyyy ");
String submitDate = mdformat.format(cal.getTime());
DateFormat date = new SimpleDateFormat("hh:mm:ss a");
String submitTime = date.format(cal);
long id = registerdetails.getPid();
DataSource.updateSubmittedDevice(submitDate, submitTime, receiver, id);
Intent in = new Intent(mCtx, Signature.class);
in.putExtra("Id", String.valueOf(id));
Log.d("ID:", String.valueOf(id));
mCtx.startActivity(in);
String recSign = registerdetails.getReceiverSign();
registerdetails.setSubmitDate(submitDate);
registerdetails.setSubmitTime(submitTime);
registerdetails.setReciever(receiver);
registerdetails.setDeviceSubmitted(true);
registerdetails.setReceiverSign(recSign);
registerDevice.remove(position);
registerDevice.add(position, registerdetails);
notifyItemChanged(position);
holder.checkbox.setVisibility(View.GONE);
if (registerdetails.getDeviceSubmitted().equals(Boolean.TRUE)) {
String temp = registerdetails.getDevName();
String temp1 = registerdetails.getCableName();
DataSource.updateDataonLoad(temp, temp1);
}
}
}
});
btnCancelSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitDialog.dismiss();
}
});
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
holder.checkbox.setChecked(false);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
if (registerdetails.getDeviceSubmitted().equals(Boolean.TRUE)) {
// if(!registerdetails.getReceiverSign().isEmpty()){
// holder.ivReceiverSign.setImageURI(Uri.parse(registerdetails.getReceiverSign()));
// }
holder.card_view.setCardBackgroundColor(Color.GRAY);
holder.checkbox.setVisibility(View.GONE);
holder.tvSubmit.setVisibility(View.VISIBLE);
holder.tvReceiver.setVisibility(View.VISIBLE);
holder.submitDate.setVisibility(View.VISIBLE);
holder.tvReceiver.setText(registerdetails.getReciever());
holder.submitDate.setText("Submit Date: " + registerdetails.getSubmitDate() + registerdetails.getSubmitTime());
} else {
holder.checkbox.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return registerDevice.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.registerDate)
TextView registerDate;
#BindView(R.id.EmpName)
TextView EmpName;
#BindView(R.id.Device)
TextView Device;
#BindView(R.id.Cable)
TextView Cable;
#BindView(R.id.checkbox)
CheckBox checkbox;
#BindView(R.id.tvReceiver)
TextView tvReceiver;
#BindView(R.id.tvSubmit)
TextView tvSubmit;
#BindView(R.id.submitDate)
TextView submitDate;
#BindView(R.id.card_view)
CardView card_view;
#BindView(R.id.ivUserSign)
ImageView ivUserSign;
#BindView(R.id.ivReceiverSign)
ImageView ivReceiverSign;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
Register class
(Here I register devices which are loaded in spinner from database.After selecting items i will click on register button and all details will be notified to adapter )
Register Page
package com.example.dhruvitpatel.deviceregistration.activity;
public class TakeDevice extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.spnName)
Spinner spnName;
#BindView(R.id.spnDevice)
Spinner spnDevice;
#BindView(R.id.spnCable)
Spinner spnCable;
#BindView(R.id.btnRegister)
Button btnRegister;
#BindView(R.id.col)
CoordinatorLayout col;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_device);
ButterKnife.bind(this);
initView();
setListener();
loadempData();
loaddevdata();
loadcabledata();
}
private void initView() {
spnName.requestFocus();
}
private void setListener() {
btnRegister.setOnClickListener(this);
}
private void loadempData() {
final List<EmployeeDetails> values = DataSource.getempData();
adapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, values);
adapter.add("Select your name");
spnName.setAdapter(adapter);
spnName.setSelection(adapter.getCount()-1);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnRegister:
empName = spnName.getSelectedItem().toString();
devName = spnDevice.getSelectedItem().toString();
Cable = spnCable.getSelectedItem().toString();
if (empName.isEmpty() && devName.isEmpty() && Cable.isEmpty()) {
Snackbar snack = Snackbar.make(col, "Select details", Snackbar.LENGTH_SHORT);
snack.show();
}
if (Cable.equals("Select cable")){
Snackbar snack = Snackbar.make(col, "Select cable", Snackbar.LENGTH_SHORT);
snack.show();
}
else if(empName.equals("Select your name")){
Snackbar snack = Snackbar.make(col, "Select name", Snackbar.LENGTH_SHORT);
snack.show();
}
else if (devName.equals("Select device")){
Snackbar snack = Snackbar.make(col, "Select device", Snackbar.LENGTH_SHORT);
snack.show();
}
else if (empName.isEmpty()) {
Snackbar snack = Snackbar.make(col, "Select name", Snackbar.LENGTH_SHORT);
snack.show();
} else if (devName.isEmpty() && Cable.isEmpty()) {
Snackbar snack = Snackbar.make(col, "Select device or cable", Snackbar.LENGTH_SHORT);
snack.show();
} else {
Calendar cal = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("dd / MM / yyyy ");
String strDate = mdformat.format(cal.getTime());
DateFormat date = new SimpleDateFormat("hh:mm:ss a");
String strTime = date.format(cal);
deviceTaken = new RegisterDevice();
deviceTaken.setOutDate(strDate);
deviceTaken.setOutTime(strTime);
deviceTaken.setEmpName(empName);
deviceTaken.setDevName(devName);
deviceTaken.setCableName(Cable);
DataSource.insertDetails(deviceTaken);
long regDevList = deviceTaken.getPid();
DataSource.updateBoolean(deviceIdDisp, cableIdDisp);
Intent intent = new Intent(this, Signature.class);
intent.putExtra("RowId", String.valueOf(regDevList));
startActivity(intent);
}
break;
}
(I get my image url in this class.i use this to get signature and i have four buttons in it)
Signature class
package com.example.dhruvitpatel.deviceregistration.activity;
public class Signature extends AppCompatActivity implements View.OnClickListener {
#BindView(R.id.btnSave)
Button btnSave;
#BindView(R.id.signLayout)
LinearLayout signLayout;
#BindView(R.id.btnRedo)
Button btnRedo;
#BindView(R.id.btnUndo)
Button btnUndo;
#BindView(R.id.btnClear)
Button btnClear;
#BindView(R.id.cordlayout)
CoordinatorLayout cordlayout;
private static final int GALLERY_REQUEST = 111;
public static String tempDir;
private String uniqueId;
File mypath;
public String current = null;
View mView;
signature mSignature;
Uri signImage;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private Path mPath;
long id;
public boolean cc = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signature);
ButterKnife.bind(this);
initView();
setListener();
}
private void initView() {
btnSave.setEnabled(false);
tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
uniqueId = getTodayDate() + "_" + getCurrentTime() + "_" + Math.random();
current = uniqueId + ".jpeg";
mypath = new File(directory, current);
Log.d("path:", String.valueOf(mypath));
mSignature = new signature(this, null);
mSignature.setBackgroundColor(Color.BLACK);
signLayout.addView(mSignature, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mView = signLayout;
btnRedo.setEnabled(false);
}
private String getTodayDate() {
final Calendar c = Calendar.getInstance();
int todaysDate = (c.get(Calendar.YEAR) * 10000) +
((c.get(Calendar.MONTH) + 1) * 100) +
(c.get(Calendar.DAY_OF_MONTH));
Log.w("DATE:", String.valueOf(todaysDate));
return (String.valueOf(todaysDate));
}
private String getCurrentTime() {
final Calendar c = Calendar.getInstance();
int currentTime = (c.get(Calendar.HOUR_OF_DAY) * 10000) +
(c.get(Calendar.MINUTE) * 100) +
(c.get(Calendar.SECOND));
Log.w("TIME:", String.valueOf(currentTime));
return (String.valueOf(currentTime));
}
private void setListener() {
btnSave.setOnClickListener(this);
btnClear.setOnClickListener(this);
btnUndo.setOnClickListener(this);
btnRedo.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSave:
// Log.v("log_tag", "Panel Saved");
if (!CommonUtils.checkPermission(Signature.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
CommonUtils.requestPermission(Signature.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, GALLERY_REQUEST);
} else {
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
}
case R.id.btnClear:
mSignature.clear();
// mPath=new Path();
// mSignature.invalidate();
btnSave.setEnabled(false);
break;
case R.id.btnUndo:
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
mSignature.invalidate();
btnRedo.setEnabled(true);
}
break;
case R.id.btnRedo:
if (undonePaths.size() > 0) {
paths.add(undonePaths.remove(undonePaths.size() - 1));
btnRedo.setEnabled(true);
mSignature.invalidate();
}
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case GALLERY_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mView.setDrawingCacheEnabled(true);
mSignature.save(mView);
}
break;
}
}
public class signature extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
Context context;
private Paint mPaint;
private float mX, mY;
private static final float TOLERANCE = 5;
public signature(Context c, AttributeSet attrs) {
super(c, attrs);
context = c;
// we set a new Path
mPath = new Path();
// and we set a new Paint with the desired attributes
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeWidth(15f);
}
public void save(View v) {
if (mBitmap == null) {
mBitmap = Bitmap.createBitmap(signLayout.getWidth(), signLayout.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
if (paths.isEmpty() && undonePaths.isEmpty()) {
Snackbar snackbar = Snackbar.make(cordlayout, "Enter your signature", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
try {
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 0, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
String url = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "title:" + current, null);
Log.v("log_tag", "url: " + url);
String rowId = getIntent().getStringExtra("RowId");
if (rowId != null) {
id = Long.parseLong(rowId);
Log.d("id:", String.valueOf(id));
signImage = Uri.fromFile(mypath);
Log.d("uri:", String.valueOf(signImage));
DataSource.updateSign(signImage, id);
}
Intent intent = new Intent(Signature.this, MainActivity.class);
intent.putExtra("RowId", String.valueOf(id));
setResult(1, intent);
startActivity(intent);
Intent in = getIntent();
String submitId = in.getStringExtra("Id");
if (submitId != null) {
long subId = Long.parseLong(submitId);
Uri recsignImage = Uri.fromFile(mypath);
DataSource.updateReceiversign(recsignImage, subId);
}
Intent intent1 = new Intent(Signature.this, MainActivity.class);
intent1.putExtra("ID", String.valueOf(submitId));
setResult(2, intent1);
startActivity(intent1);
//In case you want to delete the file
//boolean deleted = mypath.delete();
//Log.v("log_tag","deleted: " + mypath.toString() + deleted);
//If you want to convert the image to string use base64 converter
} catch (Exception e) {
Log.v("log_tag", e.toString());
}
}
}
// override onSizeChanged
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// your Canvas will draw onto the defined Bitmap
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
mCanvas = new Canvas(mBitmap);
}
// override onDraw
#Override
protected void onDraw(Canvas canvas) {
if (cc) {
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRect(0, 0, 0, 0, clearPaint);
cc = false;
}
// // draw the mPath with the mPaint on the canvas when onDraw
// canvas.drawPath(mPath, mPaint);
else {
for (Path p : paths) {
canvas.drawPath(p, mPaint);
}
canvas.drawPath(mPath, mPaint);
}
}
// when ACTION_DOWN start touch according to the x,y values
private void startTouch(float x, float y) {
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
// when ACTION_MOVE move touch according to the x,y values
private void moveTouch(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOLERANCE || dy >= TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
// when ACTION_UP stop touch
private void upTouch() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
paths.add(mPath);
mPath = new Path();
}
//override the onTouchEvent
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnSave.setEnabled(true);
startTouch(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
btnSave.setEnabled(true);
moveTouch(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
btnSave.setEnabled(true);
upTouch();
invalidate();
break;
}
return true;
}
public void clear() {
paths.clear();
undonePaths.clear();
cc = true;
invalidate();
}
}
}
}
Wat to do if i want to set image in imageview of my adapter wid id ivReceiverSign?
Create interface
public interface ImageUrl{
void getImageUrl(String imageUrl)
}
implement this interface in adapter and send the url through another class using imageUrl.getImageUrl(imageUrl).
or Use EventBus library.
Reference to Eventbus : Green robot Event bus

My imageView doesn`t work

I am working in android studio and I'm triyng to import a photo from a directory from my phone and put it on a ImageView.
In my first activity, I tried to save the photo using the camera and I tried to save the URI from the photo. That's working.
IIn another activity, I tried to import that URI but my ImageView doesn't change. The compiler saw location from the photo, so I think is working, but the imageview can't import the photo...
Could you help me?
public class PictureConfirmation extends Activity {
ImageButton use;
ImageButton retake;
TextView usetxt;
TextView retaketxt;
ImageView pictaken;
String pic;
File picfile;
Matrix matrix;
String pic2;
Bitmap bitmap;
public Bitmap rotatedbitmap;
ImageButton scan;
ImageView teeth;
TextView scantxt;
public String colorRGB;
TextView canceltxt;
Uri ImgUri;
public float ax;
public float ay;
int Rc, Gc, Bc;
public int checkcamera=0;
TextView colortxt;
#Override
protected void onCreate(Bundle savedInstance) {
final Typeface bariol_font = Typeface.createFromAsset(getAssets(), "Bariol_Bold.otf");
//going full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstance);
setContentView(R.layout.picture_confirmation);
final String PREF_NAME = "Link";
String defaultValue = "default string";
Preferences prefs = Preferences.userNodeForPackage(com.example.newrosoft1.dentafy.MainMenuActivity.class);
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
//pic = new MainMenuActivity().getpath();
pic2=propertyValue;
pic=propertyValue;
Log.d("valoare este %#" ,pic.toString());
//bitmap =BitmapFactory.decodeFile(pic);
// Uri imgUri=Uri.parse(pic);
//.setImageURI(imgUri);
use = (ImageButton) findViewById(R.id.usebtnid);
retake = (ImageButton) findViewById(R.id.retakebtnid);
retaketxt = (TextView) findViewById(R.id.retaketxtid);
retaketxt.setTypeface(bariol_font);
usetxt = (TextView) findViewById(R.id.usetextid);
usetxt.setTypeface(bariol_font);
pictaken = (ImageView) findViewById(R.id.pictakenid);
//pictaken.setImageBitmap(bitmap);
Uri imgUri=Uri.parse(pic);
pictaken.setImageURI(null);
pictaken.setImageURI(imgUri);
try {
pictaken.setImageDrawable(Drawable.createFromStream(
getContentResolver().openInputStream(imgUri),
null));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final AlertDialog.Builder alertdialog = new AlertDialog.Builder(this);
alertdialog.setTitle("Confirmation");
alertdialog.setMessage("Are you sure this is the correct picture?\nPlease note that you have a limited number of scans");
alertdialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setContentView(R.layout.processing);
Runnable r = new Runnable() {
#Override
public void run() {
setContentView(R.layout.scan_teeth_finished);
TextView done = (TextView) findViewById(R.id.donetxtid);
done.setTypeface(bariol_font);
colortxt = (TextView) findViewById(R.id.teethcolortxtid);
colortxt.setTypeface(bariol_font);
teeth = (ImageView) findViewById(R.id.teethimg);
//teeth.setImageBitmap(bitmap);
Uri imgUri=Uri.parse(pic);
teeth.setImageURI(null);
teeth.setImageURI(imgUri);
try {
teeth.setImageDrawable(Drawable.createFromStream(
getContentResolver().openInputStream(imgUri),
null));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
teeth.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[]{eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView) view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int) eventXY[0]);
int y = Integer.valueOf((int) eventXY[1]);
Drawable imgDrawable = teeth.getDrawable();
bitmap = ((BitmapDrawable) imgDrawable).getBitmap();
//Limit x, y range within bitmap
if (x < 0) {
x = 0;
} else if (x > (bitmap.getWidth() - 1)) {
x = bitmap.getWidth() - 1;
ax = x;
}
if (y < 0) {
y = 0;
} else if (y > (bitmap.getHeight() - 1)) {
y = bitmap.getHeight() - 1;
ay = y;
}
int touchedRGB = bitmap.getPixel(x, y);
int[] areapixels = new int[bitmap.getWidth() * bitmap.getHeight()];
int touchedAreaRGB;
try {
bitmap.getPixels(areapixels, 0, bitmap.getWidth(), x, y, 25, 25); //pixel area to scan
} catch (ArrayIndexOutOfBoundsException arrayindexoutofbounds) {
Toast.makeText(getApplicationContext(), "index out of bounds exception",
Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException illegalargumentexception) {
}
int total = 0;
for (int i = 0; i < areapixels.length; i++) {
if (areapixels[i] != 0)
{
Rc += (areapixels[i] >> 16) & 0xff;
Gc += (areapixels[i] >> 8) & 0xff;
Bc += (areapixels[i]) & 0xff;
total++;
}
}
if (Rc != 0 || Gc != 0 || Bc != 0) {
Rc /= total;
Gc /= total;
Bc /= total;
}
touchedAreaRGB = 0xff000000 | (Rc << 16) | (Gc << 8) | Bc;
int avrgColor = (Gc - Bc) * 10 / 2;
int yellow = 12229738;
int white = 16777215;
int value = ((touchedRGB - yellow) * 100) / (white - yellow);
int value2 = ((touchedRGB - yellow) * 10) / (white - yellow);
Log.d("value: ", "asd100 " + value);
Log.d("value: ", "asd10 " + value2);
colorRGB = "could not find color code, tap again " + value2;
if (value2 < 32)
colorRGB = "Selected tooth color is:A1";
switch (value2) {
case -33:
colorRGB = "Selected tooth color is:A1 ";
break;
case -32:
colorRGB = "Selected tooth color is:B1";
break;
case -35:
colorRGB = "Selected tooth color is:A2 ";
break;
case -36:
colorRGB = "Selected tooth color is:A3 ";
break;
case -34:
colorRGB = "Selected tooth color is:B2 ";
break;
case -38:
colorRGB = "Selected tooth color is:D2 ";
break;
case -37:
colorRGB = "Selected tooth color is:D3 ";
break;
case -40:
colorRGB = "Selected tooth color is:D4 ";
break;
}
colortxt.setText(colorRGB);
if (Gc < Bc || Gc < 100) {
// Toast.makeText(getApplicationContext(), "Could not get color code, make sure you tap on tooth", Toast.LENGTH_SHORT).show();
}
//colorRGB.setText("Selected tooth color is:C1" + value2);
Rc = 0;
Bc = 0;
Gc = 0;
total = 0;
return true;
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PictureConfirmation.this, MainMenuActivity.class));
}
});
}
};
Handler h = new Handler();
h.postDelayed(r, 2000);
}
});
alertdialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do nothing
}
});
alertdialog.create();
//pictaken.setImageBitmap(bitmap);
//Uri imgUri=Uri.parse(pic);
pictaken.setImageURI(null);
pictaken.setImageURI(imgUri);
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// startActivity(new Intent(PictureConfirmation.this, CameraMainActivity.class));
}
});
use.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.scan_teeth_start);
scan = (ImageButton) findViewById(R.id.scanbtnid);
teeth = (ImageView) findViewById(R.id.teethimageid);
scantxt = (TextView) findViewById(R.id.startscantxtid);
scantxt.setTypeface(bariol_font);
canceltxt = (TextView) findViewById(R.id.canceltxtid);
canceltxt.setTypeface(bariol_font);
//teeth.setImageBitmap(bitmap);
Uri imgUri2=Uri.parse(pic);
teeth.setImageURI(null);
teeth.setImageURI(imgUri2);
canceltxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PictureConfirmation.this, MainMenuActivity.class));
}
});
// matrix.postRotate(270);
// bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // rotating bitmap
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertdialog.show();
}
});
}
});
}
}
06-24 15:08:30.868 13184-13184/com.example.newrosoft1.dentafy D/valoare este %#: file:///file%3A/storage/emulated/0/Android/data/com.example.newrosoft1.dentafy/files/Pictures/JPEG_20160624_150829_558130986.jpg
06-24 15:08:30.868 13184-13184/com.example.newrosoft1.dentafy D/valoare 2 este %#: file:///file%3A/storage/emulated/0/Android/data/com.example.newrosoft1.dentafy/files/Pictures/JPEG_20160624_150829_558130986.jpg
06-24 15:08:30.948 13184-13184/com.example.newrosoft1.dentafy D/valoare este %#: file:///file%3A/storage/emulated/0/Android/data/com.example.newrosoft1.dentafy/files/Pictures/JPEG_20160624_150829_558130986.jpg
06-24 15:08:30.948 13184-13184/com.example.newrosoft1.dentafy D/valoare 2 este %#: file:///file%3A/storage/emulated/0/Android/data/com.example.newrosoft1.dentafy/files/Pictures/JPEG_20160624_150829_558130986.jpg
AND THE LOGCAT ERROR:
06-24 15:08:34.712 13184-13184/com.example.newrosoft1.dentafy E/ViewRootImpl: sendUserActionEvent() mView == null
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#mipmap/background2"
android:paddingTop="97dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="0dp">
<ImageView
android:layout_width="fill_parent"
android:layout_height="250dp"
android:id="#+id/pictakenid"
android:layout_alignParentBottom="true"
android:scaleType="centerCrop"
android:layout_alignParentTop="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/usebtnid"
android:src="#drawable/use"
android:layout_marginBottom="46dp"
android:background="#android:color/transparent"
android:layout_marginRight="15dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginStart="52dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/retakebtnid"
android:src="#drawable/retake2"
android:background="#android:color/transparent"
android:layout_alignTop="#+id/usebtnid"
android:layout_alignParentEnd="true"
android:layout_marginEnd="31dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="USE"
android:id="#+id/usetextid"
android:textSize="23dp"
android:textColor="#ffffff"
android:textAlignment="center"
android:contextClickable="false"
android:layout_marginBottom="44dp"
android:layout_alignBottom="#+id/usebtnid"
android:layout_alignStart="#+id/usebtnid"
android:layout_marginStart="37dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RETAKE"
android:id="#+id/retaketxtid"
android:textSize="23dp"
android:textColor="#ffffff"
android:layout_marginRight="18dp"
android:layout_alignTop="#+id/usetextid"
android:layout_alignEnd="#+id/retakebtnid" />
</RelativeLayout>
</LinearLayout>
here i create the file:
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Uri auxPath=getU(image);
Preferences prefs = Preferences.userNodeForPackage(com.example.newrosoft1.dentafy.MainMenuActivity.class);
// Preference key name
final String PREF_NAME = "Link";
// Set the value of the preference
String newValue = auxPath.toString();
prefs.put(PREF_NAME, newValue);
// Get the value of the preference;
// default value is returned if the preference does not exist
return image;
}
public Uri getU(File u){
String x;
x=getpath();
File f = new File (x);
Uri imageUri = Uri.fromFile(f);
return imageUri;
}
public String getpath(){
return mCurrentPhotoPath;
}
}

Android code to record a video using remote IP camera which is accessed by using a url

Here are some links which tell about video recording:
How can I capture a video recording on Android?
https://github.com/churnlabs/android-ffmpeg-sample
and there are also many links which tell about video recording but got no any clue how to use the remote IP camera to record video.
By using different samples on stackoverflow I become able to take picture and save on sdcard but couldn't record video.
If any one has any idea or code along with required files I will be thankful.
For example the url I am using where the IP camera is available is given below:
http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg/video.cgi?resolution=800x600&amp%3bdummy=1333689998337
Here is the layout code:
<RelativeLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/logo"
android:layout_alignParentTop="true"
android:layout_weight="1" >
<ImageButton
android:id="#+id/btnCam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
<ImageButton
android:id="#+id/btnVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/camera_icon" >
</ImageButton>
</RelativeLayout>
<LinearLayout
android:id="#+id/LinearLayout03"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/LinearLayout01"
android:layout_below="#+id/LinearLayout02"
android:layout_weight="1" >
<RelativeLayout
android:id="#+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#ffffff" >
<view
android:id="#+id/mv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
class="com.apps.GrahamConst.MjpegView" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:background="#drawable/navbar" >
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/previous" >
</ImageButton>
<ImageButton
android:id="#+id/btnMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/main" >
</ImageButton>
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:background="#null"
android:src="#drawable/next" >
</ImageButton>
</LinearLayout>
</RelativeLayout>
Here is my Activity
public class CameraDetails2 extends Activity implements OnClickListener {
private MediaScannerConnection m_pScanner;
String drawable = null;
private MjpegView mv;
private ProgressDialog dialog;
private HashMap<String, String> item;
private int id = -1;
private WindowManager winMan;
boolean recording = false;
MediaRecorder recorder;
int bytearraysize = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
winMan = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
if (winMan != null) {
int orientation = winMan.getDefaultDisplay().getOrientation();
if (orientation == 0) {
// Portrait
setContentView(R.layout.cameradetails);
} else if (orientation == 1) {
// Landscape
setContentView(R.layout.cameradetailsl);
}
}
Bundle b = getIntent().getExtras();
ImageButton b1 = (ImageButton) findViewById(R.id.btnNext);
b1.setOnClickListener(this);
ImageButton b2 = (ImageButton) findViewById(R.id.btnMain);
b2.setOnClickListener(this);
ImageButton b3 = (ImageButton) findViewById(R.id.btnPrevious);
b3.setOnClickListener(this);
ImageButton b4 = (ImageButton) findViewById(R.id.btnCam);
b4.setOnClickListener(this);
ImageButton b5 = (ImageButton) findViewById(R.id.btnVideo);
b5.setOnClickListener(this);
id = Integer.valueOf(b.get("id").toString());
item = listarrayadapter.cameraList.get(Integer.valueOf(id));
mv = (MjpegView) findViewById(R.id.mv);
try {
getVal(item.get("cameraLink"));
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&amp%3bdummy=1333689998337");
} catch (Exception e) {
e.printStackTrace();
mv.setBackgroundResource(R.drawable.offline);
}
}
#Override
protected void onResume() {
// if(recording)
// {
// getVal("http://trackfield.webcam.oregonstate.edu/axis-cgi/mjpg
/video.cgi?resolution=800x600&amp%3bdummy=1333689998337");
// }
super.onResume();
}
public void onPause() {
super.onPause();
dialog.dismiss();
mv.stopPlayback();
}
private void getVal(final String url) {
Log.i("URL===", url);
updateButtons();
dialog = ProgressDialog.show(this, null, null, true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = null;
checkUpdate = new Thread() {
public void run() {
mv.setSource(MjpegInputStream.read(url));
mv.setDisplayMode(MjpegView.SIZE_FULLSCREEN);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int btn = v.getId();
if (btn == R.id.btnMain) {
Intent intent = new Intent();
intent.setClass(CameraDetails2.this, CamerasList.class);
startActivity(intent);
finish();
}
if (btn == R.id.btnNext) {
id += 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnPrevious) {
id -= 1;
Intent myintent = new Intent(CameraDetails2.this,
CameraDetails.class);
myintent.putExtra("id", id);
startActivity(myintent);
finish();
}
if (btn == R.id.btnCam) {
if (mv != null) {
Date dt = new Date();
int years = dt.getYear();
int month = dt.getMonth();
int day = dt.getDay();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
final String filename = years + "" + month + "" + day + ""
+ hours + "" + minutes + "" + seconds;
try {
Bitmap image = MjpegView.savebmp;
File SDCardRoot =
Environment.getExternalStorageDirectory();
FileOutputStream fileOutputStream = null;
fileOutputStream = new FileOutputStream(
SDCardRoot.toString() + "/" +
filename + ".jpg");
BufferedOutputStream bos = new
BufferedOutputStream(
fileOutputStream);
int quality = 95;
image.compress(CompressFormat.JPEG, quality, bos);
final String szFile = SDCardRoot.toString() + "/"
+ filename + ".jpg";
m_pScanner = new MediaScannerConnection(this,
new MediaScannerConnectionClient()
{
public void
onMediaScannerConnected() {
m_pScanner
.scanFile(szFile, null /* mimeType */);
}
public void
onScanCompleted(String path, Uri uri) {
if
(path.equals(szFile)) {
CameraDetails2.this
.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
"Image Saved.",
Toast.LENGTH_LONG)
.show();
}
});
m_pScanner.disconnect();
}
}
});
m_pScanner.connect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (btn == R.id.btnVideo) {
if (recording) {
// stop and save
recording = false;
MjpegInputStream.isrecording = false;
List<byte[]> bytelist = new ArrayList<byte[]>();
ArrayList<ByteArrayOutputStream> byteArrayStream =
MjpegInputStream.byteArrayStream;
for (int i = 0; i < byteArrayStream.size(); i++) {
byte[] templist
=byteArrayStream.get(i).toByteArray();
bytelist.add(templist);
}
for (int j = 0; j < bytelist.size(); j++) {
bytearraysize += bytelist.get(j).length;
}
byte[] totalbytes = new byte[bytearraysize];
int f = 0;
for (int j = 0; j < bytelist.size(); j++) {
for (int a = 0; a < bytelist.get(j).length; a++) {
totalbytes[f] = bytelist.get(j)[a];
f++;
}
}
Log.e("num of bytes", "" + totalbytes.length);
// Byte[] bytes = bytelist.toArray(new
//Byte[bytelist.size()]);
try {
writeToFile(totalbytes, "" +
System.currentTimeMillis());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
recording = true;
MjpegInputStream.isrecording = true;
// onResume();
// start recording
}
// recorder=new MediaRecorder();
// try {
// recorder.prepare();
// } catch (IllegalStateException e) {
// e.printStackTrace();
// finish();
// } catch (IOException e) {
// e.printStackTrace();
// finish();
// }
//
// //recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
// // recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
//
// //
// //
// // CamcorderProfile cpHigh = CamcorderProfile
// // .get(CamcorderProfile.QUALITY_HIGH);
// // recorder.setProfile(cpHigh);
// recorder.setVideoSource(mv.getId());
// recorder.setOutputFile("/sdcard/videocapture_example.mp4");
// recorder.setMaxDuration(50000); // 50 seconds
// recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
}
public void writeToFile(byte[] bytes, String videoname) throws IOException {
try {
Log.e("num of bytes to be saved", "" + bytes.length);
String path = "/sdcard/" + videoname + ".mp4";
FileOutputStream stream = new FileOutputStream(path);
stream.write(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void updateButtons() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
ImageButton btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
if (id == 0) {
btnPrevious.setEnabled(false);
} else {
btnPrevious.setEnabled(true);
}
if (id == listarrayadapter.cameraList.size() - 1) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
}
}

Show Image View from file path?

I need to show an image by using the file name only, not from the resource id.
ImageView imgView = new ImageView(this);
imgView.setBackgroundResource(R.drawable.img1);
I have the image img1 in the drawable folder. I wish to show that image from the file.
How can I do this?
Labeeb is right about why you need to set image using path if your resources are already laying inside the resource folder ,
This kind of path is needed only when your images are stored in SD-Card .
And try the below code to set Bitmap images from a file stored inside a SD-Card .
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
And include this permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I think you can use this
Bitmap bmImg = BitmapFactory.decodeFile("path of your img1");
imageView.setImageBitmap(bmImg);
You can also use:
File imgFile = new File(“filepath”);
if(imgFile.exists())
{
ImageView myImage = new ImageView(this);
myImage.setImageURI(Uri.fromFile(imgFile));
}
This does the bitmap decoding implicit for you.
All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.
Did I mention it is super easy to use:
Picasso.with(context).load(new File(...)).into(imageView);
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(myBitmap);
}
From the official site: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
ImageView image = (ImageView) findViewById(R.id.imagePreview);
try {
image.setImageBitmap(decodeSampledBitmap(picFilename));
} catch (Exception e) {
e.printStackTrace();
}
Here the methods:
private int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Bitmap decodeSampledBitmap(String pathName,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
//I added this to have a good approximation of the screen size:
private Bitmap decodeSampledBitmap(String pathName) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
return decodeSampledBitmap(pathName, width, height);
}
How To Show Images From Folder path in Android
Very First: Make Sure You Have Add Permissions into Mainfest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
:Make a Class MyGallery
public class MyGallery extends Activity {
private GridView gridView;
private String _location;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
private AdView mAdView;
private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
public static String[] imageFileList;
TextView gallerytxt;
public static ImageAdapter imageAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mygallery);
/*if (MenuClass.mInterstitialAd.isLoaded()) {
MenuClass.mInterstitialAd.show();
}*/
gallerytxt = (TextView) findViewById(R.id.gallerytxt);
/*gallerytxt.setTextSize(20);
int[] color = {Color.YELLOW,Color.WHITE};
float[] position = {0, 1};
Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
Shader shader_gradient0 = lin_grad0;
gallerytxt.getPaint().setShader(shader_gradient0);*/
ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyGallery.this.finish();
}
});
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
gridView = (GridView) findViewById(R.id.gridView);
new MyGalleryAsy().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(MyGallery.this, ImageDetail.class);
intent.putExtra("ImgUrl", imageFileList[pos]);
//Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
if (ImageDetail.deleted) {
photo = new ArrayList<Bitmap>();
new MyGalleryAsy().execute();
ImageDetail.deleted = false;
}
}
public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
Bitmap mBitmap;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
readImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
DisplayMetrics displayMatrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
int screenWidth = displayMatrics.widthPixels / 3;
if (photo.size() > 0) {
imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
gridView.setAdapter(imageAdapter);
}
}
}
private void readImage() {
// TODO Auto-generated method stub
try {
if (isSdPresent()) {
_location = extStorageDirectory + newFolder;
} else
_location = getFilesDir() + newFolder;
File file1 = new File(_location);
if (file1.isDirectory()) { // sdCard == true
imageFileList = file1.list();
if (imageFileList != null) {
for (int i = 0; i < imageFileList.length; i++) {
try {
photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private int width;
private int mGalleryItemBackground;
public ImageAdapter(Context c) {
context = c;
}
public ImageAdapter(Context c, int width) {
context = c;
this.width = width;
}
public int getCount() {
return photo.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.galleryadapter, null);
RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);
ImageView imageView = new ImageView(context);
layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setImageBitmap(photo.get(position));
return v;
}
public void updateItemList(ArrayList<Bitmap> newItemList) {
photo = newItemList;
notifyDataSetChanged();
}
}
}
Now create its Xml Class
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize">
<TextView
android:id="#+id/gallerytxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:fontFamily="#string/font_fontFamily_medium"
android:text="My Gallery"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black"
android:textStyle="bold" />
<ImageButton
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center|bottom"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_id" />
<GridView
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/adView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/relativeLayout"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:smoothScrollbar="true"
android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]
To see the Image in Detail create a new Class ImageDetail:##
public class ImageDetail extends Activity implements OnClickListener {
public static InterstitialAd mInterstitialAd;
private ImageView mainImageView;
private LinearLayout menuTop;
private TableLayout menuBottom;
private Boolean onOff = true;
private ImageView delButton, mailButton, shareButton;
private String imgUrl = null;
private AdView mAdView;
TextView titletxt;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
public static boolean deleted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.image_detail);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mainImageView = (ImageView) findViewById(R.id.mainImageView);
menuTop = (LinearLayout) findViewById(R.id.menuTop);
menuBottom = (TableLayout) findViewById(R.id.menuBottom);
titletxt = (TextView) findViewById(R.id.titletxt);
titletxt.setTextSize(22);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
delButton = (ImageView) findViewById(R.id.delButton);
mailButton = (ImageView) findViewById(R.id.mailButton);
shareButton = (ImageView) findViewById(R.id.shareButton);
Bundle exBundle = getIntent().getExtras();
if (exBundle != null) {
imgUrl = exBundle.getString("ImgUrl");
}
if (isSdPresent()) {
imgUrl = extStorageDirectory + newFolder + imgUrl;
} else
imgUrl = getFilesDir() + newFolder + imgUrl;
if (imgUrl != null) {
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
Glide.with(this).load(imgUrl).into(imageViewTarget);
}
delButton.setOnClickListener(this);
mailButton.setOnClickListener(this);
shareButton.setOnClickListener(this);
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.shareButton:
Image_Link();
break;
case R.id.delButton:
deleted();
break;
case R.id.mailButton:
sendemail();
break;
default:
break;
}
}
private void sendemail() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"mymail#email.com", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void Image_Link() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"mymail#email.com", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void deleted() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
builder.setTitle(getString(R.string.removeoption));
builder.setMessage(getString(R.string.deleteimage));
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
File fileDel = new File(imgUrl);
boolean isCheck1 = fileDel.delete();
if (isCheck1) {
deleted = true;
finish();
MyGallery.imageAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
}
});
Dialog dialog = builder.create();
dialog.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
mInterstitialAd.loadAd(adRequest);
}
}
Create its xml image_detail.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical">
<ImageView
android:id="#+id/mainImageView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:contentDescription="#string/app_name"
android:focusable="true"
android:focusableInTouchMode="true" />
<LinearLayout
android:id="#+id/adlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:visibility="gone"></LinearLayout>
<LinearLayout
android:id="#+id/menuTop"
android:layout_width="fill_parent"
android:layout_height="56dp"
android:layout_alignWithParentIfMissing="true"
android:layout_below="#+id/adlayout"
android:background="#color/colorPrimary"
android:orientation="vertical"
android:padding="10.0dip"
android:visibility="visible">
<TextView
android:id="#+id/titletxt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Islamic Gifs"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
<TableLayout
android:id="#+id/menuBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:padding="10.0dip"
android:stretchColumns="*"
android:visibility="visible">
<TableRow>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/mailButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_shareimage"
android:contentDescription="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/shareButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_shareimage_small"
android:contentDescription="#string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/delButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="#drawable/selector_delete"
android:contentDescription="#string/app_name" />
</LinearLayout>
</TableRow>
</TableLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/menuTop"
android:layout_centerHorizontal="true"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_id"></com.google.android.gms.ads.AdView>
Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="#drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="#drawable/result_bt_mail_s"/>
Dont forget to add in application tag for sdk version 29 and 30 to add this line
android:requestLegacyExternalStorage="true"
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
You can use:
ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));
You may use this to access a specific folder and get particular image
public void Retrieve(String path, String Name)
{
File imageFile = new File(path+Name);
if(imageFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
myImage = (ImageView) findViewById(R.id.savedImage);
myImage.setImageBitmap(myBitmap);
Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();
}
}
And then you can call it by
Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();
public static Bitmap decodeFile(String path) {
Bitmap b = null;
File f = new File(path);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
public static Bitmap showBitmapFromFile(String file_path)
{
try {
File imgFile = new File(file_path);
if(imgFile.exists()){
Bitmap pic_Bitmap = decodeFile(file_path);
return pic_Bitmap;
}
} catch (Exception e) {
MyLog.e("Exception showBitmapFromFile");
return null;
}
return null;
}
if you are using image loading in List view then use Aquery concept .
https://github.com/AshishPsaini/AqueryExample
AQuery aq= new AQuery((Activity) activity, convertView);
//load image from file, down sample to target width of 250 pixels .gi
File file=new File("//pic/path/here/aaaa.jpg");
if(aq!=null)
aq.id(holder.pic_imageview).image(file, 250);
onLoadImage Full load
private void onLoadImage(final String imagePath) {
ImageSize targetSize = new ImageSize(imageView.getWidth(), imageView.getHeight()); // result Bitmap will be fit to this size
//ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleto
com.nostra13.universalimageloader.core.ImageLoader imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getContext()));
imageLoader.loadImage(imagePath, targetSize, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(final String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
progress2.setVisibility(View.VISIBLE);
new Handler().post(new Runnable() {
public void run() {
progress2.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
// Picasso.with(getContext()).load(imagePath).into(imageView);
// Picasso.with(getContext()).load(imagePath) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);
Glide.with(getContext())
.load(imagePath)
.asBitmap()
.into(imageView);
}
});
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
// else {
Log.e("onLoadImage", "onLoadingComplete");
// progress2.setVisibility(View.INVISIBLE);
// }
// setLoagingCompileImage();
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
Log.e("onLoadingFailed", imageUri);
Log.e("onLoadingFailed", failReason.toString());
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
super.onLoadingCancelled(imageUri, view);
if (view == null) {
progress2.setVisibility(View.INVISIBLE);
}
Log.e("onLoadImage", "onLoadingCancelled");
}
});
}
private void showImage(ImageView img, String absolutePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapPicture = BitmapFactory.decodeFile(absolutePath);
img.setImageBitmap(bitmapPicture);
}
Most of the answers are working but no one mentioned that the high resolution image will slow down the app , In my case i used images RecyclerView which was taking 0.9 GB of device memory In Just 30 Images.
I/Choreographer: Skipped 73 frames! The application may be doing too
much work on its main thread.
The solution is Sipmle you can degrade the quality like here : Reduce resolution of Bitmap
But I use Simple way , Glide handles the rest of work
fanContext?.let {
Glide.with(it)
.load(Uri.fromFile(File(item.filePath)))
.into(viewHolder.imagePreview)
}
You can easily do this using bitmap. You can find the code below :
ImageView imageView=findViewById(R.id.imageView);
Bitmap bitMapImage= BitmapFactory.decodeFile("write path of your image");
imageView.setImageBitmap(bitMapImage);
mageView.setImageResource(R.id.img);

Categories

Resources