How to directly upload images to server without click button? - java

Hye.I'm doing apps that comparing two faces between image in ID Card and live capture face image.User capture image of ID card at UploadActivity.Then,front camera at LivenessActivity will be prompted to capture face image.Then UploadActivity will automatically appear along with both images that were captured.User need to click button "verify" and it will show progress bar and upload the images to server to compare them.But,what code I have to put so that it can upload both images to the server without clicking the "verify" button?Perhaps after images appear at UploadActivity,it will directly show progress bar and upload the images to the server .This is my code for your references.Thank you in advance.
UploadActivity:
btnCaptureId.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
captureImage();
}
});
// boolean flag to identify the media type, image or video
final boolean isImage = i.getBooleanExtra("isImage",true);
previewMedia(isImage);
if (fileUri != null )
{
//go to LivenessActivity to caoture image of face
Intent intent = new Intent(this, LivenessActivity.class);
startActivityForResult(intent, 2);
}
btnverify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// uploading the file to server
try {
new UploadFileToServer(Config.IMAGE_DOC, Config.IMAGE_FACE).execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
LivenessActivity:
#Override
public Detector.DetectionType onDetectionSuccess(DetectionFrame validFrame) {
FaceIDDataStruct dataStruct = mDetector.getFaceIDDataStruct();
if (dataStruct != null) {
face = dataStruct.images.get("image_best");
Intent returnIntent = new Intent();
returnIntent.putExtra("image_best",face);
//result go to UploadActivity
setResult(UploadActivity.PAGE_INTO_LIVENESS, returnIntent);
finish();
}
if (face == null) {
face = validFrame.getCroppedFaceImageData();
}
//do something with liveness face
return DetectionType.DONE;
}

button.performClick(); to click programmatically

This is the code that I add to make it automatically upload without click button.
#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
// launching upload activity
launchUploadActivity(true);
} 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();
}
}
if (requestCode == 2) {
if (resultCode == PAGE_INTO_LIVENESS) {
Bundle extras = getIntent().getExtras();
byte[] face = extras.getByteArray("image_best");
viewImage();
//automatically upload to server
try {
new UploadFileToServer(Config.IMAGE_DOC, Config.IMAGE_FACE).execute();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
}
}
}

Just Follow the steps
After set/show the image on imageview, start server call to upload it.
show progress dialog until the uploading finished

Related

Android: cannot get values using .getStringExtra

I'll just go straight to the problem. In UploadNotesActivity.java....
First, I pick a .pdf file using intent
chooseNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// Start the Intent
startActivityForResult(intent, RESULT_LOAD_FILE);
}
});
and then, in `onActivityResult, I save the filePath of the picked file.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK && data != null) {
data.putExtra("filePath", data.getData().getPath());
choosenFile.setText(data.getStringExtra("filePath"));
} else {
Toast.makeText(this, "Error in choosing file",
Toast.LENGTH_LONG).show();
}
}
click Upload button to start upload the file
uploadNotesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onUploadButtonClick();
}
});
the onUploadButtonClick()
private void onUploadButtonClick() {
final String serverUrlString = "http://XXXX/uploadNotes.php";
if (getIntent().getStringExtra("filePath").isEmpty()) {
Log.d(TAG, "filePath is null");
} else {
Log.d(TAG, getIntent().getStringExtra("filePath"));
}
final String fileToUploadPath = getIntent().getStringExtra("filePath");
final String paramNameString = "uploaded_file";
String fileName[] = fileToUploadPath.split("/");
final MultipartUploadRequest request =
new MultipartUploadRequest(this, UUID.randomUUID().toString(), serverUrlString);
request.addFileToUpload(fileToUploadPath, paramNameString,
fileName[fileName.length-1]+".pdf", ContentType.APPLICATION_OCTET_STREAM);
request.setNotificationConfig(R.drawable.ic_launcher,
getString(R.string.app_name),
getString(R.string.uploading),
getString(R.string.upload_success),
getString(R.string.upload_error),
false);
// if you comment the following line, the system default user-agent will be used
request.setCustomUserAgent("UploadServiceDemo/1.0");
// set the intent to perform when the user taps on the upload notification.
// currently tested only with intents that launches an activity
// if you comment this line, no action will be performed when the user taps
// on the notification
// request.setNotificationClickIntent(new Intent(this, MainActivity.class));
// set the maximum number of automatic upload retries on error
request.setMaxRetries(2);
try {
request.startUpload();
} catch (Exception exc) {
Toast toast = Toast.makeText(getApplicationContext(), "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_LONG);
toast.show();
}
}
But the problem is, it will throw null pointer exception, which I don't quite get the reason.
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.onUploadButtonClick(UploadNotesActivity.java:73)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.access$100(UploadNotesActivity.java:19)
at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity$2.onClick(UploadNotesActivity.java:53)
line 73: if (getIntent().getStringExtra("filePath").isEmpty())
line 19: public class UploadNotesActivity extends Activity
line 53: onUploadButtonClick();
Seems like the filePath in line 73 is empty and the way I save filePath into bundle (?) is incorrect. How to get the filePath from onActivityResult? Here's the .java class, just in case. Thank you in advance. Really need your help.
An Intentobject is used to pass params between activities. Ones you receives the file path you must to keep it in your activity.
Create a filePathvariable inside your activity, set it on onActivityResult and read it on onUploadButtonClick.
Notice that must save variable value during the onSaveInstanceState callback and restore it in onCreate because every time you turn your phone the activity is destroyed and recreated. Check this for more information: Recreating an Activity

Allow user to choose an image from their gallery to upload to imageview in an activity?

I am not sure what to search for, I have tried a few things but have not found what I need. Basically I have a default image for my app that is the logo displaying in an imageview. I have and "admin" activity where the user will be able to customize the app further. How would I allow them to change from my default logo to one of their choice and display it in the same imageview on the mainactivity (separate from where they choose it, the admin activity)??
Thanks much!
On click of button we will trigger following code:
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
On ActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try {
String path = "";
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
Log.d("image selected path", imageUri.getPath());
System.out.println("image selected path"
+ imageUri.getPath());
path = getRealPathFromURI(EditProfileMemberActivity.this,
imageUri);
}
//DO other stuff
}
} catch (Exception e) {
System.out.println(e);
}
}

ActivityNotFoundException when trying to start activity from an intent returned by Action.PICK_ACTIVITY

I am working on an application that associates "gestures" with activities (like Dolphin Browser do with urls). What I want to do is to allow the users to select an activity with Action.PICK_ACTIVITY :
Intent data = new Intent(Intent.ACTION_MAIN);
data.addCategory(Intent.CATEGORY_LAUNCHER);
Intent intent = new Intent(Intent.ACTION_PICK_ACTIVITY);
intent.putExtra(Intent.EXTRA_INTENT, data);
startActivityForResult(intent, PICK_ACTIVITY);
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_ACTIVITY && resultCode == RESULT_OK) {
Gesture gesture = new Gesture();
gesture.intent = data;
Intent intent = new Intent(this, GestureEditorActivity.class);
intent.putExtra("com.example.gesture.Gesture",gesture.toByteArray());
startActivity(intent);
}
}
And then, when the user draw the associated gesture, I start the activity :
Intent intent = GestureList.getInstance(getApplicationContext()).getIntentForGesture(gesture);//intent corresponds to data in onActivityResult method
if(intent != null)
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
Toast.makeText(this, R.string.unrecognized_gesture, Toast.LENGTH_LONG).show();
But I got an ActivityNotFoundException :
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.MAIN dat=#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;component=com.android.calculator2/.Calculator;end }
Here is my getIntentForGesture method :
public Intent getIntentForGesture(Gesture gesture)
{
float bestDist = Float.MAX_VALUE;
Gesture bestGesture = null;
for(Gesture g:this)
{
float dist = gesture.distance(g);
if(dist < bestDist)
{
bestDist = dist;
bestGesture = g;
}
}
if(bestGesture != null)
return bestGesture.intent;
else
return null;
}
Sorry for my broken English and thanks in advance for your answers
You have to add FLAG_ACTIVITY_NEW_TASK flag to your intent
Intent intent = GestureList.getInstance(getApplicationContext()).getIntentForGesture(gesture);//intent corresponds to data in onActivityResult method
if (intent != null) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(this, R.string.unrecognized_gesture, Toast.LENGTH_LONG).show();
}
The Calculator activity can't be found. Probably a problem in your manifest file, so you can try:
Option #1:
Check everything is well written. The error message states:
No Activity found to handle Intent { act=android.intent.action.MAIN dat=#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;component=**com.android.calculator2/.Calculator**;end }
That slash / may be the error.
OPTION #2:
The key in your case is that you are trying to open an activity from another package (in this particular gesture, the calculator), so you could try checking if you can launch the calculator app like this:
Intent calcInt = new Intent();
calcInt.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
startActivity(calcInt);
If the calculator doesn't launch with this simple code, then I would bet the device doesn't have the default calculator installed.
OPTION #3:
Post your Android Manifest file so we can check it.

Take picture from Camera Intent and overlay another small image on it

I have an app that right now opens up the camera at the click of a button. Then the user can take the picture with the standard camera app which leads to a Cancel/Save option. If cancel if chosen, the picture can be taken again. If the Save option is chosen the image is saved to the Gallery. I want to add some stuff to the image in this Cancel/Save mode before either are clicked.
I think the best way to do this would be to bring the photo into my app and do my modifications there and save with a button. I have no idea how to do this. I know I have to use the onActivityResult function, but thats about it.
Any advice is appreciated.
When you launch the IMAGE_CAPTURE intent to let the user take a photo, you should pass as parameter the path where you store the image.
First you should save the path of the taken picture, then, when the user come back to your activity, manage the bitmap and combine with other elements.
camera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
long time = System.currentTimeMillis();
File root = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File dir = new File(root.getAbsolutePath() + "/Camera");
if (dir.exists() == false) {
dir.mkdirs();
}
String path = dir.getAbsolutePath() + File.separatorChar
+ time + ".jpg";
filesaved = new File(path);
try {
if (filesaved.exists() == false) {
filesaved.getParentFile().mkdirs();
filesaved.createNewFile();
}
} catch (IOException e) {
Toast.makeText(
context,
"Unable to create external file"
+ storageState, Toast.LENGTH_LONG).show();
return;
}
uritopass = Uri.fromFile(filesaved);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uritopass);
startActivityForResult(intent, TAKE_PICTURE);
} else {
Toast.makeText(
context,
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState, Toast.LENGTH_LONG).show();
}
}
});
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PICTURE) {
//user took a photo
File imageFile = new File(filesaved.toString());
Bitmap bm = decodeFile(imageFile);
if (bm != null) {
bm = combineImages(bm);
img.setImageBitmap(bm);
}
}
}
}
...
decodefile method to load the Bitmap from the original file Here.
combineImages method to combine 2 or more Bitmap Here .

Building a Camera App - Receive

I am new to Android programming and I'm writing an application in Java that opens the camera take a photo and save it. I made it via Intents but I can't see onActivityResult running.
I have tested it into my phone (Samsung Galaxy S) and when I take the photo I receive a preview of that photo having two buttons one Save and the other Cancel. I haven't added something to my code to do this so I think it's something that camera does. I want after capturing the image to run onActivityResult (after I press the Save button on the preview).
But how I'm going to return a result to start onActivityResult after pressing the Button Save on the preview?
I FORGOT to tell that after i press save my entire app is terminated.
Here is my Code
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TakePicButton = (Button) findViewById(R.id.TakePicture);
TakePicButton.setOnClickListener((android.view.View.OnClickListener) this);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.TakePicture){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
try the below code, you will have to modify it a bit, it will help you get From Library and From Camera both, the SELECT_PICTURE is used for getting image from library
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
myFile = new File(selectedImagePath);
else if (filemanagerstring != null)
myFile = new File(filemanagerstring);
if (myFile != null) {
Bitmap bmp_fromGallery = decodeImageFile(selectedImagePath);
break;
case CAMERA_REQUEST:
Bitmap bmp_Camera = (Bitmap) data.getExtras().get("data");
break;
default:
break;
}
}

Categories

Resources