My imageView doesn`t work - android

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

Related

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

How can I save my current imageview when onClick?

How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}

NullPointerException when retrieving data from sqlite database

ive stored some image names in a sqlite database.My code is supposed to retrieve all the imagenames and store it in a array and then assign the first image to an imageview based on its name.Im using UIL to set the images to the image view.
MY CODE
public class Locker extends Activity {
int index = 0, limit, tolerance = 40, state = 1;
String[] bgimg;
String[] ranimg;
int[] ActXCod;
int[] ActYCod;
ImageView image;
ImageLoader imageloader;
File Path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locker);
image = (ImageView) findViewById(R.id.imageView1);
SharedPreferences getprefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String temp = getprefs.getString("ImageSeqNo", "4");
limit = Integer.parseInt(temp);
Path = getExternalFilesDir(null);
Constants cons = new Constants();
ranimg = cons.getImagePath(Path.toString());
imageloader = ImageLoader.getInstance();
try {
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} catch (Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("ERROR");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent object holds X-Y values
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int XCood = (int) event.getX();
int YCood = (int) event.getY();
int XMin = ActXCod[index] - tolerance, XMax = ActXCod[index]
+ tolerance, YMin = ActYCod[index] - tolerance, YMax = ActYCod[index]
+ tolerance;
/*
* String text = "You clicked at x = " + XCood + " and y = " +
* YCood; final Toast toast = Toast.makeText(this, text,
* Toast.LENGTH_SHORT); toast.show(); Handler handler = new
* Handler(); handler.postDelayed(new Runnable() {
*
* #Override public void run() { toast.cancel(); } }, 750);
*/
if (index < (limit - 1)) // loop to check number of images
{
// loop to check status
if ((state == 1)
&& (((XCood > XMin) && (XCood < XMax)) && ((YCood > YMin) && (YCood < YMax)))) {
index++;
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
} else {
index++;
Random r = new Random();
int ran = r.nextInt(10 - 0);
imageloader.displayImage("file://" + ranimg[ran], image);
state = 0;
}
} else {
if (state == 1) {
Intent i = new Intent(Locker.this, Compare_Pattern.class);
startActivity(i);
finish();
} else {
new AlertDialog.Builder(this)
.setTitle("Failed Login Attempt")
.setMessage(
"Your previous login attempt has failed.Would you like to try again?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// continue with delete
Intent intent = getIntent();
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// do nothing
finish();
}
}).show();
}
}
}
return super.onTouchEvent(event);
}
#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;
}
class getData implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
DataBaseHandler handler = new DataBaseHandler(
getApplicationContext());
handler.open();
ActXCod = handler.getXcod();
ActYCod = handler.getYcod();
bgimg = handler.getImg();
handler.close();
}
}
}
i tried debugging the code and its giving me a Java.lang.NullPointerException for bgimg[index] at the line imageloader.displayImage("file://" + Path.toString() + "/" + bgimg[index], image);. i cannot figure out why. Any help is gratefully accepted.
new Thread(new getData()).start();
imageloader.displayImage("file://" + Path.toString() + "/"
+ bgimg[index], image);
bgimg is not initialized yet. Even if you start your thread, it does not run and compelete initialization of bgimg immediately.
Move the code that requires the result of the thread code into the thread itself. You can use Activity.runOnUiThread() to move the execution back to UI thread from a background thread.

open cv error(fatal signal 11) if images converted to grayscale

I know its related to heap of device but it even crashes when i use very small images.And i tried it on samsung grand,motog,karbonn titanium s1.It crashes everywhere>is there a way to handle it.The only thing iam doing is first converting the images to gray scale and then compare.if i compare images without converting to grayscale it works fine no matter how big is image.
here is my code--
main activity
public class MainActivity extends Activity {
private static final String TAG = "OCVSample::Activity";
private static Bitmap bmp, yourSelectedImage, bmpimg1, bmpimg2;
private static ImageView iv1, iv2;
private static TextView tv;
private static String path1, path2;
private static String text;
private static Button start;
private static int imgNo = 0;
private static Uri selectedImage;
private static InputStream imageStream;
private static long startTime, endTime;
private static final int SELECT_PHOTO = 100;
//private static int descriptor = DescriptorExtractor.BRISK;
private static int descriptor = DescriptorExtractor.SIFT;
private static String descriptorType;
private static int min_dist = 10;
private static int min_matches = 750;
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
doTask1(iv1,true);
doTask1(iv2, false);
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
iv2 = (ImageView) MainActivity.this.findViewById(R.id.img2);
start = (Button) MainActivity.this.findViewById(R.id.button1);
tv = (TextView) MainActivity.this.findViewById(R.id.tv);
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this,
mLoaderCallback);
run();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent call = new Intent(MainActivity.this, Settings.class);
call.putExtra("descriptor", descriptor);
call.putExtra("min_dist", min_dist);
call.putExtra("min_matches", min_matches);
call.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
call.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(call);
break;
}
return true;
}
public void run() {
if (descriptor == DescriptorExtractor.BRIEF)
descriptorType = "BRIEF";
else if (descriptor == DescriptorExtractor.BRISK)
descriptorType = "BRISK";
else if (descriptor == DescriptorExtractor.FREAK)
descriptorType = "FREAK";
else if (descriptor == DescriptorExtractor.ORB)
descriptorType = "ORB";
else if (descriptor == DescriptorExtractor.SIFT)
descriptorType = "SIFT";
else if(descriptor == DescriptorExtractor.SURF)
descriptorType = "SURF";
System.out.println(descriptorType);
tv.setText("Select the two images to be compared.\n"+"DescriptorExtractor:"+descriptorType+"\nHamming distance between descriptors:"+min_dist+"\nMinimum number of good matches:"+min_matches);
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 1;
}
});
iv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 2;
}
});
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (bmpimg1 != null && bmpimg2 != null) {
/*if(bmpimg1.getWidth()!=bmpimg2.getWidth()){
bmpimg2 = Bitmap.createScaledBitmap(bmpimg2, bmpimg1.getWidth(), bmpimg1.getHeight(), true);
}*/
bmpimg1 = Bitmap.createScaledBitmap(bmpimg1, 100, 100, true);
bmpimg2 = Bitmap.createScaledBitmap(bmpimg2, 100, 100, true);
Mat img1 = new Mat();
Utils.bitmapToMat(bmpimg1, img1);
Mat img2 = new Mat();
Utils.bitmapToMat(bmpimg2, img2);
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_RGBA2GRAY);
Imgproc.cvtColor(img2, img2, Imgproc.COLOR_RGBA2GRAY);
img1.convertTo(img1, CvType.CV_32F);
img2.convertTo(img2, CvType.CV_32F);
//Log.d("ImageComparator", "img1:"+img1.rows()+"x"+img1.cols()+" img2:"+img2.rows()+"x"+img2.cols());
Mat hist1 = new Mat();
Mat hist2 = new Mat();
MatOfInt histSize = new MatOfInt(180);
MatOfInt channels = new MatOfInt(0);
ArrayList<Mat> bgr_planes1= new ArrayList<Mat>();
ArrayList<Mat> bgr_planes2= new ArrayList<Mat>();
Core.split(img1, bgr_planes1);
Core.split(img2, bgr_planes2);
MatOfFloat histRanges = new MatOfFloat (0f, 180f);
boolean accumulate = false;
Imgproc.calcHist(bgr_planes1, channels, new Mat(), hist1, histSize, histRanges, accumulate);
Core.normalize(hist1, hist1, 0, hist1.rows(), Core.NORM_MINMAX, -1, new Mat());
Imgproc.calcHist(bgr_planes2, channels, new Mat(), hist2, histSize, histRanges, accumulate);
Core.normalize(hist2, hist2, 0, hist2.rows(), Core.NORM_MINMAX, -1, new Mat());
img1.convertTo(img1, CvType.CV_32F);
img2.convertTo(img2, CvType.CV_32F);
hist1.convertTo(hist1, CvType.CV_32F);
hist2.convertTo(hist2, CvType.CV_32F);
double compare = Imgproc.compareHist(hist1, hist2, Imgproc.CV_COMP_CHISQR);
Log.v("ImageComparator", "compare: "+compare);
if(compare>0 && compare<1500) {
Toast.makeText(MainActivity.this, "Images may be possible duplicates, verifying", Toast.LENGTH_LONG).show();
new asyncTask(MainActivity.this).execute();
}
else if(compare==0)
Toast.makeText(MainActivity.this, "Images are exact duplicates", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Images are not duplicates", Toast.LENGTH_LONG).show();
startTime = System.currentTimeMillis();
} else
Toast.makeText(MainActivity.this,
"You haven't selected images.", Toast.LENGTH_LONG)
.show();
}
});
}
#Override
protected void onNewIntent(Intent newIntent) {
super.onNewIntent(newIntent);
min_dist = newIntent.getExtras().getInt("min_dist");
descriptor = newIntent.getExtras().getInt("descriptor");
min_matches = newIntent.getExtras().getInt("min_matches");
run();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try{
selectedImage = imageReturnedIntent.getData();
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
if (imgNo == 1) {
iv1.setImageBitmap(yourSelectedImage);
path1 = selectedImage.getPath();
bmpimg1 = yourSelectedImage;
iv1.invalidate();
} else if (imgNo == 2) {
iv2.setImageBitmap(yourSelectedImage);
path2 = selectedImage.getPath();
bmpimg2 = yourSelectedImage;
iv2.invalidate();
}
}
catch(OutOfMemoryError exception){
Toast.makeText(getBaseContext(), exception.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
catch (NullPointerException e) {
// TODO: handle exception
Toast.makeText(getBaseContext(), "Image cant be selected", Toast.LENGTH_SHORT);
}
}
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this, // My changes
mLoaderCallback);
}
public static class asyncTask extends AsyncTask<Void, Void, Void> {
private static Mat img1, img2, descriptors, dupDescriptors;
private static FeatureDetector detector;
private static DescriptorExtractor DescExtractor;
private static DescriptorMatcher matcher;
private static MatOfKeyPoint keypoints, dupKeypoints;
private static MatOfDMatch matches, matches_final_mat;
private static ProgressDialog pd;
private static boolean isDuplicate = false;
private MainActivity asyncTaskContext=null;
private static Scalar RED = new Scalar(255,0,0);
private static Scalar GREEN = new Scalar(0,255,0);
public asyncTask(MainActivity context)
{
asyncTaskContext=context;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(asyncTaskContext);
pd.setIndeterminate(true);
pd.setCancelable(true);
pd.setCanceledOnTouchOutside(false);
pd.setMessage("Processing...");
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
compare();
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
Mat img3 = new Mat();
MatOfByte drawnMatches = new MatOfByte();
Features2d.drawMatches(img1, keypoints, img2, dupKeypoints,
matches_final_mat, img3, GREEN, RED, drawnMatches, Features2d.NOT_DRAW_SINGLE_POINTS);
bmp = Bitmap.createBitmap(img3.cols(), img3.rows(),
Bitmap.Config.ARGB_8888);
Imgproc.cvtColor(img3, img3, Imgproc.COLOR_BGR2RGB);
Utils.matToBitmap(img3, bmp);
List<DMatch> finalMatchesList = matches_final_mat.toList();
final int matchesFound=finalMatchesList.size();
endTime = System.currentTimeMillis();
if (finalMatchesList.size() > min_matches)// dev discretion for
// number of matches to
// be found for an image
// to be judged as
// duplicate
{
text = finalMatchesList.size()
+ " matches were found. Possible duplicate image.\nTime taken="
+ (endTime - startTime) + "ms";
isDuplicate = true;
} else {
text = finalMatchesList.size()
+ " matches were found. Images aren't similar.\nTime taken="
+ (endTime - startTime) + "ms";
isDuplicate = false;
}
pd.dismiss();
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(
asyncTaskContext);
alertDialog.setTitle("Result");
alertDialog.setCancelable(false);
LayoutInflater factory = LayoutInflater.from(asyncTaskContext);
final View view = factory.inflate(R.layout.image_view, null);
ImageView matchedImages = (ImageView) view
.findViewById(R.id.finalImage);
matchedImages.setImageBitmap(bmp);
matchedImages.invalidate();
final CheckBox shouldBeDuplicate = (CheckBox) view
.findViewById(R.id.checkBox);
TextView message = (TextView) view.findViewById(R.id.message);
message.setText(text);
alertDialog.setView(view);
shouldBeDuplicate
.setText("These images are actually duplicates.");
alertDialog.setPositiveButton("Add to logs",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
File logs = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt");
FileWriter fw;
BufferedWriter bw;
try {
fw = new FileWriter(logs, true);
bw = new BufferedWriter(fw);
bw.write("Algorithm used: "
+ descriptorType
+ "\nHamming distance: "
+ min_dist + "\nMinimum good matches: "+min_matches
+"\nMatches found: "+matchesFound+"\nTime elapsed: "+(endTime-startTime)+"seconds\n"+ path1
+ " was compared to " + path2
+ "\n" + "Is actual duplicate: "
+ shouldBeDuplicate.isChecked()
+ "\nRecognized as duplicate: "
+ isDuplicate + "\n");
bw.close();
Toast.makeText(
asyncTaskContext,
"Logs updated.\nLog location: "
+ Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
try {
File dir = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/");
dir.mkdirs();
logs.createNewFile();
logs = new File(
Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt");
fw = new FileWriter(logs, true);
bw = new BufferedWriter(fw);
bw.write("Algorithm used: "
+ descriptorType
+ "\nMinimum distance between keypoints: "
+ min_dist + "\n" + path1
+ " was compared to " + path2
+ "\n"
+ "Is actual duplicate: "
+ shouldBeDuplicate.isChecked()
+ "\nRecognized as duplicate: "
+ isDuplicate + "\n");
bw.close();
Toast.makeText(
asyncTaskContext,
"Logs updated.\nLog location: "
+ Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt",
Toast.LENGTH_LONG).show();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(asyncTaskContext, e.toString(),
Toast.LENGTH_LONG).show();
}
}
void compare() {
try {
bmpimg1 = bmpimg1.copy(Bitmap.Config.ARGB_8888, true);
bmpimg2 = bmpimg2.copy(Bitmap.Config.ARGB_8888, true);
img1 = new Mat();
img2 = new Mat();
Utils.bitmapToMat(bmpimg1, img1);
Utils.bitmapToMat(bmpimg2, img2);
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_BGR2RGB);
Imgproc.cvtColor(img2, img2, Imgproc.COLOR_BGR2RGB);
detector = FeatureDetector.create(FeatureDetector.PYRAMID_FAST);
DescExtractor = DescriptorExtractor.create(descriptor);
matcher = DescriptorMatcher
.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
keypoints = new MatOfKeyPoint();
dupKeypoints = new MatOfKeyPoint();
descriptors = new Mat();
dupDescriptors = new Mat();
matches = new MatOfDMatch();
detector.detect(img1, keypoints);
Log.d("LOG!", "number of query Keypoints= " + keypoints.size());
detector.detect(img2, dupKeypoints);
Log.d("LOG!", "number of dup Keypoints= " + dupKeypoints.size());
// Descript keypoints
DescExtractor.compute(img1, keypoints, descriptors);
DescExtractor.compute(img2, dupKeypoints, dupDescriptors);
Log.d("LOG!", "number of descriptors= " + descriptors.size());
Log.d("LOG!",
"number of dupDescriptors= " + dupDescriptors.size());
// matching descriptors
matcher.match(descriptors, dupDescriptors, matches);
Log.d("LOG!", "Matches Size " + matches.size());
// New method of finding best matches
List<DMatch> matchesList = matches.toList();
List<DMatch> matches_final = new ArrayList<DMatch>();
for (int i = 0; i < matchesList.size(); i++) {
if (matchesList.get(i).distance <= min_dist) {
matches_final.add(matches.toList().get(i));
}
}
matches_final_mat = new MatOfDMatch();
matches_final_mat.fromList(matches_final);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void doTask1(ImageView iv,boolean iv_flag) {
Bitmap bitmap=null;
if(iv_flag){
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
}
else{
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
Log.d(TAG, "bitmap: " + bitmap.getWidth() + "x" + bitmap.getHeight());
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Log.d(TAG, "bitmap 8888: " + bitmap.getWidth() + "x" + bitmap.getHeight());
//GrabCut part
Mat img = new Mat();
Utils.bitmapToMat(bitmap, img);
Log.d(TAG, "img: " + img);
int r = img.rows();
int c = img.cols();
Point p1 = new Point(c/10, r/10);
Point p2 = new Point(c-c/10, r-r/10);
Rect rect = new Rect(p1, p2);
Log.d(TAG, "rect: " + rect);
Mat mask = new Mat();
Mat fgdModel = new Mat();
Mat bgdModel = new Mat();
Mat imgC3 = new Mat();
Imgproc.cvtColor(img, imgC3, Imgproc.COLOR_RGBA2RGB);
Log.d(TAG, "imgC3: " + imgC3);
Log.d(TAG, "Grabcut begins");
Imgproc.grabCut(imgC3, mask, rect, bgdModel, fgdModel, 2, Imgproc.
GC_INIT_WITH_RECT);
Log.d(TAG, "Grabcut ends");
Log.d(TAG, "mask: " + mask);
Log.d(TAG, "bgdModel: " + bgdModel);
Log.d(TAG, "fgdModel: " + fgdModel);
Core.convertScaleAbs(mask, mask, 100, 0);
Imgproc.cvtColor(mask, mask, Imgproc.COLOR_GRAY2RGBA);
Log.d(TAG, "maskC4: " + mask);
//convert to Bitmap
Log.d(TAG, "Convert to Bitmap");
//Utils.matToBitmap(imgC3, bitmap);
Utils.matToBitmap(mask, bitmap);
iv.setImageBitmap(bitmap);
if(iv_flag)
bmpimg1=bitmap;
else
bmpimg2=bitmap;
//release MAT part
img.release();
imgC3.release();
mask.release();
fgdModel.release();
bgdModel.release();
}
}
settings activity---
public class Settings extends Activity {
#SuppressWarnings("unused")
private static RadioGroup descTypes;
private static RadioButton brief, brisk, freak, orb;
private static Button apply;
private static EditText DIST_LIMIT, MIN_MATCHES;
private static int descriptor, min_dist, min_matches;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
descTypes = (RadioGroup) findViewById(R.id.radioGroup1);
brief = (RadioButton) findViewById(R.id.radio0);
brisk = (RadioButton) findViewById(R.id.radio1);
freak = (RadioButton) findViewById(R.id.radio2);
orb = (RadioButton) findViewById(R.id.radio3);
apply = (Button) findViewById(R.id.button1);
DIST_LIMIT = (EditText) findViewById(R.id.editText1);
MIN_MATCHES = (EditText) findViewById(R.id.editText2);
MIN_MATCHES.setText("100");
DIST_LIMIT.setText("80");
apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int descriptor = 0, min_dist = 80, min_matches=100;
if (brief.isChecked())
descriptor = DescriptorExtractor.BRIEF;
else if (brisk.isChecked())
descriptor = DescriptorExtractor.BRISK;
else if (freak.isChecked())
descriptor = DescriptorExtractor.FREAK;
else if (orb.isChecked())
descriptor = DescriptorExtractor.ORB;
try {
min_dist = Integer.parseInt(DIST_LIMIT.getText().toString());
} catch (Exception e) {
e.printStackTrace();
min_dist = 500;
}
Intent call = new Intent(Settings.this, MainActivity.class);
call.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
call.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
call.putExtra("descriptor", descriptor);
call.putExtra("min_dist", min_dist);
call.putExtra("min_matches", min_matches);
startActivity(call);
}
});
}
#Override
protected void onNewIntent(Intent newIntent) {
super.onNewIntent(newIntent);
descriptor = newIntent.getExtras().getInt("descriptor");
min_dist = newIntent.getExtras().getInt("min_dist");
min_matches = newIntent.getExtras().getInt("min_matches");
DIST_LIMIT.setText(min_dist + "");
switch (descriptor) {
case 3:
orb.setChecked(true);
break;
case 4:
brief.setChecked(true);
break;
case 5:
brisk.setChecked(true);
break;
case 6:
freak.setChecked(true);
break;
}
apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (brief.isChecked())
descriptor = DescriptorExtractor.BRIEF;
else if (brisk.isChecked())
descriptor = DescriptorExtractor.BRISK;
else if (freak.isChecked())
descriptor = DescriptorExtractor.FREAK;
else if (orb.isChecked())
descriptor = DescriptorExtractor.ORB;
try {
min_dist = Integer.parseInt(DIST_LIMIT.getText().toString());
min_matches = Integer.parseInt(MIN_MATCHES.getText().toString());
} catch (Exception e) {
e.printStackTrace();
min_dist = 80;
min_matches=100;
}
Intent call = new Intent(Settings.this, MainActivity.class);
call.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
call.putExtra("descriptor", descriptor);
call.putExtra("min_dist", min_dist);
call.putExtra("min_matches", min_matches);
startActivity(call);
}
});
}
}
and the logcat---
08-22 18:44:11.919: V/ImageComparator(24384): compare: 48.32461247119096
08-22 18:44:12.139: D/LOG!(24384): number of query Keypoints= 1x65
08-22 18:44:12.139: D/LOG!(24384): number of dup Keypoints= 1x62
08-22 18:44:12.139: A/libc(24384): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 24587 (AsyncTask #1)

Photoshop image blending mode in 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>

Categories

Resources