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)
Related
Hi I am new to android i have searching this for a week,
i have a fragment that contains
textview
editext
spinner
calender
image choosing
Adding and removing same fragment in an container with unique tag. in spinner there is multiple numbers that is displayed in activity dynamically, if i add or remove same fragment, the values shown in textview should change dynamically. I know to access each instance by its tag and can get the values in activity but unable to find which fragment instance have changed.
For example, if i have added same fragment four times, made change in spinner in all the four fragment, unable to identify which instance have increased or decreased and correct the total
And also unable to find whether image is added or not.
My fragment is
public class Service_details extends Fragment {
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
ProgressDialog pDialog;
TextView textView_service_no, textView_datePicker, textView_amount, textView_optionalDate;
Spinner spinner_services;
EditText editText_dedicated, editText_intention;
ImageView display_photo;
HashMap<String, String> cList = new HashMap<>();
String[] services;
String initial_spinner_value;
String birthday_price;
String deathday_price;
String rosary_price;
String mass_price;
String prayer_price;
String marriageday_price;
OnMessageReadListener messageReadListener;
String service_value = null;
String service_spinner_string=null;
String person_image_string =null;
String editText_dedicated_string=null;
String editText_intention_string=null;
String textView_telecast_date_string=null;
String textView_amount_string =null;
String total_amount_string=null;
String tax_amount_string=null;
String final_total_amount_string=null;
int c;
int count;
String TAG = "Fragment";
Bitmap bitmap;
LinearLayout linearLayout10;
public interface OnMessageReadListener {
void onMessageRead(String message);
}
public Service_details() {
// Required empty public constructor
}
public static Service_details newInstance(int i) {
Service_details service_details = new Service_details();
Bundle bundle = new Bundle();
int c = i;
bundle.putInt("service_count",i);
service_details.setArguments(bundle);
return service_details;
}
Calendar cal;
public String message;
String path;
int temp;
int a;
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_service_details, container, false);
textView_service_no = view.findViewById(R.id.service_counting);
editText_dedicated = view.findViewById(R.id.editText_dedicated_to);
editText_intention = view.findViewById(R.id.editText_intention);
textView_datePicker = view.findViewById(R.id.date_picker);
spinner_services = view.findViewById(R.id.spinner_services);
textView_amount = view.findViewById(R.id.textview_amount);
display_photo = view.findViewById(R.id.display_photo);
textView_optionalDate = view.findViewById(R.id.textview_exactDate);
cal = Calendar.getInstance();
linearLayout10 = view.findViewById(R.id.linear10);
ButterKnife.bind(this, view);
getJson();
assert getArguments() != null;
count = getArguments().getInt("service_count");
Log.e(TAG, "count value : "+ count);
textView_service_no.setText(valueOf(count));
++count;
a=0;
display_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
textView_optionalDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
textView_optionalDate.setText(""+arg3+"/"+(arg2+1)+"/"+arg1);
Toast.makeText(getActivity(), ""+arg3+"/"+(arg2+1)+"/"+arg1, Toast.LENGTH_SHORT).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
dialog.show();
}
});
textView_datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
textView_datePicker.setText(""+arg3+"/"+(arg2+1)+"/"+arg1);
Toast.makeText(getActivity(), ""+arg1+"/"+(arg2+1)+"/"+arg3, Toast.LENGTH_SHORT).show();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 5);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.show();
}
});
services = new String[]{"Select Service","Birth Day", "Death Day", "Rosary", "Hollymass", "Prayer", "Marriage Day"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, services);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_services.setAdapter(arrayAdapter);
spinner_services.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spin_value = parent.getItemAtPosition(position).toString();
((Services)getActivity()).setCurrentSpinnerItem(spin_value);
switch (position) {
case 0:
textView_amount.setText(cList.get("empty"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
Log.e(TAG,"textView_amount (fragment name)"+ textView_amount.getTag());
String message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
Log.e(TAG, "message_temp: "+message_temp);
messageReadListener.onMessageRead(message);
break;
case 1:
textView_amount.setText(cList.get("birthday_price"));
display_photo.setVisibility(View.VISIBLE);
linearLayout10.setVisibility(View.VISIBLE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
a= Integer.parseInt(message_temp);
a= a-temp;
message = Integer.toString(a);*/
messageReadListener.onMessageRead(message);
break;
case 2:
textView_amount.setText(cList.get("deathday_price"));
display_photo.setVisibility(View.VISIBLE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 3:
textView_amount.setText(cList.get("rosary_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 4:
textView_amount.setText(cList.get("mass_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 5:
textView_amount.setText(cList.get("prayer_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.GONE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
case 6:
textView_amount.setText(cList.get("marriageday_price"));
display_photo.setVisibility(View.GONE);
linearLayout10.setVisibility(View.VISIBLE);
message_temp = textView_amount.getText().toString();
if(!message_temp.equals("")){
a = Integer.parseInt(message_temp);
}
a = a-temp;
message = Integer.toString(a);
messageReadListener.onMessageRead(message);
break;
}
// String message = textView_amount.getText().toString();
// messageReadListener.onMessageRead(message);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getActivity());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
Log.e(TAG, "contentURI : " + contentURI);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
display_photo.setImageBitmap(bitmap);
Log.e(TAG, "PATH1" + path);
Log.e(TAG, "BITMAP " + bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
display_photo.setImageBitmap(thumbnail);
path = saveImage(thumbnail);
Log.e(TAG, "PATH2" + path);
saveImage(thumbnail);
Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
Log.e(TAG, "PATH3" + path);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
Log.e(TAG, "wallpaperDirectory" + wallpaperDirectory);
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getActivity(),
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
Log.e(TAG, "File Saved::--->" + f.getAbsolutePath());
Log.e(TAG, "PATH4" + path);
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
/*------------------------------------------------------------------------------------------------------------*/
public void getDetailsFromFragment() {
service_value = textView_service_no.getText().toString();
editText_dedicated_string = editText_dedicated.getText().toString();
editText_intention_string = editText_intention.getText().toString();
textView_telecast_date_string = textView_datePicker.getText().toString();
textView_amount_string = textView_amount.getText().toString();
service_spinner_string = spinner_services.getSelectedItem().toString();
if(bitmap!=null){
person_image_string = bitmap.toString();
}
Log.e(TAG, " SERVICE NO. : " + service_value + " \n" + "SERVICES :" + service_spinner_string + " \n" + "DEDICATED TO : " + editText_dedicated_string + " \n" + " INTENTION : " +
editText_intention_string + " \n" + " TELECASTE DATE : " + textView_telecast_date_string + " \n" + " AMOUNT : " + textView_amount_string + "\n" + "IMAGE : " + person_image_string);
Log.e(TAG, "FINAL PAYMENT DETAILS: " + total_amount_string + " " + tax_amount_string + " " + final_total_amount_string);
messageReadListener.onMessageRead(message);
}
public void changeCount(int a){
c = a;
textView_service_no.setText(valueOf(c));
}
#Override
public void onAttach (Context context){
super.onAttach(context);
Activity activity = (Activity) context;
try {
messageReadListener = (OnMessageReadListener) activity;
} catch (ClassCastException c) {
throw new ClassCastException(activity.toString() + " must override onMessageReadListener...");
}
}
}
My activity is
public class Services extends DashBoard implements Service_details.OnMessageReadListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_services);
}
#OnClick(R.id.add_service)
public void addService(){
service_one_amount = Integer.parseInt(message4);
// service_one_amount = message4;
Log.e(TAG, "service_one_amount : "+ service_one_amount);
// service_one_amount = service_one_amount+ ;
if(size<5){
fragTag = "numericField" + numericFragmentCount;
getSupportFragmentManager().beginTransaction().add(R.id.container_frame,Service_details.newInstance(a), fragTag).commit();
++a;
++numericFragmentCount;
Log.e(TAG, "fragment size: "+ size);
}else {
Toast.makeText(this,"Maximum limit reached",Toast.LENGTH_LONG).show();
}
}
#OnClick(R.id.remove_service)
public void removeService(){
size= getSupportFragmentManager().getFragments().size();
if(size>1) {
--numericFragmentCount;
fragTag = "numericField" + numericFragmentCount;
fragment = getSupportFragmentManager().findFragmentById(R.id.container_frame);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
--a;
}
Log.e(TAG, "fragment : " + fragment);
}else {
Toast.makeText(this,"Minimum limit reached",Toast.LENGTH_LONG).show();
}
}
#SuppressLint("SetTextI18n")
#Override
public void onMessageRead(String message) {
try{
String identity_frag = "numericField1";
Fragment service_details1 = getSupportFragmentManager().findFragmentByTag("numericField1");
Fragment service_details2 = getSupportFragmentManager().findFragmentByTag("numericField2");
Fragment service_details3 = getSupportFragmentManager().findFragmentByTag("numericField3");
Fragment service_details4 = getSupportFragmentManager().findFragmentByTag("numericField4");
Fragment service_details5 = getSupportFragmentManager().findFragmentByTag("numericField5");
Log.e(TAG,"before adding message4: "+message4);
message1 = Integer.parseInt(message);
service_details1 instanceof Service_details;
Log.e(TAG,"before initial temp: "+ temp);
if(!textView_amount_view.getText().toString().equals("0")){
initial_amount= String.valueOf(message4);
}else {
initial_amount =textView_amount_view.getText().toString();
}
message3 = Integer.parseInt(initial_amount);
message1= message3+message1-temp;
temp = message1;
Log.e(TAG,"after initial temp: "+ temp);
message1 = message1+service_one_amount;
long res = (long) Math.ceil((message1/ 100.0f) * 18);
double res1 = ((message1/ 100f) * 18);
Toast.makeText(getApplicationContext(), "" + res1, Toast.LENGTH_SHORT).show();
int final_amount = (int) (message1 + res);
message4 = Integer.toString(message1);
Log.e(TAG,"after adding message4: "+message4);
textView_amount_view.setText(currency_symbol+" "+ String.valueOf(message4));
textView_tax_amount_view.setText(currency_symbol+" "+ String.valueOf(res)+ decimal_value);
textView_total_amount_view.setText(currency_symbol+" "+ String.valueOf(final_amount)+ decimal_value);
Log.e(TAG,"total amount: "+message4);
Log.e(TAG,"tax amount: "+res);
Log.e(TAG,"amount after tax: "+final_amount);
}catch (NumberFormatException e){
e.printStackTrace();
}
}
}
if u find question is hard please upvote to reach more people..
Thanks in advance..
I wrote a program that is used to detect bananas using OpenCV's Haar Cascade method.
public class MainActivity extends Activity implements CvCameraViewListener2 {
private static final String TAG = "OCVSample::Activity";
private static final Scalar BANANA_RECT_COLOR = new Scalar(0, 255, 0, 255);
public static final int JAVA_DETECTOR = 0;
private Mat mRgba;
private Mat mGray;
private File mCascadeFile;
private CascadeClassifier mJavaDetectorBanana;
boolean check = false;
private int mDetectorType = JAVA_DETECTOR;
private String[] mDetectorName;
private float mRelativeBananaSize = 0.2f;
private int mAbsoluteBananaSize = 0;
private CameraBridgeViewBase mOpenCvCameraView;
public Button mSpeechButton;
public TextView checkResults;
double xCenter = -1;
double yCenter = -1;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV Loaded Successfully");
try {
InputStream is = getResources().openRawResource(R.raw.banana4th);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "banana4th.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
mJavaDetectorBanana = new CascadeClassifier(mCascadeFile.getAbsolutePath());
if (mJavaDetectorBanana.empty()) {
Log.e(TAG, "Failed to load cascade classifier");
mJavaDetectorBanana = null;
} else
Log.i(TAG, "Loaded cascade classifier from " + mCascadeFile.getAbsolutePath());
cascadeDir.delete();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);
}
mOpenCvCameraView.enableFpsMeter();
mOpenCvCameraView.setCameraIndex(0);
mOpenCvCameraView.enableView();
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
public MainActivity() {
mDetectorName = new String[2];
mDetectorName[JAVA_DETECTOR] = "Java";
Log.i(TAG, "Instantiated new" + this.getClass());
}
#Override
public void onCreate(Bundle savedInstanceState){
Log.i(TAG,"Called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.fd_activity_surface_view);
mOpenCvCameraView.setCvCameraViewListener(this);
mSpeechButton = (Button) findViewById(R.id.ttsBtn);
checkResults = (TextView) findViewById(R.id.checkResultTB);
Button backButton = (Button) findViewById(R.id.backBtn);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent UIActivity = new Intent(MainActivity.this, UiActivity.class);
startActivity(UIActivity);
}
});
}
#Override
public void onPause() {
super.onPause();
if(mOpenCvCameraView!=null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume() {
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_3_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mGray = new Mat();
mRgba = new Mat();
}
public void onCameraViewStopped() {
mGray.release();
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
if (mAbsoluteBananaSize == 0) {
int height = mGray.rows();
if (Math.round(height * mRelativeBananaSize) > 0) {
mAbsoluteBananaSize = Math.round(height * mRelativeBananaSize);
}
}
MatOfRect bananas = new MatOfRect();
if (mDetectorType == JAVA_DETECTOR) {
if (mJavaDetectorBanana != null) {
mJavaDetectorBanana.detectMultiScale(mGray, bananas, 1.1, 2, 2, //TODO: objdetect.CV_HAAR_SCALE_IMAGE)
new Size(mAbsoluteBananaSize, mAbsoluteBananaSize), new Size());
}
} else {
Log.e(TAG, "Detection method is not selected!");
}
Rect[] bananasArray = bananas.toArray();
for (int i = 0; i < bananasArray.length; i++) {
Imgproc.rectangle(mRgba, bananasArray[i].tl(), bananasArray[i].br(), BANANA_RECT_COLOR, 3);
xCenter = (bananasArray[i].x + bananasArray[i].width + bananasArray[i].x) / 2;
yCenter = (bananasArray[i].y + bananasArray[i].height + bananasArray[i].y) / 2;
}
return mRgba;
}
After running the code and a banana is present in the Android device's camera, the banana will be outlined in a rectangle as shown:
Banana Outlined in blue rectangle using the imgproc.rectangle function
After this, I wish to add a button which upon being pressed, will change the text of a textview to say "Banana Detected" if a banana is present on the screen and "Banana Not Detected" if a banana is not present on the screen.
This is where I'm stuck, how do you check if a banana is on screen? I know an if-else must be used but I'm unsure of the conditions needed. Any help is greatly appreciated!
If no bananas are detected, your bananasArray should be empty.
In this case, change the TextView by checking if bananasArray contains data.
(For example, by checking if bananasArray.length > 0)
I have an activity/intent in which a text file (which contains a JSON array) is read from the device.
On every reload another row from the array is being processes.
The text file isn't that large (20 Kb) and is being downloaded in the MainActivity together with some images (up to 50) which are between 20 and 70 Kb.
Everytime the intent is reloaded and another row is processes, another image is being loaded into an ImageView. Also several TextViews are updated with Strings that are read from the JSON array.
The issue is that with every reload of the intent, the memory usage increases with about 1 Mb.
I show this through the use of:
Runtime runtime = Runtime.getRuntime();
long usedMemory=runtime.totalMemory() / (1024 * 1024);
The Bitmap is recycled,
BufferedWriter is closed,
FileInputStream is closed,
BufferedReader is closed and
InputStreamReader is closed
What am I missing that causes the memory usage to increase?
This is the code form the Activity:
public class LoadRaaplijstActivity extends AppCompatActivity {
private TextView locatieText;
private TextView totaalText;
private TextView inhoudText;
private TextView descriptionText;
private TextView eanText;
private TextView ditpadText;
private TableLayout layout16;
private TableLayout layout32;
private Button raapbuttonNext;
private Menu menu;
private Toast toast;
private String next;
private String prev;
private String deze;
private String ean;
private String foto;
private String description;
private String voorraad;
private String totaal;
private String inhoud;
private JSONArray bakken;
private int aantalbakken;
private String einde = "";
private String loadeinde = "0";
private String picked;
private String locatie;
private String locatiepadclean;
private String locatiemeterclean;
private String locatieplankclean;
private String locatievakjeclean;
private String pijl;
private String totaalditpad;
private String batch;
private String kar;
private String raper;
private String afmaken;
String spinneridSelected;
String spinnerkarSelected;
String spinnerraperSelected;
String radioAfmakenSelected;
Bitmap myBitmap;
ArrayList<Integer> gehadArray = new ArrayList<Integer>();
//JSON array
private JSONArray raaplijstresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setContentView(R.layout.activity_load_raaplijst);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.productimage).setVisibility(View.GONE);
findViewById(R.id.wificonnectie).setVisibility(View.GONE);
findViewById(R.id.probeeropnieuw).setVisibility(View.GONE);
findViewById(R.id.raapbuttonNext).setVisibility(View.VISIBLE);
findViewById(R.id.raapbuttonPrev).setVisibility(View.VISIBLE);
raapbuttonNext = (Button) findViewById(R.id.raapbuttonNext);
raapbuttonNext.setFocusable(true);
raapbuttonNext.setFocusableInTouchMode(true);
raapbuttonNext.requestFocus();
locatieText = (TextView) findViewById(R.id.locatieText);
totaalText = (TextView) findViewById(R.id.totaalText);
inhoudText = (TextView) findViewById(R.id.inhoudText);
eanText = (TextView) findViewById(R.id.eanText);
ditpadText = (TextView) findViewById(R.id.ditpadTxt);
descriptionText = (TextView) findViewById(R.id.descriptionText);
layout16 = (TableLayout) findViewById(R.id.layout16);
layout32 = (TableLayout) findViewById(R.id.layout32);
Intent intent = getIntent();
spinneridSelected = intent.getStringExtra("spinneridSelected");
spinnerkarSelected = intent.getStringExtra("spinnerkarSelected");
spinnerraperSelected = intent.getStringExtra("spinnerraperSelected");
radioAfmakenSelected = intent.getStringExtra("radioAfmakenSelected");
deze = intent.getStringExtra("load");
batch = spinneridSelected;
kar = spinnerkarSelected;
raper = spinnerraperSelected;
afmaken = radioAfmakenSelected;
if(afmaken.equals("ja")){
deze = getLaatstgehad();
}
Integer gehad = Integer.parseInt(deze.toString());
gehadArray = intent.getIntegerArrayListExtra("gehadArray");
if(!gehadArray.contains(gehad)) {
try {
gehadArray.add(gehad);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}else{
locatieText.setTextColor(Color.GREEN);
}
saveGehad();
getRaaplijstRegel();
}
private void saveGehad() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File file = new File(dir, "/gehad.txt");
if(file.exists()) file.delete();
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.write(deze.toString());
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLaatstgehad() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File file = new File(dir, "/gehad.txt");
String ret = deze;
if(file.exists()){
try {
FileInputStream inputStream = new FileInputStream (file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStreamReader.close();
bufferedReader.close();
inputStream.close();
String gehadFromFile = stringBuilder.toString();
ret = gehadFromFile;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
ret = deze;
}
return ret;
}
public void loadPrev (View view){
loadRaaplijstPrev();
}
public void loadRaaplijstPrev (){
if (prev.equals("-1")) {
Intent intent = new Intent(this, GratisProducten.class);
Bundle extras = new Bundle();
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", "nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("load", prev);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected","nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
}
public void loadBegin (View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
public void loadBegin(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
public void loadNext (View view){
loadRaaplijstNext();
}
public void loadRaaplijstNext (){
if (loadeinde.equals("1")) {
loadEnd();
} else {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected","nee");
extras.putString("load", next);
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
}
public void loadEnd(){
Intent intent = new Intent(this, EndActivity.class);
Bundle extras = new Bundle();
extras.putString("einde", einde);
extras.putString("load", deze);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", "nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
private String readRaaplijstFromFile() {
String ret = "Raaplijst niet gevonden";
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
try {
FileInputStream inputStream = new FileInputStream (new File(dir + "/raaplijstJSON.txt"));
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStreamReader.close();
bufferedReader.close();
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
private void getRaaplijstRegel(){
String raaplijstJson = readRaaplijstFromFile();
if(raaplijstJson.equals("Raaplijst niet gevonden")){
}else{
try {
JSONObject j = new JSONObject(raaplijstJson);
raaplijstresult = j.getJSONArray(Config.JSON_ARRAY_RAAPLIJST);
getRegel(raaplijstresult);
} catch (JSONException e) {StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
writeExceptionToFile(stacktrace);
e.printStackTrace();
}
}
}
private void getRegel(JSONArray j) {
for (int h = 0; h < j.length(); h++) {
try {
JSONObject sorteerObj = j.getJSONObject(h);
JSONArray sorteer = sorteerObj.getJSONArray("sorteer");
int i = Integer.parseInt(deze);
try {
JSONObject json = sorteer.getJSONObject(i);
einde = json.getString("einde");
loadeinde = json.getString("loadeinde");
if(loadeinde.equals("1")){
loadEnd();
}
ean = json.getString("ean");
eanText.setText("EAN: " + ean);
locatie = json.getString("locatie");
locatieText.setText(locatie);
locatiepadclean = json.getString("locatiepad");
if(locatiepadclean.equals("leeg")){
locatiepadclean = "";
}
locatiemeterclean = json.getString("locatiemeter");
if(locatiemeterclean.equals("leeg")){
locatiemeterclean = "";
}
locatieplankclean = json.getString("locatieplank");
if(locatieplankclean.equals("leeg")){
locatieplankclean = "";
}
locatievakjeclean = json.getString("locatievakje");
if(locatievakjeclean.equals("leeg")){
locatievakjeclean = "";
}
picked = json.getString("picked");
if(picked.equals("1")) {
locatieText.setTextColor(Color.GREEN);
}
foto = json.getString("foto");
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File imgFile = new File(dir + "/" + foto);
if(imgFile.exists()){
if (myBitmap != null) {
myBitmap.recycle();
myBitmap = null;
}
myBitmap = decodeFile(imgFile, 231, 231);
ImageView bindImage = (ImageView) findViewById(R.id.productimage);
bindImage.setImageBitmap(myBitmap);
}else{
toast = Toast.makeText(getApplicationContext(), imgFile.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 20);
toast.show();
}
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
findViewById(R.id.productimage).setVisibility(View.VISIBLE);
description = json.getString("description");
descriptionText.setText(description);
voorraad = json.getString("voorraad");
aantalbakken = Integer.parseInt(json.getString("aantalbakken"));
if(aantalbakken == 32){
findViewById(R.id.layout16).setVisibility(View.GONE);
findViewById(R.id.layout32).setVisibility(View.VISIBLE);
findViewById(R.id.layout32).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
public void onSwipeTop() {
}
public void onSwipeRight() {
loadRaaplijstPrev();
}
public void onSwipeLeft() {
loadRaaplijstNext();
}
public void onSwipeBottom() {
}
});
}else{
findViewById(R.id.layout32).setVisibility(View.GONE);
findViewById(R.id.layout16).setVisibility(View.VISIBLE);
findViewById(R.id.layout16).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
public void onSwipeTop() {
}
public void onSwipeRight() {
loadRaaplijstPrev();
}
public void onSwipeLeft() {
loadRaaplijstNext();
}
public void onSwipeBottom() {
}
});
}
int b = 0;
int[] textViewIds;
int[] bakdrawables;
if(aantalbakken == 32) {
textViewIds = new int[]{R.id.b32, R.id.b33, R.id.b34, R.id.b35, R.id.b36, R.id.b37, R.id.b38, R.id.b39,
R.id.b40, R.id.b41, R.id.b42, R.id.b43, R.id.b44, R.id.b45, R.id.b46, R.id.b47,
R.id.b48, R.id.b49, R.id.b50, R.id.b51, R.id.b52, R.id.b53, R.id.b54, R.id.b55,
R.id.b56, R.id.b57, R.id.b58, R.id.b59, R.id.b60, R.id.b61, R.id.b62, R.id.b63
};
bakdrawables = new int[]{R.drawable.vbbb1, R.drawable.vbbb2, R.drawable.vbbb3, R.drawable.vbbb4, R.drawable.vbbb5, R.drawable.vbbb6, R.drawable.vbbb7, R.drawable.vbbb8,
R.drawable.vbbb9, R.drawable.vbbb10, R.drawable.vbbb11, R.drawable.vbbb12, R.drawable.vbbb13, R.drawable.vbbb14, R.drawable.vbbb15, R.drawable.vbbb16,
R.drawable.vbbb17, R.drawable.vbbb18, R.drawable.vbbb19, R.drawable.vbbb20, R.drawable.vbbb21, R.drawable.vbbb22, R.drawable.vbbb23, R.drawable.vbbb24,
R.drawable.vbbb25, R.drawable.vbbb26, R.drawable.vbbb27, R.drawable.vbbb28, R.drawable.vbbb29, R.drawable.vbbb30, R.drawable.vbbb31, R.drawable.vbbb32
};
}else{
textViewIds = new int[]{R.id.b16, R.id.b17, R.id.b18, R.id.b19,
R.id.b20, R.id.b21, R.id.b22, R.id.b23,
R.id.b24, R.id.b25, R.id.b26, R.id.b27,
R.id.b28, R.id.b29, R.id.b30, R.id.b31
};
bakdrawables = new int[]{R.drawable.vbb1, R.drawable.vbb2, R.drawable.vbb3, R.drawable.vbb4, R.drawable.vbb5, R.drawable.vbb6, R.drawable.vbb7, R.drawable.vbb8,
R.drawable.vbb9, R.drawable.vbb10, R.drawable.vbb11, R.drawable.vbb12, R.drawable.vbb13, R.drawable.vbb14, R.drawable.vbb15, R.drawable.vbb16
};
}
for (int z = 0; z < aantalbakken; z++) {
String prefixbakdrawable = "vbb";
if(aantalbakken == 32){
prefixbakdrawable = "vbbb";
}
Integer inhoudBak = Integer.parseInt(json.getString("b" + z));
if (inhoudBak > 0) {
((TextView) findViewById(textViewIds[z])).setText(inhoudBak.toString());
((TextView) findViewById(textViewIds[z])).setTextColor(Color.WHITE);
findViewById(textViewIds[z]).setBackgroundResource(bakdrawables[z]);
} else {
((TextView) findViewById(textViewIds[z])).setText(" ");
}
}
totaal = json.getString("totaal");
totaalText.setText(totaal);
inhoud = json.getString("inhoud");
inhoudText.setText(inhoud);
prev = json.getString("prev");
next = json.getString("next");
pijl = json.getString("pijl");
if(pijl.equals("left")){
locatieText.setBackgroundResource(R.drawable.left);
}
totaalditpad = json.getString("totaalditpad");
ditpadText.setText(totaalditpad);
if (sorteerObj.has("bakken")) {
bakken = sorteerObj.getJSONArray("bakken");
}
} catch (JSONException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
e.printStackTrace();
}
} catch (JSONException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
writeExceptionToFile(stacktrace);
e.printStackTrace();
}
}
}
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
public void probeerOpnieuw (View v){
loadAgain("ja");
}
public void loadAgain(String doorgaan) {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("load", deze);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", doorgaan);
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_load_raaplijst, menu);
this.menu = menu;
String headerTxtTxt = "Batch: " + batch + "- Kar: " + kar + "- Raper: " + raper;
Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory() / (1024 * 1024);
long usedMemory=(runtime.totalMemory() / (1024 * 1024)) - (runtime.freeMemory() / (1024 * 1024));
if(!Config.DEBUG.equals("")) headerTxtTxt = headerTxtTxt + " MaxMem:" + maxMemory + "Mb CurMem:" + usedMemory;
setTitle(headerTxtTxt);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.stopraaplijst:
Intent intent = new Intent(this, MainActivity.class);
Bundle extras = new Bundle();
intent.putExtras(extras);
startActivity(intent);
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
loadAgain(radioAfmakenSelected);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
loadRaaplijstPrev();
return true;
case KeyEvent.KEYCODE_ENTER:
loadRaaplijstNext();
return true;
default:
return true;
}
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_ENTER:
return true;
default:
return true;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void writeExceptionToFile(String exception){
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(
new Date());
File dir = new File(root.getAbsolutePath() + "/Lograaplijst");
if (!dir.exists()) {
dir.mkdirs();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String formattedDate = df.format(c.getTime());
File file = new File(dir, "log_h_" + formattedDate + "_" + batch + "_" + kar + ".txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + exception.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview
I am developping an android application for face recognition ,and when i press the button to store the picture , My app stopped !!
Here is my code the the Activity Add Picture :
public class Add_Picture extends FragmentActivity implements CvCameraViewListener2 {
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
Log.e("no","no");
}
else {
Log.e("ok","ok");
}
}
static
{
// If you use opencv 2.4, System.loadLibrary("opencv_java")
System.loadLibrary("opencv_java3");
}
private static final String TAG = "Reconnaissance Faciale";
public static final int VIEW_MODE_LISTFRAMES= 1;
private MenuItem listframes;
public static int viewMode;
private Mat mRgba;
private CameraBridgeViewBase mOpenCvCameraView;
private DBhelper dbhelper;
private Button store;
private Button back;
private EditText text;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public Add_Picture() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(com.example.opencv_java_androidstudio.R.layout.activity_add__picture);
// setContentView(R.layout.activity_add__picture);
//setContentView(R.layout.activity_add__picture);
//mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.camera);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(com.example.opencv_java_androidstudio.R.id.camera);
mOpenCvCameraView.setCvCameraViewListener(this);
mOpenCvCameraView.setCameraIndex(1);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
//mOpenCvCameraView.setRotation(90);
//store= (Button) findViewById(R.id.store);
store= (Button) findViewById(com.example.opencv_java_androidstudio.R.id.store);
store.setRotation(90);
Mat test = new Mat(200, 200, CvType.CV_8UC1);
Imgproc.equalizeHist(test, test);
//mOpenCvCameraView.getDisplay();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
listframes = menu.add("Faces list");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == listframes){
viewMode = VIEW_MODE_LISTFRAMES;
// Intent intent = new Intent(AjoutframeActivity.this, ListframeActivity.class);
// startActivity(intent);
}
return true;
}
#Override
public void onPause()
{
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
}
public void onCameraViewStopped() {
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba=inputFrame.rgba();
store.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1){
storeframesiDB(mRgba);
}
});
return mRgba;
}
public void storeframesiDB(Mat mat){
MatOfKeyPoint points = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
surf.detect(mat, points);
Mat descriptors = new Mat();
extractor.compute(mat, points, descriptors);
int rows=descriptors.rows();
String str=Frametraitement.matToJson(descriptors);
dbhelper = new DBhelper(this);
//text= (EditText) findViewById(R.id.storage);
text= (EditText) findViewById(com.example.opencv_java_androidstudio.R.id.storage);
String textstore= text.getText().toString();
Frameclass fr = new Frameclass(textstore,str,rows);
text.setText("");
dbhelper.open();
dbhelper.insertframeDetails(fr);
dbhelper.close();
}
}
My Logcat shows me that : Canno't load info library for OpenCV.
And here is my class for the image's traitement :
public class Frametraitement {
private static final String TAG = "RF";
private DBhelper dbhelper;
public static Mat matRetrieve(String filePath, int rows, int cols, int type){
Log.d(TAG, "matRetrieve - path: " + filePath);
if(isExternalStorageReadable()){
File matFile = new File(filePath);
InputStream in = null;
try {
in = new FileInputStream(matFile);
byte[] data = convertInputStreamToByteArray(in);
//Mat result = new Mat(320, 212, CvType.CV_8UC1);
Mat result = new Mat(rows, cols, type);
result.put(0, 0, data);
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
Log.e(TAG, "External Storage not readable.");
}
return null;
}
public static byte[] matStore( Mat mat){
//Log.d(TAG, "matStore - path: "+filePath);
byte[] data=null;
if(isExternalStorageWritable() && mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize(); // or mat.channels() ?
data= new byte[cols * rows * elemSize];
mat.get(0, 0, data);
Log.e(TAG, "data"+ data);
Log.e(TAG, "mat"+ mat);
} else {
Log.e(TAG, "External Storage not writable.");
}
return data;
}
public static String matToJson(Mat mat){
Log.i(TAG, "matToJson");
JsonObject obj = new JsonObject();
if(mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
mat.get(0, 0, data);
obj.addProperty("rows", mat.rows());
obj.addProperty("cols", mat.cols());
obj.addProperty("type", mat.type());
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
Log.d(TAG, "matToJson - boooom: "+dataString);
obj.addProperty("data", dataString);
Gson gson = new Gson();
String json = gson.toJson(obj);
return json;
} else {
Log.e(TAG, "Mat not continuous.");
}
return "{}";
}
public static Mat matFromJson(String json){
Log.d(TAG, "matToJson");
JsonParser parser = new JsonParser();
JsonObject JsonObject = parser.parse(json).getAsJsonObject();
int rows = JsonObject.get("rows").getAsInt();
int cols = JsonObject.get("cols").getAsInt();
int type = JsonObject.get("type").getAsInt();
String dataString = JsonObject.get("data").getAsString();
byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);
Mat mat = new Mat(rows, cols, type);
mat.put(0, 0, data);
Log.e(TAG,"matfromjson"+mat);
return mat;
}
private static byte[] convertInputStreamToByteArray(InputStream inputStream) {
byte[] bytes= null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int count;
while ((count = inputStream.read(buff)) != -1) {
bos.write(buff, 0, count);
}
bos.flush();
bos.close();
inputStream.close();
bytes = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
/* Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static byte[] getBytes(String ch) {
Mat mat=matFromJson(ch);
//Log.e(TAG,"chaine"+ch);
return matStore(mat);
}
public static Mat getmatfrombyte(byte[] data, int rows, int cols) {
Mat result = new Mat(rows, cols, CvType.CV_8UC1);
result.put(0, 0, data);
return result;
}
public static Mat calculdescriptors(Mat mat){
MatOfKeyPoint points = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
surf.detect(mat, points);
int nbrepts= points.toList().size();
Mat descriptors = new Mat();
extractor.compute(mat, points, descriptors);
return descriptors;
}
public static MatOfDMatch matching(Mat matcour,Mat mattrain){
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
MatOfDMatch matches = new MatOfDMatch();
matcher.match(matcour, mattrain, matches);
matches.toList();
Log.e(TAG,"matches "+matches.toList());
return filterMatchesByDistance(matches);
}
public static MatOfDMatch filterMatchesByDistance(MatOfDMatch matches){
List<org.opencv.core.DMatch> matches_original = matches.toList();
List<org.opencv.core.DMatch> matches_filtered = new ArrayList<>();
int DIST_LIMIT = 30;
// Check all the matches distance and if it passes add to list of filtered matches
Log.d("DISTFILTER", "ORG SIZE:" + matches_original.size() + "");
for (int i = 0; i < matches_original.size(); i++) {
org.opencv.core.DMatch d = matches_original.get(i);
if (Math.abs(d.distance) <= DIST_LIMIT) {
matches_filtered.add(d);
}
}
Log.d("DISTFILTER", "FIL SIZE:" + matches_filtered.size() + "");
MatOfDMatch mat = new MatOfDMatch();
mat.fromList(matches_filtered);
return mat;
}
}