So I'm working on a project where I take in an image from either gallery or camera and get a series of statistics from the image (brightness, contrast, sharpness, etc). Currently I have this working from gallery. I can open gallery, pull an image, and if a face is detected it will be cropped in a 2nd imageview. The stats are gathered from the cropped image ( see showimage(bitmap) in the gallery button area ). I've been struggling for the last week trying to get the same thing to work from the camera.
I'm currently using the following open source projects for getting the image from gallery and for cropping the face from the image:
https://github.com/hanscappelle/SO-2169649
https://github.com/lafosca/AndroidFaceCropper
I've made some advancements, and then backtracked a lot because I think I was trying to do it wrong. Here is my current working code for JUST gallery:
public class MainActivity extends AppCompatActivity {
// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_SINGLE_PICTURE = 101;
public static final String IMAGE_TYPE = "image/*";
/* Get the reference to the text label */
TextView label = null;
private ImageView selectedImagePreview;
private ImageView imageViewFace;
void showImage(Bitmap image)
{
/* Get the starting time */
long startTime = 0;
startTime = System.nanoTime();
/* Get the image statistics */
ImageStats imageStats = new ImageStats(image);
System.out.println("Execution time: " + (((double)(System.nanoTime() - startTime))/1000000000.0) + " seconds!");
/* Get the image statistics */
double[] stats = imageStats.getStats();
/* Decide whether or not the image is of good quality */
String results = imageStats.result;
/* Create the labels */
String[] labels = new String[]{"Standard Luminosity: ", "Contrast: ", "Face orientation: ", "Sharpness: "};
/* The string of statistics */
StringBuffer strStatsBuff = new StringBuffer();
/* Go through all the statistics */
for(int statIndex = 0; statIndex < stats.length; ++statIndex)
{
/* Add the statistics */
strStatsBuff.append(labels[statIndex]);
strStatsBuff.append(String.valueOf(stats[statIndex]));
strStatsBuff.append("\n");
}
/* Add the file name */
strStatsBuff.append("\n");
strStatsBuff.append(results);
/* Set the label and show the cropped image */
label.setText(strStatsBuff.toString());
FaceCropper mFaceCropper = new FaceCropper();
mFaceCropper.setEyeDistanceFactorMargin(0);
image = mFaceCropper.getCroppedImage(image);
imageViewFace.setImageBitmap(image);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// no need to cast to button view here since we can add a listener to any view, this
// is the single image selection
label = (TextView)findViewById(R.id.label);
findViewById(R.id.buttonGallery).setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType(IMAGE_TYPE);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select image"), SELECT_SINGLE_PICTURE);
}
});
selectedImagePreview = (ImageView)findViewById(R.id.imageView1);
imageViewFace = (ImageView)findViewById(R.id.imageViewFace);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_SINGLE_PICTURE) {
Uri selectedImageUri = data.getData();
try {
Bitmap bitmap;
selectedImagePreview.setImageBitmap(new UserPicture(selectedImageUri, getContentResolver()).getBitmap());
bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImageUri));
showImage(bitmap);
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), "Failed to load image", e);
e.printStackTrace();
}
}
} else {
// report failure
Toast.makeText(getApplicationContext(),"failed to get intent data", Toast.LENGTH_LONG).show();
Log.d(MainActivity.class.getSimpleName(), "Failed to get intent data, result code is " + resultCode);
}
}
}
My "closest to working" method pulled an image from the camera, but both the original imageview and the imageview that should have been cropped to face both just showed the original image.
I had the following included under oncreate -
findViewById(R.id.buttonCamera).setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0 ){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
and this included in onactivityresult -
else if (requestCode==CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
selectedImagePreview.setImageBitmap(bitmap);
showImage(bitmap);
}
Welcome to any suggestions! If you need any more info or I haven't provided something obvious, let me know. I'm new to stackoverflow, java, and android. Thanks!
I have a solution now. If anyone needs to do the same or similar here's what mine looks like:
public class MainActivity extends AppCompatActivity {
// this is the action code we use in our intent,
// this way we know we're looking at the response from our own action
private static final int SELECT_SINGLE_PICTURE = 101;
private static final int CAMERA_REQUEST = 102;
public static final String IMAGE_TYPE = "image/*";
private final int RequestCode = 20;
Uri mImageCaptureUri1;
/* Get the reference to the text label */
TextView label = null;
ImageView selectedImagePreview;
ImageView imageViewFace;
void showImage(Bitmap image)
{
imageViewFace.setImageBitmap(null);
FaceCropper mFaceCropper = new FaceCropper();
mFaceCropper.setMaxFaces(1);
mFaceCropper.setEyeDistanceFactorMargin(0);
image = mFaceCropper.getCroppedImage(image);
String faceFound;
if (mFaceCropper.faceDetected==true){
faceFound = "Face Detected!";
}else faceFound ="No face detected!";
/* Get the starting time */
long startTime = 0;
startTime = System.nanoTime();
/* Get the image statistics */
ImageStats imageStats = new ImageStats(image);
System.out.println("Execution time: " + (((double)(System.nanoTime() - startTime))/1000000000.0) + " seconds!");
/* Get the image statistics */
double[] stats = imageStats.getStats();
/* Decide whether or not the image is of good quality */
String results = imageStats.result;
/* Create the labels */
String[] labels = new String[]{"Standard Luminosity: ", "Contrast: ", "Face orientation: ", "Sharpness: "};
/* The string of statistics */
StringBuffer strStatsBuff = new StringBuffer();
/* Go through all the statistics */
for(int statIndex = 0; statIndex < stats.length; ++statIndex)
{
/* Add the statistics */
strStatsBuff.append(labels[statIndex]);
strStatsBuff.append(String.valueOf(stats[statIndex]));
strStatsBuff.append("\n");
}
/* Add the file name */
strStatsBuff.append(faceFound);
/* Set the label and show the cropped image */
label.setText(strStatsBuff.toString());
if (mFaceCropper.faceDetected == true)
{
imageViewFace.setImageBitmap(image);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// no need to cast to button view here since we can add a listener to any view, this
// is the single image selection
label = (TextView)findViewById(R.id.label);
findViewById(R.id.buttonGallery).setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType(IMAGE_TYPE);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select image"), SELECT_SINGLE_PICTURE);
}
});
findViewById(R.id.buttonCamera).setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0 ){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri1);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
selectedImagePreview = (ImageView)findViewById(R.id.imageView1);
imageViewFace = (ImageView)findViewById(R.id.imageViewFace);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_SINGLE_PICTURE) {
Uri selectedImageUri = data.getData();
try {
Bitmap bitmap;
selectedImagePreview.setImageBitmap(new UserPicture(selectedImageUri, getContentResolver()).getBitmap());
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImageUri));
selectedImagePreview.setImageBitmap(bitmap);
showImage(bitmap);
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), "Failed to load image", e);
e.printStackTrace();
}
}
else if (requestCode==CAMERA_REQUEST){
try {
Bitmap bitmap;
selectedImagePreview.setImageBitmap(new UserPicture(mImageCaptureUri1, getContentResolver()).getBitmap());
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageCaptureUri1));
selectedImagePreview.setImageBitmap(bitmap);
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
showImage(bitmap);
} catch (IOException e) {
Log.e(MainActivity.class.getSimpleName(), "Failed to load image", e);
e.printStackTrace();
}
}
}
else {
// report failure
Toast.makeText(getApplicationContext(),"failed to get intent data", Toast.LENGTH_LONG).show();
Log.d(MainActivity.class.getSimpleName(), "Failed to get intent data, result code is " + resultCode);
}
}
}
Related
I need to access the specific folder depending on the name of the created project. In Main_Activity the name of this project is filled and new folder is created. Thus, Camera_Activity saves the photos taken in that folder. Next I access Gallery_Activity, but it never goes to the folder of the created project. How can I access to that folder?
An example: Name of the created folder: Proj_1, but user select the photos from another one that opens by default, the uri that comes out is:
content://com.android.externalstorage.documents/document/primary%3APictures%2FCaptures_Camera2%2FProj_aa%2Fpic_040621_110254.jpeg
Part of AndroidManifest.xml
...
<uses-feature android:name="android.hardware.camera2.full" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
...
MainActivity.java
...
createNewProject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Coge el nombre de EditText, crea nueva carpeta y empieza la captura de las imagenes
if(newName.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(), "Please, fill in the field.", Toast.LENGTH_LONG).show();
} else {
name = newName.getText().toString();
GlobalVariables.ProjectName = name;
Intent intent = new Intent(MainActivity.this, Camera_Activity.class);
startActivity(intent);
}
}
});
...
Camera_Activity.java takes the necessary photos, saves them and has a button to enter the gallery:
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mTextureView = findViewById(R.id.camera_preview);
btn_take_pic = findViewById(R.id.button_take_photo);
acceptButton = findViewById(R.id.btn_ok);
cancelButton = findViewById(R.id.btn_cancel);
btn_gallery = findViewById(R.id.go_to_gallery);
imagePreview = findViewById(R.id.image_view_photo_preview);
...
// File name to save the picture
// First is getting the new project name from previous Activity:
String newProjName = GlobalVariables.ProjectName;
// Creating part of the name for image: timestamp. That will be: pic_tamestamp.jpeg
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("ddMMyy_HHmmss").format(new Date());
directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Captures_Camera2/Proj_" + newProjName);
GlobalVariables.MyDirectoryPath = directory.getPath();
if (!directory.exists() || !directory.isDirectory())
directory.mkdirs();
mFile = new File(directory, "pic_" + timestamp + ".jpeg");
pathToFile = mFile.getPath();
....
// ------------ GO TO GALLERY ---------
btn_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "You are going to Gallery...");
Intent GalleryIntent = new Intent(context, Gallery_Activity.class);
startActivity(GalleryIntent);
}
});
// ------------ SAVE PHOTO TO THE GALLERY ---------
acceptButton.setOnClickListener(new View.OnClickListener() {//26
#Override
public void onClick(View v) {
Toast.makeText(context, "Image saved to " + pathToFile, Toast.LENGTH_LONG).show();
// Recreating the activity with a new instance
recreate();
}
});
...
Gallery_Activity.java
public class Gallery_Activity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = "GalleryActivity";
private final Context context = this;
private ImageView imageView1, imageView2;
private final int CODE_IMAGE_GALLERY_FIRST = 1;
private final int CODE_IMAGE_GALLERY_SECOND = 2;
private final int CODE_MULTIPLE_IMAGES_GALLERY = 3;
// Variables to check the name
private String directoryPath;
private String MyPath1 = null;
private String MyPath2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Keeping the screen on even when there is no touch interaction
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_gallery);
imageView1 = findViewById(R.id.imageView1);
// If you make a short click in the ImageView, you can choose only one image, if it is long click, you can choose two images
imageView1.setOnClickListener(this);
imageView1.setOnLongClickListener(this);
imageView2 = findViewById(R.id.imageView2);
imageView2.setOnClickListener(this);
imageView2.setOnLongClickListener(this);
directoryPath = GlobalVariables.MyDirectoryPath;
Log.d(TAG, " The path from Camera_Activity is: " + directoryPath); // /storage/emulated/0/Pictures/Captures_Camera2/Proj_*
chooseMultipleImages();
}
private void chooseMultipleImages() {
// TODO: here it does NOT enter the giving folder although using the path
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting two images.."), CODE_MULTIPLE_IMAGES_GALLERY);
}
....
public void processImages(View view) {
//Toast.makeText(context, "Going to detect features...", Toast.LENGTH_SHORT).show();
Intent processIntent = new Intent(context, ImageProcessing.class);
startActivity(processIntent);
finish();
}
#Override
public boolean onLongClick(View v) {
recreate();
return false;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageView1){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting first image.."), CODE_IMAGE_GALLERY_FIRST);
}
else if(v.getId() == R.id.imageView2){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting second image.."), CODE_IMAGE_GALLERY_SECOND);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ContentResolver resolver = this.getContentResolver();
// Get data from the folder
assert data != null;
Uri MyData = data.getData(); // for simple image
ClipData MultiImg = data.getClipData(); // for multiple images
GlobalVariables.countImg = MultiImg.getItemCount();
/* ******************************************
To pick multiples images from Gallery
******************************************
*/
if (requestCode == CODE_MULTIPLE_IMAGES_GALLERY && resultCode == RESULT_OK ){
/*
// TODO: For multiple images, more than 2 change this
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();*/
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
if(GlobalVariables.countImg == 2){
// Getting name of the picture and print it
MyPath1 = MultiImg.getItemAt(0).getUri().toString();
MyPath2 = MultiImg.getItemAt(1).getUri().toString();
String Name1 = StringUtils.right(MyPath1,22);
String Name2 = StringUtils.right(MyPath2,22);
//String Proj_name = StringUtils.
GlobalVariables.PictureName1 = Name1;
GlobalVariables.PictureName2 = Name2;
Log.d(TAG, "--- First data name: " + StringUtils.right(MyPath1,22));
Log.d(TAG, "--- Second data name: " + StringUtils.right(MyPath2,22));
//Log.d(TAG, "Selected Items: " + clipData.getItemCount());
Log.d(TAG, "The full path is: " + MultiImg.getItemAt(0).getUri().toString());
// Showing images in the imageView
imageView1.setImageURI(MultiImg.getItemAt(0).getUri());
imageView2.setImageURI(MultiImg.getItemAt(1).getUri());
} else if (MyData != null ){
Log.d(TAG, "Only one image selected..");
Toast.makeText(context, "You should select 2 images and not only one", Toast.LENGTH_LONG).show();
recreate();
}
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
else if (GlobalVariables.countImg > 2){
//Log.d(TAG, "More than two selected images...");
Toast.makeText(context, "You should select 2 images and not ..." + GlobalVariables.countImg, Toast.LENGTH_LONG).show();
recreate();
}
}
/* ******************************************
To pick only one image fom Gallery for
each of ImageView and check that they
are different.
******************************************
*/
// pick image to the imageView1
else if(requestCode == CODE_IMAGE_GALLERY_FIRST && resultCode == RESULT_OK && MyData != null){
MyPath1 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView2 has an image: \n" + StringUtils.right(MyPaths2,22));
assert StringUtils.right(MyPath1, 22) != null;
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName1 = StringUtils.right(MyPath1,22);
imageView1.setImageURI(MyData);
}
}
// pick image to the imageView2
else if(requestCode == CODE_IMAGE_GALLERY_SECOND && resultCode == RESULT_OK && MyData != null) {
MyPath2 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView1 has an image: \n" + StringUtils.right(MyPaths2,22));
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName2 = StringUtils.right(MyPath2,22);
imageView2.setImageURI(MyData);
}
}
}
....
}
Can someone advise me on how I can solve this problem?
It is clear that I could leave things as they are and tell the user to check the folder where he selects the photos. But I would like it to be something more fluid and intuitive.
Thanks in advance.
private ArrayList<File> m_list = new ArrayList<File>();
String folderpath = Environment.getExternalStorageDirectory()
+ File.separator + "folder_name/";
File dir = new File(folderpath);
m_list.clear();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.getPath().contains("Not_Found"))
m_list.add(file);
}
}
I have been trying to figure this out all day, as I would like to add an image depending on the outcome of the emotion may detect. Just wanted to add some some images but I'm still new to this. Can anyone help me with this one to.
btw here's my code:
public class DetectionActivity extends AppCompatActivity {
// Background task of face detection.
private class DetectionTask extends AsyncTask<InputStream, String, Face[]> {
private boolean mSucceed = true;
#Override
protected Face[] doInBackground(InputStream... params) {
// Get an instance of face service client to detect faces in image.
FaceServiceClient faceServiceClient = SampleApp.getFaceServiceClient();
try {
publishProgress("Detecting...");
// Start detection.
return faceServiceClient.detect(
params[0], /* Input stream of image to detect */
true, /* Whether to return face ID */
true, /* Whether to return face landmarks */
new FaceServiceClient.FaceAttributeType[]{
FaceServiceClient.FaceAttributeType.Emotion,
});
} catch (Exception e) {
mSucceed = false;
publishProgress(e.getMessage());
addLog(e.getMessage());
return null;
}
}
#Override
protected void onPreExecute() {
mProgressDialog.show();
addLog("Request: Detecting in image " + mImageUri);
}
#Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.setMessage(progress[0]);
setInfo(progress[0]);
}
#Override
protected void onPostExecute(Face[] result) {
if (mSucceed) {
addLog("Response: Success. Detected " + (result == null ? 0 : result.length)
+ " face(s) in " + mImageUri);
}
// Show the result on screen when detection is done.
setUiAfterDetection(result, mSucceed);
}
}
// Flag to indicate which task is to be performed.
private static final int REQUEST_SELECT_IMAGE = 0;
// The URI of the image selected to detect.
private Uri mImageUri;
// The image selected to detect.
private Bitmap mBitmap;
// Progress dialog popped up when communicating with server.
ProgressDialog mProgressDialog;
// When the activity is created, set all the member variables to initial state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
//this hides the back button and I thank you
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getString(R.string.progress_dialog_title));
// Disable button "detect" as the image to detect is not selected.
setDetectButtonEnabledStatus(false);
LogHelper.clearDetectionLog();
}
// Save the activity state when it's going to stop.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ImageUri", mImageUri);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
// Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.smile);
builder.setTitle(R.string.app_name);
builder.setView(messageView);
builder.create();
builder.show();
break;
case R.id.menuHelp:
// Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
// Intent help = new Intent(this, HelpActivity.class);
//startActivity(help);
// break;
View messageViewh = getLayoutInflater().inflate(R.layout.help, null, false);
AlertDialog.Builder builderh = new AlertDialog.Builder(this);
builderh.setIcon(R.drawable.smile);
builderh.setTitle(R.string.app_nameh);
builderh.setView(messageViewh);
builderh.create();
builderh.show();
break;
}
return true;
}
// Recover the saved state when the activity is recreated.
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageUri = savedInstanceState.getParcelable("ImageUri");
if (mImageUri != null) {
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
}
}
// Called when image selection is done.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
// If image is selected successfully, set the image URI and bitmap.
mImageUri = data.getData();
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
if (mBitmap != null) {
// Show the image on screen.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(mBitmap);
// Add detection log.
addLog("Image: " + mImageUri + " resized to " + mBitmap.getWidth()
+ "x" + mBitmap.getHeight());
}
// Clear the detection result.
FaceListAdapter faceListAdapter = new FaceListAdapter(null);
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
// Clear the information panel.
setInfo("");
// Enable button "detect" as the image is selected and not detected.
setDetectButtonEnabledStatus(true);
}
break;
default:
break;
}
}
// Called when the "Select Image" button is clicked.
public void selectImage(View view) {
Intent intent = new Intent(this, SelectImageActivity.class);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
// Called when the "Detect" button is clicked.
public void detect(View view) {
// Put the image into an input stream for detection.
ByteArrayOutputStream output = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
// Start a background task to detect faces in the image.
new DetectionTask().execute(inputStream);
// Prevent button click during detecting.
setAllButtonsEnabledStatus(false);
}
// View the log of service calls.
public void viewLog(View view) {
Intent intent = new Intent(this, DetectionLogActivity.class);
startActivity(intent);
}
// Show the result on screen when detection is done.
private void setUiAfterDetection(Face[] result, boolean succeed) {
// Detection is done, hide the progress dialog.
mProgressDialog.dismiss();
// Enable all the buttons.
setAllButtonsEnabledStatus(true);
// Disable button "detect" as the image has already been detected.
setDetectButtonEnabledStatus(false);
if (succeed) {
// The information about the detection result.
String detectionResult;
if (result != null) {
detectionResult = result.length + " face"
+ (result.length != 1 ? "s" : "") + " detected";
// Show the detected faces on original image.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(ImageHelper.drawFaceRectanglesOnBitmap(
mBitmap, result, true));
// Set the adapter of the ListView which contains the details of the detected faces.
FaceListAdapter faceListAdapter = new FaceListAdapter(result);
// Show the detailed list of detected faces.
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
} else {
detectionResult = "0 face detected";
}
setInfo(detectionResult);
}
mImageUri = null;
mBitmap = null;
}
// Set whether the buttons are enabled.
private void setDetectButtonEnabledStatus(boolean isEnabled) {
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
}
// Set whether the buttons are enabled.
private void setAllButtonsEnabledStatus(boolean isEnabled) {
Button selectImageButton = (Button) findViewById(R.id.select_image);
selectImageButton.setEnabled(isEnabled);
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
// Button ViewLogButton = (Button) findViewById(R.id.view_log);
// ViewLogButton.setEnabled(isEnabled);
}
// Set the information panel on screen.
private void setInfo(String info) {
TextView textView = (TextView) findViewById(R.id.info);
textView.setText(info);
}
// Add a log item.
private void addLog(String log) {
LogHelper.addDetectionLog(log);
}
// The adapter of the GridView which contains the details of the detected faces.
private class FaceListAdapter extends BaseAdapter {
// The detected faces.
List<Face> faces;
// The thumbnails of detected faces.
List<Bitmap> faceThumbnails;
// Initialize with detection result.
FaceListAdapter(Face[] detectionResult) {
faces = new ArrayList<>();
faceThumbnails = new ArrayList<>();
if (detectionResult != null) {
faces = Arrays.asList(detectionResult);
for (Face face : faces) {
try {
// Crop face thumbnail with five main landmarks drawn from original image.
faceThumbnails.add(ImageHelper.generateFaceThumbnail(
mBitmap, face.faceRectangle));
} catch (IOException e) {
// Show the exception when generating face thumbnail fails.
setInfo(e.getMessage());
}
}
}
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public int getCount() {
return faces.size();
}
#Override
public Object getItem(int position) {
return faces.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_face_with_description, parent, false);
}
convertView.setId(position);
// Show the face thumbnail.
((ImageView) convertView.findViewById(R.id.face_thumbnail)).setImageBitmap(
faceThumbnails.get(position));
// Show the face details.
String getEmotion;
// String improve = improveMessage(getEmotion);
DecimalFormat formatter = new DecimalFormat("#0.0");
//add
// String message = findMessage(getEmotion());
// String improve = improveMessage(getEmotion);
String face_description = String.format("Emotion: %s\n",
getEmotion(faces.get(position).faceAttributes.emotion)
);
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(face_description);
return convertView;
}
private String getEmotion(Emotion emotion) {
String emotionType = "";
double emotionValue = 0.0;
String emotionInfo = "";
if (emotion.anger > emotionValue) {
emotionValue = emotion.anger;
emotionType = "Anger";
emotionInfo = "If you haven't fed him/her yet maybe this precious one is thirsty or hungry.\n Try giving your attention. If your baby is acting unusual it's best to seek for medical help.";
}
if (emotion.contempt > emotionValue) {
emotionValue = emotion.contempt;
emotionType = "Contempt";
emotionInfo = "You go girl!";
}
if (emotion.disgust > emotionValue) {
emotionValue = emotion.disgust;
emotionType = "Disgust";
emotionInfo = "Look! If your baby is feeling this way mabye she/he doesn't like this. \n If what your doing right now is good for him/her maybe you can support that.";
}
if (emotion.fear > emotionValue) {
emotionValue = emotion.fear;
emotionType = "Fear";
emotionInfo = "Your baby looks somewhat uncomfortable.\n Make your baby feel comfortable and take note of what makes them feel like that. ";
}
if (emotion.happiness > emotionValue) {
emotionValue = emotion.happiness;
emotionType = "Happiness";
emotionInfo = "Just continue what you are doing. It is important to remember what can make them happy. \n";
}
if (emotion.neutral > emotionValue) {
emotionValue = emotion.neutral;
emotionType = "Neutral";
emotionInfo = "Maybe you should just observe first";
}
if (emotion.sadness > emotionValue) {
emotionValue = emotion.sadness;
emotionType = "Sadness";
emotionInfo = "Just cuddle or dandle your baby.";
}
if (emotion.surprise > emotionValue) {
emotionValue = emotion.surprise;
emotionType = "Surprise";
emotionInfo = "Oooh look. Play with your baby. Try doing peek a boo";
}
return String.format("%s: %f \n\n%s", emotionType, emotionValue, emotionInfo);
}
}
}
Just would like to add some images like happy if that is the detected emotion. Please do help me. Any help is highly appreciated. Thank you :)
I would like to add that after the emotionInfo.
I guess detectWithStream is you want.
Official Doc: Faces.detectWithStream Method
From Java SDK, the List<DetectedFace> object will return if successful.
I'm having problems in the following context, I need to make signatures on a form that is an image in PNG or JPG, this functionality belongs to a mobile application with Android system.
The status is in the following situation, I can place the signature in the place where the user clicked. But I'm having trouble resizing the signature bitmap proportionally to the amount of zoom that was given. You need to position the signature Bitmap at the point the user clicked on, but referring to the image and not the screen.
I have browsed a lot of topics on the internet, many here in StackOverflow, but I do not find any that gives me any idea how I can do such an activity. I have already arrived several times on the third page of Google.
Can anyone help me, or can you give me some insight into how I can do this?
problem sketch
My code
public class SignatureActivity extends Activity implements OnClickListener {
private LinearLayout mContent;
private Button mClear, mSave, mCancel;
private View view;
private Dialog dialog;
private Signature mSignature;
private TouchImageView img;
private float xPosition;
private float yPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_signature);
img = (TouchImageView) findViewById(R.id.iv_form);
img.setImageResource(R.drawable.imp_009_tiss_1200x859);
img.setOnClickListener(this);
// Dialog Function
dialog = new Dialog(SignatureActivity.this);
// Removing the features of Normal Dialogs
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_signature);
dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mSignature = (Signature) dialog.getWindow().findViewById(R.id.signatureView1);
dialog.setCancelable(true);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_form:
dialog_action();
break;
default:
break;
}
}
public void carregaComponentes() {
mContent = (LinearLayout) dialog.findViewById(R.id.ll_area_assinatura);
mClear = (Button) dialog.findViewById(R.id.clear);
mSave = (Button) dialog.findViewById(R.id.save);
mCancel = (Button) dialog.findViewById(R.id.cancel);
mSignature = (Signature) dialog.findViewById(R.id.signatureView1);
}
public void dialog_action() {
carregaComponentes();
mSignature.setBackgroundColor(Color.WHITE);
mSignature.setSigColor(255, 0, 0, 255);
view = mContent;
mClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Cleared");
mSignature.clearSignature();
}
});
mSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
view.setDrawingCacheEnabled(true);
if (saveSignature(view)) {
dialog.dismiss();
} else {
mSignature.clearSignature();
}
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v("log_tag", "Panel Canceled");
dialog.dismiss();
mSignature.clearSignature();
}
});
dialog.show();
}
public boolean saveSignature(View view) {
DisplayMetrics dm = new DisplayMetrics();
float dpi = dm.scaledDensity;
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenW = dm.widthPixels;
int screenH = dm.heightPixels;
Bitmap assinatura = mSignature.getImage();
Bitmap assinaturaRedimensionada = Bitmap.createScaledBitmap(
assinatura,
(Integer.valueOf((int) (screenW * 0.20))),
(Integer.valueOf((int) (screenH * 0.070))),
false);
img.buildDrawingCache();
Bitmap imgGto = img.getDrawingCache();
Bitmap gtoAssinada = Bitmap.createBitmap(imgGto.getWidth(), imgGto.getHeight(), imgGto.getConfig());
Canvas canvas = new Canvas(gtoAssinada);
canvas.drawBitmap(imgGto, new Matrix(), null);
canvas.drawBitmap(assinaturaRedimensionada, TouchImageViewListener.x, TouchImageViewListener.y, null);
// Creating Separate Directory for saving Generated Images
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String StoredPath = "GTO_assinada" + pic_name + ".png";
File fichero = new File(sd, StoredPath);
try {
if (sd.canWrite()) {
fichero.createNewFile();
OutputStream os = new FileOutputStream(fichero);
gtoAssinada.compress(Bitmap.CompressFormat.PNG, 90, os);
os.close();
img.setImageBitmap(gtoAssinada);
mSignature.clearSignature();
Toast.makeText(getApplicationContext(), "GTO Assinada com Sucesso!", Toast.LENGTH_LONG).show();
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
I just bought a puzzle game source code from codecanyon yesterday and its not what I expected. User have to choose a image from gallery to start the puzzle, but I want it changed in this way > activity "Choose Puzzle" then user has to choose an image listed in that activity(not from gallery, from drawables).
Im 90% sure this is the "choose from gallery" button function code
public void pickImageOnClick(View view){
shouldSwitch = false;
//startActivityForResult(i, PHOTO_FROM_MEMORY_REQUESTED);
Intent localIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
localIntent.setType("image/*");
localIntent.setAction(Intent.ACTION_GET_CONTENT);
localIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(localIntent, PHOTO_FROM_MEMORY_REQUESTED);
}
private File createGameFile(String part, String ext) throws Exception
{
//Getting external storage path, and .temp directory in it.
File mainDir= Environment.getExternalStorageDirectory();
mainDir=new File(mainDir.getAbsolutePath()+MAIN_FOLDER);
//If .temp does not exists, it is created.
if(!mainDir.exists()) mainDir.mkdir();
return new File(mainDir.getAbsolutePath().toString(), part+ext);
// return File.createTempFile(part, ext, mainDir);
}
public void playOnClick(View View){
Intent intent = new Intent(this, PuzzleActivity.class);
String[] gameSizes = getResources().getStringArray(R.array.gamesizes);
intent.putExtra(EXTRA_GAMESIZE, gameSizes[gameSizeSpinner.getSelectedItemPosition()]);
intent.putExtra(EXTRA_IMGURI, imageUri);
//Toast.makeText(getApplicationContext(), "Hi"+imageUri, 400).show();
int orientation; //Determining screen orientation.
orientation = (selectedImage.getWidth()>selectedImage.getHeight()) ?
GameBoard.ORIENTATION_HORIZONTAL : GameBoard.ORIENTATION_PORTRAIT;
intent.putExtra(EXTRA_BOARD_ORIENTATION, orientation);
// String str = orientation == 0 ? "PORTRAIT" : "HORIZONTAL";
// Log.d("KAMIL", "Orientation : " + str);
shouldSwitch = true;
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PHOTO_FROM_MEMORY_REQUESTED && resultCode == RESULT_OK){
//updateSelectedPicture(data.getData());
try
{
imageUri = data.getData();
//scaleImage(uri, 2048);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 9;
//Opening the input stream and receiving Bitmap.
InputStream imageStream = getContentResolver().openInputStream(imageUri);
//selectedImage = BitmapFactory.decodeStream(imageStream);
selectedImage = BitmapFactory.decodeStream(imageStream,null,options);
//.selectedImage = BitmapFactory.decodeFile(i);
//Bitmap thumbnail = BitmapFactory.decodeFile(mFileTemp.getPath());
if (selectedImage.getHeight() > 1200)
selectedImage = Bitmap.createScaledBitmap(selectedImage, selectedImage.getWidth() * 1200 / selectedImage.getHeight(), 1200, false);
//Toast.makeText(getApplicationContext(), ""+selectedImage.getHeight(), 400).show();
System.gc();
playButton.setEnabled(true);
}
catch (FileNotFoundException localFileNotFoundException)
{
localFileNotFoundException.printStackTrace();
}
}
"pickImageOnClick"...thats it
Try this,
ImageView imageview = (ImageView)findViewById(R.id.imageView);
imageview.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
I want to sync the local database file in the Android app with the users' DropBox or SkyDrive account. Anything would do.
I am not able to get a running code.
Please help.
Here is the code I got from the official DropBox site, but it says error at
"final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;" as NoClassDefFoundError
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";
///////////////////////////////////////////////////////////////////////////
// Your app-specific settings. //
///////////////////////////////////////////////////////////////////////////
// Replace this with your app key and secret assigned by Dropbox.
// Note that this is a really insecure way to do this, and you shouldn't
// ship code which contains your key & secret in such an obvious way.
// Obfuscation is good.
final static private String APP_KEY = "5gqlcpeirbe9kju";
final static private String APP_SECRET = "zs9bi3nwqf4arn2";
// If you'd like to change the access type to the full Dropbox instead of
// an app folder, change this value.
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
///////////////////////////////////////////////////////////////////////////
// End app-specific settings. //
///////////////////////////////////////////////////////////////////////////
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
// Android widgets
private Button mSubmit;
private LinearLayout mDisplay;
private Button mPhoto;
private Button mRoulette;
private ImageView mImage;
private final String PHOTO_DIR = "/Photos/";
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCameraFileName = savedInstanceState.getString("mCameraFileName");
}
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
setContentView(R.layout.main);
checkAppKeySetup();
mSubmit = (Button)findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
mApi.getSession().startAuthentication(DBRoulette.this);
}
}
});
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView)findViewById(R.id.image_view);
// This is the button to take a photo
mPhoto = (Button)findViewById(R.id.photo_button);
mPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// Picture from camera
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// This is not the right way to do this, but for some reason, having
// it store it in
// MediaStore.Images.Media.EXTERNAL_CONTENT_URI isn't working right.
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String newPicFile = df.format(date) + ".jpg";
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mCameraFileName = outFile.toString();
Uri outuri = Uri.fromFile(outFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
Log.i(TAG, "Importing New Picture: " + mCameraFileName);
try {
startActivityForResult(intent, NEW_PICTURE);
} catch (ActivityNotFoundException e) {
showToast("There doesn't seem to be a camera.");
}
}
});
// This is the button to take a photo
mRoulette = (Button)findViewById(R.id.roulette_button);
mRoulette.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DownloadRandomPicture download = new DownloadRandomPicture(DBRoulette.this, mApi, PHOTO_DIR, mImage);
download.execute();
}
});
// Display the proper UI state if logged in or not
setLoggedIn(mApi.getSession().isLinked());
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("mCameraFileName", mCameraFileName);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
// This is what gets called on finishing a media piece to import
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == NEW_PICTURE) {
// return from file upload
if (resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
}
if (uri == null && mCameraFileName != null) {
uri = Uri.fromFile(new File(mCameraFileName));
}
File file = new File(mCameraFileName);
if (uri != null) {
UploadPicture upload = new UploadPicture(this, mApi, PHOTO_DIR, file);
upload.execute();
}
} else {
Log.w(TAG, "Unknown Activity Result from mediaImport: "
+ resultCode);
}
}
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
// Clear our stored keys
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
/**
* Convenience function to change UI state based on being logged in
*/
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Unlink from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Link with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") ||
APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
// Check if the app has set up its manifest properly.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
String scheme = "db-" + APP_KEY;
String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
testIntent.setData(Uri.parse(uri));
PackageManager pm = getPackageManager();
if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
showToast("URL scheme in your app's " +
"manifest is not set up correctly. You should have a " +
"com.dropbox.client2.android.AuthActivity with the " +
"scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*
* #return Array of [access_key, access_secret], or null if none stored
*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
}
return session;
}
}
Do you add the dropbox-android-sdk.jar in your buildPath and in a correct way ?
The DropboxAPI JAR file should be in the libs/ folder, not lib/.
Try this and tell me if it works now ...
PS: I'm working with DropboxAPI for android, and their code works very well for me and their documentation is really good to do your own application.