Face Recognition with OpenCv, NDK and Android - java

I was trying to run this code to take a photo and recognize tho photo owner, at first the user clicks the button Train and takes a picture than enter its name, after that he clicks on Recognize button and take a picture if the picture was saved the apps recognize its face if not it shows unknown person for example. The app runs good but when it crashes sometimes with this error:
FATAL EXCEPTION: main
Process: com.facedetection.app, PID: 7442
java.lang.RuntimeException: Unable to stop activity {com.facedetection.app/com.facedetection.app.TrainActivity}: CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.0.0-pre) E:\AssemCourses\opencv-master\modules\core\src\matrix.cpp:235: error: (-215:Assertion failed) s >= 0 in function 'setSize'
]
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4852)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4915)
at android.app.ActivityThread.access$1600(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1759)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.0.0-pre) E:\AssemCourses\opencv-master\modules\core\src\matrix.cpp:235: error: (-215:Assertion failed) s >= 0 in function 'setSize'
]
at org.opencv.face.FaceRecognizer.train_0(Native Method)
at org.opencv.face.FaceRecognizer.train(FaceRecognizer.java:133)
at com.facedetection.app.TrainActivity.trainfaces(TrainActivity.java:95)
at com.facedetection.app.TrainActivity.onStop(TrainActivity.java:351)
at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1305)
at android.app.Activity.performStop(Activity.java:6777)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4847)
Here is the classe mentionned in the error logcat:
Class TrainActivity.java:
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.stetho.Stetho;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.face.Face;
import org.opencv.face.FaceRecognizer;
import org.opencv.face.LBPHFaceRecognizer;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static org.opencv.objdetect.Objdetect.CASCADE_SCALE_IMAGE;
/**
* Created by Assem Abozaid on 6/2/2018.
*/
public class TrainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
private static String TAG = TrainActivity.class.getSimpleName();
private CameraBridgeViewBase openCVCamera;
private Mat rgba,gray;
private CascadeClassifier classifier;
private MatOfRect faces;
private static final int PERMS_REQUEST_CODE = 123;
private ArrayList<Mat> images;
private ArrayList<String> imagesLabels;
private Storage local;
private String[] uniqueLabels;
FaceRecognizer recognize;
private boolean trainfaces() {
if(images.isEmpty())
return false;
List<Mat> imagesMatrix = new ArrayList<>();
for (int i = 0; i < images.size(); i++)
imagesMatrix.add(images.get(i));
Set<String> uniqueLabelsSet = new HashSet<>(imagesLabels); // Get all unique labels
uniqueLabels = uniqueLabelsSet.toArray(new String[uniqueLabelsSet.size()]); // Convert to String array, so we can read the values from the indices
int[] classesNumbers = new int[uniqueLabels.length];
for (int i = 0; i < classesNumbers.length; i++)
classesNumbers[i] = i + 1; // Create incrementing list for each unique label starting at 1
int[] classes = new int[imagesLabels.size()];
for (int i = 0; i < imagesLabels.size(); i++) {
String label = imagesLabels.get(i);
for (int j = 0; j < uniqueLabels.length; j++) {
if (label.equals(uniqueLabels[j])) {
classes[i] = classesNumbers[j]; // Insert corresponding number
break;
}
}
}
Mat vectorClasses = new Mat(classes.length, 1, CvType.CV_32SC1); // CV_32S == int
vectorClasses.put(0, 0, classes); // Copy int array into a vector
recognize = LBPHFaceRecognizer.create(3,8,8,8,200);
recognize.train(imagesMatrix, vectorClasses);
if(SaveImage())
return true;
return false;
}
public void showLabelsDialog() {
Set<String> uniqueLabelsSet = new HashSet<>(imagesLabels); // Get all unique labels
if (!uniqueLabelsSet.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select label:");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
images.remove(images.size()-1);
}
});
builder.setCancelable(false); // Prevent the user from closing the dialog
String[] uniqueLabels = uniqueLabelsSet.toArray(new String[uniqueLabelsSet.size()]); // Convert to String array for ArrayAdapter
Arrays.sort(uniqueLabels); // Sort labels alphabetically
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, uniqueLabels) {
#Override
public #NonNull
View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
if (getResources().getBoolean(R.bool.isTablet))
textView.setTextSize(20); // Make text slightly bigger on tablets compared to phones
else
textView.setTextSize(18); // Increase text size a little bit
return textView;
}
};
ListView mListView = new ListView(this);
mListView.setAdapter(arrayAdapter); // Set adapter, so the items actually show up
builder.setView(mListView); // Set the ListView
final AlertDialog dialog = builder.show(); // Show dialog and store in final variable, so it can be dismissed by the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dialog.dismiss();
addLabel(arrayAdapter.getItem(position));
Log.i(TAG, "Labels Size "+imagesLabels.size()+"");
}
});
} else {
showEnterLabelDialog();
}
}
private void showEnterLabelDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please enter your name:");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Submit", null); // Set up positive button, but do not provide a listener, so we can check the string before dismissing the dialog
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
images.remove(images.size()-1);
}
});
builder.setCancelable(false); // User has to input a name
AlertDialog dialog = builder.create();
// Source: http://stackoverflow.com/a/7636468/2175837
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
Button mButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String string = input.getText().toString().trim();
if (!string.isEmpty()) { // Make sure the input is valid
// If input is valid, dismiss the dialog and add the label to the array
dialog.dismiss();
addLabel(string);
}
}
});
}
});
// Show keyboard, so the user can start typing straight away
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
private void addLabel(String string) {
String label = string.substring(0, 1).toUpperCase(Locale.US) + string.substring(1).trim().toLowerCase(Locale.US); // Make sure that the name is always uppercase and rest is lowercase
imagesLabels.add(label); // Add label to list of labels
Log.i(TAG, "Label: " + label);
}
public boolean SaveImage() {
File path = new File(Environment.getExternalStorageDirectory(), "TrainedData");
path.mkdirs();
String filename = "lbph_trained_data.xml";
File file = new File(path, filename);
recognize.save(file.toString());
if(file.exists())
return true;
return false;
}
public void cropedImages(Mat mat) {
Rect rect_Crop=null;
for(Rect face: faces.toArray()) {
rect_Crop = new Rect(face.x, face.y, face.width, face.height);
}
Mat croped = new Mat(mat, rect_Crop);
images.add(croped);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.train_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Stetho.initializeWithDefaults(this);
if (hasPermissions()){
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Permission Granted Before");
}
else {
requestPerms();
}
openCVCamera = (CameraBridgeViewBase)findViewById(R.id.java_camera_view);
openCVCamera.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_FRONT);
openCVCamera.setVisibility(SurfaceView.VISIBLE);
openCVCamera.setCvCameraViewListener(this);
local = new Storage(this);
Button detect = (Button)findViewById(R.id.take_picture_button);
detect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(gray.total() == 0)
Toast.makeText(getApplicationContext(), "Can't Detect Faces", Toast.LENGTH_SHORT).show();
classifier.detectMultiScale(gray,faces,1.1,3,0|CASCADE_SCALE_IMAGE, new Size(30,30));
if(!faces.empty()) {
if(faces.toArray().length > 1)
Toast.makeText(getApplicationContext(), "Mutliple Faces Are not allowed", Toast.LENGTH_SHORT).show();
else {
if(gray.total() == 0) {
Log.i(TAG, "Empty gray image");
return;
}
cropedImages(gray);
showLabelsDialog();
Toast.makeText(getApplicationContext(), "Face Detected", Toast.LENGTH_SHORT).show();
}
}else
Toast.makeText(getApplicationContext(), "Unknown Face", Toast.LENGTH_SHORT).show();
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.CAMERA};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
Log.i(TAG, "Permission has been added");
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) || shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)){
Toast.makeText(this, "Permission Denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private BaseLoaderCallback callbackLoader = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch(status) {
case BaseLoaderCallback.SUCCESS:
faces = new MatOfRect();
openCVCamera.enableView();
images = local.getListMat("images");
imagesLabels = local.getListString("imagesLabels");
break;
default:
super.onManagerConnected(status);
break;
}
}
};
#Override
protected void onPause() {
super.onPause();
if(openCVCamera != null)
openCVCamera.disableView();
}
#Override
protected void onStop() {
super.onStop();
if (images != null && imagesLabels != null) {
local.putListMat("images", images);
local.putListString("imagesLabels", imagesLabels);
Log.i(TAG, "Images have been saved");
if(trainfaces()) {
images.clear();
imagesLabels.clear();
}
}
}
#Override
protected void onDestroy(){
super.onDestroy();
if(openCVCamera != null)
openCVCamera.disableView();
}
#Override
protected void onResume(){
super.onResume();
if(OpenCVLoader.initDebug()) {
Log.i(TAG, "System Library Loaded Successfully");
callbackLoader.onManagerConnected(BaseLoaderCallback.SUCCESS);
} else {
Log.i(TAG, "Unable To Load System Library");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, this, callbackLoader);
}
}
#Override
public void onCameraViewStarted(int width, int height) {
rgba = new Mat();
gray = new Mat();
classifier = FileUtils.loadXMLS(this, "lbpcascade_frontalface_improved.xml");
}
#Override
public void onCameraViewStopped() {
rgba.release();
gray.release();
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Mat mGrayTmp = inputFrame.gray();
Mat mRgbaTmp = inputFrame.rgba();
int orientation = openCVCamera.getScreenOrientation();
if (openCVCamera.isEmulator()) // Treat emulators as a special case
Core.flip(mRgbaTmp, mRgbaTmp, 1); // Flip along y-axis
else {
switch (orientation) { // RGB image
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
Core.flip(mRgbaTmp, mRgbaTmp, 0); // Flip along x-axis
break;
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
Core.flip(mRgbaTmp, mRgbaTmp, 1); // Flip along y-axis
break;
}
switch (orientation) { // Grayscale image
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
Core.transpose(mGrayTmp, mGrayTmp); // Rotate image
Core.flip(mGrayTmp, mGrayTmp, -1); // Flip along both axis
break;
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
Core.transpose(mGrayTmp, mGrayTmp); // Rotate image
break;
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
Core.flip(mGrayTmp, mGrayTmp, 1); // Flip along y-axis
break;
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
Core.flip(mGrayTmp, mGrayTmp, 0); // Flip along x-axis
break;
}
}
gray = mGrayTmp;
rgba = mRgbaTmp;
Imgproc.resize(gray, gray, new Size(200,200.0f/ ((float)gray.width()/ (float)gray.height())));
return rgba;
}
}
The Lines of Errors mentionned in the logcat refers to those java code lines:
In TrainActivity.java:
recognize = LBPHFaceRecognizer.create(3,8,8,8,200);
recognize.train(imagesMatrix, vectorClasses);
And
if(trainfaces()) {
images.clear();
imagesLabels.clear();
}
Do you guys have any idea about this problem and how to fix it?
PS: I am a beginner with OpenCv.

You can solve it by reset preferences onCreate TrainActivity
// -------------------------------
// reset preferences
local = new Storage(this);
images = new ArrayList<>();
imagesLabels = new ArrayList<>();
local.putListMat("images", images);
local.putListString("imagesLabels", imagesLabels);
// -------------------------------

Related

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

Unable to upload pictures taken by camera

Why is my activity unable to upload pictures taken by camera while it easily uploads the picture picked from the gallery?
The picture uploaded through the gallery is available on the server but the file(picture) taken through the camera is not found on the server after the API hit.
Opening the directory on the server gives 'File not found' error for the file uploaded via camera.
Here is my code:
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import static com.app.engage.Interfaces.Keys.userDetails.*;
import com.app.engage.Interfaces.ApiResponse;
import com.app.engage.Interfaces.NetworkConnectivityListener;
import com.app.engage.R;
import com.app.engage.Utilities.ConnectionDetector;
import com.app.engage.Utilities.GetServerData;
import com.app.engage.Utilities.ImageOnlyOptionsDialog;
import com.app.engage.Utilities.ProgressDialog;
import com.app.engage.Utilities.RoleSectDialog;
import com.app.engage.Utilities.RoundCorner;
import com.app.engage.Utilities.SharedPreference_Main;
import com.app.engage.Utilities.Utilities;
import com.bumptech.glide.Glide;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import com.app.engage.Interfaces.OnButtonClicked;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SignupActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, ApiResponse.Api_hit, View.OnClickListener {
private TextView toolbarText;
public static TextView selections;
private ProgressDialog progressDialog;
private String selected_role = null;
private String selectedRole = "", selectedOrgType = "";
public static String selectedNatPriArea = "";
private ArrayList<String> role_list, org_type, nat_pri_area;
private ApiResponse apiResponse;
private ImageView dp;
private Uri uriFilePath;
private int REQUEST_CODE_CAMERA = 1002;
private int REQUEST_PICK_IMAGE = 1003;
private AlertDialog.Builder builder;
private TextView upload_dp;
private AppCompatCheckBox stayLoggedIn;
private Spinner roleSpinner, organisationTypeSpinner;
private Button signUp;
private SharedPreference_Main sharedPreference_main;
private String mCurrentPhotoPath;
// private Utilities utilities;
private TextView select_nat_pri_area;
private ConnectionDetector receiver;
private EditText fullName, email, orgName, password, reEnterPassword;
private File file = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
getWindow().setBackgroundDrawableResource(R.drawable.blurred_background); //setting background here
android.support.v7.widget.Toolbar toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
role_list = new ArrayList<>(); //arraylist that will hold the roles coming from the server
org_type = new ArrayList<>();//arraylist that will hold the roles coming from the server
nat_pri_area = new ArrayList<>();
sharedPreference_main = new SharedPreference_Main(this);
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeAsUpIndicator(R.drawable.white_back_icon_for_toolbar);
toolbarText = findViewById(R.id.toolbarText);
select_nat_pri_area = findViewById(R.id.nat_pri_areaaa);
toolbarText.setText("Sign Up");
apiResponse = new ApiResponse(this);
roleSpinner = findViewById(R.id.select_role_spinner);
organisationTypeSpinner = findViewById(R.id.organisation_type_spinner);
fullName = findViewById(R.id.full_name_editText);
email = findViewById(R.id.email_editText_signUp);
password = findViewById(R.id.pass_edit_text);
reEnterPassword = findViewById(R.id.reEnterPword);
orgName = findViewById(R.id.org_edit_text);
selections = findViewById(R.id.selectionss);
signUp = findViewById(R.id.signUp_Button);
dp = findViewById(R.id.dp);
progressDialog = new ProgressDialog(this);
select_nat_pri_area.setOnClickListener(this);
upload_dp = findViewById(R.id.upload_dp);
dp.setOnClickListener(this);
selections.setOnClickListener(this);
upload_dp.setOnClickListener(this);
// utilities = new Utilities(this);
receiver = new ConnectionDetector(new NetworkConnectivityListener() {
#Override
public void onNetworkConnected() //if network connection is available
{
if (role_list.size() <= 0 || org_type.size() <= 0 || nat_pri_area.size() <= 0) {
getData();
}
}
#Override
public void onNetworkDisconnected() {
displayAlert();
}
}, this);
// sharedPreference_main = SharedPreference_Main.getInstance(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) //initialising the AlertDialogue builder
{
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
roleSpinner.setOnItemSelectedListener(this);
organisationTypeSpinner.setOnItemSelectedListener(org_type_selection);
dp.setOnClickListener(this);
upload_dp.setOnClickListener(this);
// natPriorityAreaSpinner.setAdapter(adapterSetter(priorityArea));
signUp.setOnClickListener(this);
}
private ArrayAdapter<String> adapterSetter(ArrayList<String> data) //to temporarily populate the spinners
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.custom_spinner, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, filter);
receiver.isNetworkAvailable();
//checkConnection();
}
public void signup() {
if (!validate()) { //if the conditions in the validate function are not met return
onSignupFailed();
Toast.makeText(this, "Something went wrong sign-up failed", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(this, "signing up", Toast.LENGTH_SHORT).show();
// signUp.setEnabled(false);
progressDialog.progressDialogStart("Please Wait...");
try {
apiResponse.hitVolleyMultipartApi(this, "signup", getparams(), prof_pic, file);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
// TODO: Implement your own signup logic here.'
// save();
}
public void onSignupSuccess() //if signup is successful
{
signUp.setEnabled(true);
setResult(RESULT_OK, null);
//Toast.makeText(this, "snkflsndkfl", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, HomeActivity.class);
//i.putExtra("Back Functionality", true);
startActivity(i);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Signup failed", Toast.LENGTH_LONG).show();
signUp.setEnabled(true);
}
public boolean validate() //to check the entered information
{
boolean valid = true;
String name = fullName.getText().toString();
String mail = email.getText().toString();
String pword = password.getText().toString();
String org_Name = orgName.getText().toString();
String reEnterPword = reEnterPassword.getText().toString();
if (name.isEmpty() || name.length() < 3) {
fullName.setError("at least 3 characters", null);
valid = false;
} else {
fullName.setError(null);
}
if (mail.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(mail).matches()) {
email.setError("enter a valid email address", null);
valid = false;
} else {
email.setError(null);
}
if (org_Name.isEmpty()) {
orgName.setError("Please enter the organisation's name", null);
valid = false;
} else {
orgName.setError(null);
}
if (pword.isEmpty() || password.length() < 4 || password.length() > 10) {
password.setError("between 4 and 10 alphanumeric characters", null);
valid = false;
} else {
password.setError(null);
}
if (reEnterPword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPword.equals(pword))) {
reEnterPassword.setError("Password Do not match", null);
valid = false;
} else {
reEnterPassword.setError(null);
}
return valid;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
selectedRole = "Facilitator";
break;
case 1:
selectedRole = "Provider Administrator";
break;
case 2:
selectedRole = "Provider Executive";
break;
case 3:
selectedRole = "School PLD Administrator";
break;
case 4:
selectedRole = "MOE National Priority";
break;
case 5:
selectedRole = "Senior Leadership";
break;
case 6:
selectedRole = "Teacher";
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
AdapterView.OnItemSelectedListener org_type_selection = new AdapterView.OnItemSelectedListener() //for organisation type selection
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
selectedOrgType = "Education";
break;
case 1:
selectedOrgType = "IT";
break;
case 2:
selectedOrgType = "Medical";
break;
case 3:
selectedOrgType = "";
break;
case 4:
selectedOrgType = "";
break;
case 5:
selectedOrgType = "";
break;
case 6:
selectedOrgType = "";
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.dp:
case R.id.upload_dp:
ImageOnlyOptionsDialog imageOnlyOptionsDialog = new ImageOnlyOptionsDialog();
imageOnlyOptionsDialog.setonButtonClickListener(new OnButtonClicked() {
#Override
public void onButtonCLick(int buttonId) {
switch (buttonId) {
case R.id.btnCamera:
startCamera();
break;
case R.id.btnGallery:
pickFromGallery();
break;
default:
break;
}
}
});
imageOnlyOptionsDialog.show(getSupportFragmentManager(), ImageOnlyOptionsDialog.class.getSimpleName());
break;
case R.id.signUp_Button:
signup();
break;
case R.id.nat_pri_areaaa:
case R.id.selectionss:
Bundle data = new Bundle();
data.putStringArrayList("pri_areas", nat_pri_area);
RoleSectDialog roleSectDialog = new RoleSectDialog();
roleSectDialog.setArguments(data);
roleSectDialog.show(getSupportFragmentManager(), RoleSectDialog.class.getSimpleName());
roleSectDialog.setonButtonClickListener(new OnButtonClicked() {
#Override
public void onButtonCLick(int buttonId) {
switch (buttonId) {
case R.id.k:
break;
default:
break;
}
}
});
break;
default:
break;
}
}
public void startCamera() {
PackageManager packageManager = this.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
File mainDirectory = new File(Environment.getExternalStorageDirectory(), "MyFolder/tmp");
if (!mainDirectory.exists())
mainDirectory.mkdirs();
Calendar calendar = Calendar.getInstance();
uriFilePath = Uri.fromFile(new File(mainDirectory, "IMG_" + calendar.getTimeInMillis() + ".jpeg"));
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, uriFilePath);
startActivityForResult(intent1, REQUEST_CODE_CAMERA);
}
}
public void pickFromGallery() //this is the intent creation for picking image from gallery
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) //this receives the intent's result
{
if (requestCode == REQUEST_CODE_CAMERA) {
if (resultCode == RESULT_OK) {
try {
ExifInterface exif = new ExifInterface(uriFilePath.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
}
String filePath = getRealPathFromURI(uriFilePath);
file = new File(new URI("file://" + filePath.replace(" ", "%20")));//photo is file type that is global
Glide.with(this)
.load(file)
.placeholder(R.drawable.upload_image)
.into(dp);
// getImageDetails(photo);
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_PICK_IMAGE) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
Toast.makeText(this, selectedImagePath, Toast.LENGTH_SHORT).show();
try {
file = new File(new URI("file://" + selectedImagePath.replace(" ", "%20")));
Glide.with(this).load(file).placeholder(R.drawable.upload_image)
.into(dp);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
}
public String getRealPathFromURI(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(projection[0]);
return cursor.getString(column_index);
}
return uri.getPath();
}
public HashMap<String, String> getparams() { //parameters passed while hitting the API
HashMap<String, String> params = new HashMap<>();
params.put(rulee, "sign_up");
params.put(emaill, email.getText().toString());
params.put(word, password.getText().toString());
params.put(f_name, fullName.getText().toString());
params.put(n_p_a, selections.getText().toString());
params.put(or_name, orgName.getText().toString());
params.put(or_type, selectedOrgType);
Toast.makeText(this, selectedRole, Toast.LENGTH_SHORT).show();
params.put(rolId, selectedRole);
return params;
}
#Override
public void response(String responseObject, String method_call) //this gets the response when API is hit
{
progressDialog.dismissDialog();
try {
JSONObject response = new JSONObject(responseObject);
if (response.getString("flag").equalsIgnoreCase("success")) {
JSONObject object = response.getJSONObject("response");
sharedPreference_main.setUserName(object.getString(f_name));
sharedPreference_main.setUserEmail(object.getString(emaill));
sharedPreference_main.setUserOrganisation(object.getString(or_name));
sharedPreference_main.setUserRole(object.getString(rol));
sharedPreference_main.setOrgType(object.getString(or_type));
sharedPreference_main.setNPA(object.getString(n_p_a));
sharedPreference_main.setUserProfilePic(object.getString(prof_pic));
onSignupSuccess(); //if everything works out call the home activity
} else if (response.getString("flag").equalsIgnoreCase("0")) {
String resp = response.getString("response");
builder.setTitle("Error:"); //building up the dialog
builder.setMessage(resp);
displayAlert(resp);
} else if (response.getString("flag").equalsIgnoreCase("1")) {
// Toast.makeText(this, response.getString("flag"), Toast.LENGTH_SHORT).show();
JSONArray data = response.getJSONArray("message");
if (data.length() > 0) {
for (int i = 0; i < data.length(); i++) {
JSONObject inData = data.getJSONObject(i);
if (inData.has("role_name")) {
role_list.add(inData.getString("role_name"));
} else if (inData.has("organisation_type")) {
org_type.add(inData.getString("organisation_type"));
} else if (inData.has("prior_name")) {
nat_pri_area.add(inData.getString("prior_name"));
}
// N_P_A.add(inData.getString("prior_name"));
}
}
if (role_list.size() > 0) {
// String[] role = role_list.toArray(new String[role_list.size()]);
roleSpinner.setAdapter(adapterSetter(role_list));
}
if (org_type != null) {
// String organisationType[] =org_type.toArray(new String[org_type.size()]);
organisationTypeSpinner.setAdapter(adapterSetter(org_type));
}
// String[] priorityArea = org_type.toArray(new String[org_type.size()]);
//
}
// onSignupSuccess();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void error(String error) {
progressDialog.dismissDialog();
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
private void displayAlert(final String code) {
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
fullName.setText("");
email.setText("");
password.setText("");
orgName.setText("");
}
}).show();
}
private void displayAlert() //overloaded function
{
builder.setTitle("No internet connection");
builder.setTitle("Please switch on the internet");
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// checkConnection();
if (receiver.isNetworkAvailable()) {
dialogInterface.c**strong text**ancel();
} else {
displayAlert();
}
}
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// checkConnection();
dialogInterface.cancel();
}
}).show();
}
public void getData() {
GetServerData getServerData = new GetServerData(this);
getServerData.getRoles();
}
}
Note:
Language version - Java
Target SDK -23
Any help would be appreciated.
This was happening because the permissions were not being provided to the application while running it on the smartphone. Newer versions of Android require the apps to be granted permissions from within the smartphone.
Use this and upvote after your issue gets resolve.
private File profilePic;
private Uri photoFileUri;
/**
* Method below will work for Camera Intent.
*/
private void clickPicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = AppUtils.getInstance().createImageFile(); // Create the File where the photo should go
outputFileUri = FileProvider.getUriForFile(SignUpActivity.this, getApplicationContext().getPackageName() + ".provider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePictureIntent, CAMERA_IMAGE_REQUEST);
} catch (IOException io) {
io.printStackTrace(); // Error occurred while creating the File
}
//outputFileUri = Uri.fromFile(photoFile);//At this Uri the image captured will get saved.
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case AppConstants.MediaConstants.REQUEST_CAPTURE_IMAGE:
profilePic = new File(AppUtils.getInstance().getRealPathFromURI(photoFileUri, mActivity));
break;
}
}
}
Use this method below directly in your classs
/**
* method to get real path from uri
*
* #param contentURI
* #param context
* #return
*/
public String getRealPathFromURI(Uri contentURI, Context context) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
create "provide_paths.xml" file in folder name "xml" in res directory and add code below in it
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>

android opencv camera app hanging

I am creating an android camera app using opencv. First I make it like when I click the start button, it start taking pictures and in every second takes a picture and store it in storage. It works perfectly for me.
Then I tried to make it some tricky by forcing it to take 5 pictures in a second it works well.
But actually I faced problem when I make it to 20 pictures in 1 second. It did not work. The app hangs as soon as I click on the start button. I don't know why. But I think the problem is in threading.
Can someone help me how i will do it.
I have two java files in my project and here is the code.
package org.opencv.samples.tutorial3;
import java.io.FileOutputStream;
import java.util.List;
import org.opencv.android.JavaCameraView;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.util.AttributeSet;
import android.util.Log;
public class Tutorial3View extends JavaCameraView implements PictureCallback {
private static final String TAG = "Sample::Tutorial3View";
private String mPictureFileName;
public Tutorial3View(Context context, AttributeSet attrs) {
super(context, attrs);
}
public List<String> getEffectList() {
return mCamera.getParameters().getSupportedColorEffects();
}
public boolean isEffectSupported() {
return (mCamera.getParameters().getColorEffect() != null);
}
public String getEffect() {
return mCamera.getParameters().getColorEffect();
}
public void setEffect(String effect) {
Camera.Parameters params = mCamera.getParameters();
params.setColorEffect(effect);
mCamera.setParameters(params);
}
public List<Size> getResolutionList() {
return mCamera.getParameters().getSupportedPreviewSizes();
}
public void setResolution(Size resolution) {
disconnectCamera();
mMaxHeight = resolution.height;
mMaxWidth = resolution.width;
connectCamera(getWidth(), getHeight());
}
public Size getResolution() {
return mCamera.getParameters().getPreviewSize();
}
public void takePicture(final String fileName) {
Log.i(TAG, "Taking picture");
this.mPictureFileName = fileName;
// Postview and jpeg are sent in the same buffers if the queue is not empty when performing a capture.
// Clear up buffers to avoid mCamera.takePicture to be stuck because of a memory issue
mCamera.setPreviewCallback(null);
// PictureCallback is implemented by the current class
mCamera.takePicture(null, null, this);
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.i(TAG, "Saving a bitmap to file");
// The camera preview was automatically stopped. Start it again.
mCamera.startPreview();
mCamera.setPreviewCallback(this);
// Write the image in a file (in jpeg format)
try {
FileOutputStream fos = new FileOutputStream(mPictureFileName);
fos.write(data);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}
}
And the second one is:
package org.opencv.samples.tutorial3;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class Tutorial3Activity extends Activity implements CvCameraViewListener2 {
private static final String TAG = "OCVSample::Activity";
private Tutorial3View mOpenCvCameraView;
private List<Size> mResolutionList;
private MenuItem[] mEffectMenuItems;
private SubMenu mColorEffectsMenu;
private MenuItem[] mResolutionMenuItems;
private SubMenu mResolutionMenu;
Thread thread;
Button start,stop;
boolean loop=false;
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 Tutorial3Activity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
#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.tutorial3_surface_view);
start=(Button)findViewById(R.id.button2) ;
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loop=true;
thread = new Thread(new task());
thread.start();
}
});
stop=(Button) findViewById(R.id.button);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loop=false;
}
});
mOpenCvCameraView = (Tutorial3View) findViewById(R.id.tutorial3_activity_java_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
#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_0_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
return inputFrame.rgba();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
List<String> effects = mOpenCvCameraView.getEffectList();
if (effects == null) {
Log.e(TAG, "Color effects are not supported by device!");
return true;
}
mColorEffectsMenu = menu.addSubMenu("Color Effect");
mEffectMenuItems = new MenuItem[effects.size()];
int idx = 0;
ListIterator<String> effectItr = effects.listIterator();
while(effectItr.hasNext()) {
String element = effectItr.next();
mEffectMenuItems[idx] = mColorEffectsMenu.add(1, idx, Menu.NONE, element);
idx++;
}
mResolutionMenu = menu.addSubMenu("Resolution");
mResolutionList = mOpenCvCameraView.getResolutionList();
mResolutionMenuItems = new MenuItem[mResolutionList.size()];
ListIterator<Size> resolutionItr = mResolutionList.listIterator();
idx = 0;
while(resolutionItr.hasNext()) {
Size element = resolutionItr.next();
mResolutionMenuItems[idx] = mResolutionMenu.add(2, idx, Menu.NONE,
Integer.valueOf(element.width).toString() + "x" + Integer.valueOf(element.height).toString());
idx++;
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item.getGroupId() == 1)
{
mOpenCvCameraView.setEffect((String) item.getTitle());
Toast.makeText(this, mOpenCvCameraView.getEffect(), Toast.LENGTH_SHORT).show();
}
else if (item.getGroupId() == 2)
{
int id = item.getItemId();
Size resolution = mResolutionList.get(id);
mOpenCvCameraView.setResolution(resolution);
resolution = mOpenCvCameraView.getResolution();
String caption = Integer.valueOf(resolution.width).toString() + "x" + Integer.valueOf(resolution.height).toString();
Toast.makeText(this, caption, Toast.LENGTH_SHORT).show();
}
return true;
}
class task implements Runnable {
public void run() {
while (loop) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String currentDateandTime = sdf.format(new Date());
final String fileName = Environment.getExternalStorageDirectory().getPath() +
"/sample_picture_" + currentDateandTime + ".jpg";
mOpenCvCameraView.takePicture(fileName);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Tutorial3Activity.this, fileName + " saved", Toast.LENGTH_SHORT).show();
}
});
try {
thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Note: The above code works well for taking 5 pictures in 1 second. But when I change thread.sleep(200) to thread.sleep(50) for taking 20 pictures in 1 second it hangs.

java.lang.NoClassDefFoundError: rx.subjects.PublishSubject

I've added Adobe creative SDK into my project and now im getting an error when im trying to move to Edit image function.
FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: rx.subjects.PublishSubject
at com.adobe.creativesdk.aviary.internal.account.AdobeAccountConnection.<init>(AdobeAccountConnection.java:45)
at com.adobe.creativesdk.aviary.AdobeImageEditorActivity.onCreate(AdobeImageEditorActivity.java:517)
at android.app.Activity.performCreate(Activity.java:5268)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
at android.app.ActivityThread.access$600(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1259)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:740)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)
I went through the documentations but i've no idea why im getting this error
i have attached my code
package com.sliit.dailyselfie.Camera;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
import com.bumptech.glide.Glide;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import com.sliit.dailyselfie.R;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import rebus.bottomdialog.BottomDialog;
public class CameraActivity extends AppCompatActivity {
private static final int ActivityStartCAM=0;
private final static int EDIT_IMAGE=1;
private ImageView IV;
private String ImageFileLoaction="";
BottomBar CamBottomBar;
ImageButton bcan,bsnap,bdesc;
Dialog d;
BottomDialog dialog;
String challenge;
Bundle extras;
boolean picpresent=false;
Uri ImageUri;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
IV = (ImageView)findViewById(R.id.snap1);
IV.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (picpresent) {
dialog = new BottomDialog(CameraActivity.this);
dialog.title("Options");
dialog.canceledOnTouchOutside(true);
dialog.cancelable(true);
dialog.inflateMenu(R.menu.camera_bottomsheet_menu);
dialog.setOnItemSelectedListener(new BottomDialog.OnItemSelectedListener() {
#Override
public boolean onItemSelected(int id) {
switch (id) {
case R.id.addeffects:
image();
return true;
case R.id.crop:
Toast.makeText(getApplicationContext(),"crop",Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
dialog.show();
}
return true;
}
});
extras = getIntent().getExtras();
if (extras != null) {
challenge = extras.getString("Challenge");
}
CamBottomBar = BottomBar.attach(this, savedInstanceState);
CamBottomBar.noNavBarGoodness();
CamBottomBar.setItemsFromMenu(R.menu.camera_bottombar, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.nav_back) {
IV.setImageResource(R.drawable.selfieimage);
IV.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
picpresent = false;
} else if (menuItemId == R.id.nav_takeSnap) {
Intent CAMint= new Intent();
CAMint.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile=null;
try{
photoFile=createImageFile();
}catch(IOException e){
e.printStackTrace();
}
CAMint.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(CAMint, ActivityStartCAM);
} else if (menuItemId == R.id.nav_addDetails) {
if (picpresent) {
switch (challenge) {
case "fitness":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.fitnessdialog);
ImageView fitim = (ImageView) d.findViewById(R.id.fitdialogimg);
TextView fittxt = (TextView) d.findViewById(R.id.fitdialogdesc);
d.show();
break;
case "maternity":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.maternitydialog);
ImageView matimg = (ImageView) d.findViewById(R.id.matdialogimg);
TextView mattxt = (TextView) d.findViewById(R.id.matdialogdesc);
d.show();
break;
case "child":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.childdialog);
ImageView chilimg = (ImageView) d.findViewById(R.id.childialogimg);
TextView chiltxt = (TextView) d.findViewById(R.id.childialogdesc);
d.show();
break;
}
}else{
Toast.makeText(CameraActivity.this, "Please select image", Toast.LENGTH_SHORT).show();
}
}
//
// CamBottomBar.mapColorForTab(0, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(1, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(2, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.nav_back) {
IV.setImageResource(R.drawable.selfieimage);
IV.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
picpresent = false;
} else if (menuItemId == R.id.nav_takeSnap) {
Intent CAMint = new Intent();
CAMint.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
CAMint.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(CAMint, ActivityStartCAM);
} else if (menuItemId == R.id.nav_addDetails) {
if (picpresent) {
switch (challenge) {
case "fitness":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.fitnessdialog);
ImageView fitim = (ImageView) d.findViewById(R.id.fitdialogimg);
TextView fittxt = (TextView) d.findViewById(R.id.fitdialogdesc);
d.show();
break;
case "maternity":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.maternitydialog);
ImageView matimg = (ImageView) d.findViewById(R.id.matdialogimg);
TextView mattxt = (TextView) d.findViewById(R.id.matdialogdesc);
d.show();
break;
case "child":
d = new Dialog(CameraActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.childdialog);
ImageView chilimg = (ImageView) d.findViewById(R.id.childialogimg);
TextView chiltxt = (TextView) d.findViewById(R.id.childialogdesc);
d.show();
break;
}
}else{
Toast.makeText(CameraActivity.this, "Please select image", Toast.LENGTH_SHORT).show();
}
}
//
// CamBottomBar.mapColorForTab(0, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(1, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
// CamBottomBar.mapColorForTab(2, ContextCompat.getColor(CameraActivity.this, R.color.bottomPrimary));
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
rotateImage(setReducedImageSize());
IV.setScaleType(ImageView.ScaleType.CENTER_CROP);
if(!picpresent){
IV.setImageResource(R.drawable.selfieimage);
IV.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
}
public void TakePhoto(View v){
Intent CAMint= new Intent();
CAMint.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile=null;
try{
photoFile=createImageFile();
}catch(IOException e){
e.printStackTrace();
}
CAMint.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(CAMint, ActivityStartCAM);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==ActivityStartCAM && resultCode==RESULT_OK){
rotateImage(setReducedImageSize());
ImageUri = Uri.parse(ImageFileLoaction);
IV.setScaleType(ImageView.ScaleType.CENTER_CROP);
picpresent=true;
}
if (resultCode == RESULT_OK && requestCode==EDIT_IMAGE) {
/* Make a case for the request code we passed to startActivityForResult() */
/* Show the image! */
Uri editedImageUri = data.getData();
ImageUri=data.getData();
Glide.with(this).load(editedImageUri).into(IV);
picpresent=true;
}
}
File createImageFile()throws IOException{
String timestamp= new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFieldname="IMAGE "+timestamp+"_";
File storageDeirectory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image=File.createTempFile(imageFieldname,".jpg",storageDeirectory);
ImageFileLoaction=image.getAbsolutePath();
return image;
}
private Bitmap setReducedImageSize(){
int taretimagevieweidth=IV.getWidth();
int targetimageviewheight=IV.getHeight();
BitmapFactory.Options bmfop= new BitmapFactory.Options();
bmfop.inJustDecodeBounds=true;
BitmapFactory.decodeFile(ImageFileLoaction,bmfop);
int Cameraheight=bmfop.outHeight;
int Camerawidth=bmfop.outWidth;
int scalefactor =Math.min(Camerawidth/taretimagevieweidth,Cameraheight/targetimageviewheight);
bmfop.inSampleSize=scalefactor;
bmfop.inJustDecodeBounds=false;
return BitmapFactory.decodeFile(ImageFileLoaction,bmfop);
}
private void rotateImage(Bitmap bitmap){
ExifInterface exifInterface = null;
try{
exifInterface = new ExifInterface(ImageFileLoaction);
}catch(Exception e){
e.printStackTrace();
}
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
default:
}
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
IV.setImageBitmap(rotatedBitmap);
}
public void image(){
/* 1) Make a new Uri object (Replace this with a real image on your device) */
Uri imageUri = ImageUri;
/* 2) Create a new Intent */
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
.setData(imageUri)
.build();
/* 3) Start the Image Editor with request code 1 */
startActivityForResult(imageEditorIntent,EDIT_IMAGE);
}
}
This is because you are using a version of Android 4.x, and the MultiDex is not correctly implemented. I solved this problem following the next steps:
Add the following lines in module.gradle
defaultConfig { multiDexEnabled true }
compile 'com.android.support:multidex:1.0.1'
Extend the class application from MultiDexApplication
Example:
public class Globalapplication extends MultiDexApplication implements IAviaryClientCredentials {...}
override attachBaseContext in the previous class
Example:
#Override
protected void attachBaseContext(Context base) {
MultiDex.install(this);
super.attachBaseContext(base);
}
for more information read:
NoClassDefFoundError with Android Studio on Android 4
https://developer.android.com/studio/build/multidex.html
According to Oracle documentation,
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
So, Definition of rx.subjects.PublishSubject is not found...
look at the packages it seems somehow you are not able to access the rx.subjects.PublishSubject package or is missing. make sure you are importing rx.subjects.*;

Syntax error on token "(", delete this token

I'm working on an app for my last year of A-Levels and I'm trying to make a colour averager. I can make the app take the picture and display it in an imageView but I can't seem to get the pixels from the image. I've tried using "imageViewName".getPixels or anything else .getPixels but the brackets after getPixels have the error "Syntax error on token "(", delete this token" and the same for the end bracket. The error occurs here: photoViewForCrop.getPixels(pixels[], x, y, imageWidth, imageHeight); Which is quite close to the end of the code.
Here's my activity that takes the photo and saves it to the SD card, please ignore that it's called 'UploadPhotoActivity', not sure what I was thinking.
Imports or ints that aren't used in the code were added by my teacher when he was messing with it and not helping at all.
package com.colours.javerager;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class UploadPhotoActivity extends Activity {
//Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
//directory for file names
private static final String IMAGE_DIRECTORY_NAME = "JAverager";
private Uri fileUri; //file url to store
private ImageView photoViewForCrop;
private Button takePhotoButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photo);
// Show the Up button in the action bar.
//setupActionBar();
ActionBar actionBar = getActionBar();
// hide the action bar
actionBar.hide();
photoViewForCrop = (ImageView) findViewById(R.id.photoViewForCrop);
takePhotoButton = (Button) findViewById(R.id.takePhotoButton);
/**
* Capture image button click event
*/
takePhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
//checks if device has a camera
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
photoViewForCrop.setVisibility(View.VISIBLE);
// bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 2;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
photoViewForCrop.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "JAverager_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
int imageWidth = 640;
int imageHeight = 480;
int[] pixels = new int[307200];
int x = 1;
int y = 1;
photoViewForCrop.getPixels(pixels[], x, y, imageWidth, imageHeight);
int pixelTotal= 307200;
int valuethispixel;
int currentBlue;
int currentRed;
int currentGreen;
int totalBlue = 0;
int totalRed = 0;
int totalGreen = 0;
int currentPixel = 1;
int tempNum;
int avRed;
int avGreen;
int avBlue;
{
while(1 < pixelTotal){
tempNum = (Integer) pixels[currentPixel];
currentBlue = Color.blue(tempNum);
currentRed = Color.red(tempNum);
currentGreen = Color.green(tempNum);
totalBlue = totalBlue + currentBlue;
totalRed = totalRed + currentRed;
totalGreen = totalGreen + currentGreen;
currentPixel = currentPixel + 1;
}
totalBlue = totalBlue / pixelTotal;
totalRed = totalRed / pixelTotal;
totalGreen = totalGreen / pixelTotal;
}
};
ImageView does not implement the functionality you want.
Perhaps you should look at PixelGrabber ( http://docs.oracle.com/javase/7/docs/api/java/awt/image/PixelGrabber.html
everything after the getOutputMediaFile method is not inside a method, thats why your method call and after that the while loop definition won't work

Categories