Error:java.lang.NoClassDefFoundError - java

Sorry, It's a repetitive question, but i haven't find my answer yet.
To make a FileChooser in my Android application i used this. So I added 2 jar files in my Properties-> Java Build path( one of them is android-support-v4.jar and the other is a handmade library(afilechooser)), but when it comes to run i face with these errors in onResume() method.
1-Is it possible that there is a problem with libs?
2-What is your solution?
3-Is there any problem with the FileChooserActivity?
The class is:
public class FileChooserActivity extends FragmentActivity implements
OnBackStackChangedListener {
public static final String PATH = "path";
public static final String EXTERNAL_BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private FragmentManager mFragmentManager;
private BroadcastReceiver mStorageListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, R.string.storage_removed, Toast.LENGTH_LONG).show();
finishWithResult(null);
}
};
private String mPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooser);
mFragmentManager = getSupportFragmentManager();
mFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mPath = EXTERNAL_BASE_PATH;
addFragment(mPath);
} else {
mPath = savedInstanceState.getString(PATH);
}
setTitle(mPath);
}
#Override
protected void onPause() {
super.onPause();
unregisterStorageListener();
}
#Override
protected void onResume() {
super.onResume();
registerStorageListener();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(PATH, mPath);
}
#Override
public void onBackStackChanged() {
mPath = EXTERNAL_BASE_PATH;
int count = mFragmentManager.getBackStackEntryCount();
if (count > 0) {
BackStackEntry fragment = mFragmentManager
.getBackStackEntryAt(count - 1);
mPath = fragment.getName();
}
setTitle(mPath);
}
/**
* Add the initial Fragment with given path.
*
* #param path The absolute path of the file (directory) to display.
*/
private void addFragment(String path) {
FileListFragment explorerFragment = FileListFragment.newInstance(mPath);
mFragmentManager.beginTransaction()
.add(R.id.explorer_fragment, explorerFragment).commit();
}
/**
* "Replace" the existing Fragment with a new one using given path.
* We're really adding a Fragment to the back stack.
*
* #param path The absolute path of the file (directory) to display.
*/
private void replaceFragment(String path) {
FileListFragment explorerFragment = FileListFragment.newInstance(path);
mFragmentManager.beginTransaction()
.replace(R.id.explorer_fragment, explorerFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(path).commit();
}
/**
* Finish this Activity with a result code and URI of the selected file.
*
* #param file The file selected.
*/
private void finishWithResult(File file) {
if (file != null) {
Uri uri = Uri.fromFile(file);
setResult(RESULT_OK, new Intent().setData(uri));
finish();
} else {
setResult(RESULT_CANCELED);
finish();
}
}
/**
* Called when the user selects a File
*
* #param file The file that was selected
*/
protected void onFileSelected(File file) {
if (file != null) {
mPath = file.getAbsolutePath();
if (file.isDirectory()) {
replaceFragment(mPath);
} else {
finishWithResult(file);
}
} else {
Toast.makeText(FileChooserActivity.this, R.string.error_selecting_file, Toast.LENGTH_SHORT).show();
}
}
/**
* Register the external storage BroadcastReceiver.
*/
private void registerStorageListener() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
registerReceiver(mStorageListener, filter);
}
/**
* Unregister the external storage BroadcastReceiver.
*/
private void unregisterStorageListener() {
unregisterReceiver(mStorageListener);
}
}
The errors are:
06-04 04:30:57.547: E/AndroidRuntime(605): FATAL EXCEPTION: main
06-04 04:30:57.547: E/AndroidRuntime(605): java.lang.NoClassDefFoundError: com.ipaulpro.afilechooser.R$layout
06-04 04:30:57.547: E/AndroidRuntime(605): at com.ipaulpro.afilechooser.FileChooserActivity.onCreate(FileChooserActivity.java:65)
06-04 04:30:57.547: E/AndroidRuntime(605): at android.app.Activity.performCreate(Activity.java:5104)
06-04 04:30:57.547: E/AndroidRuntime(605): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-04 04:30:57.547: E/AndroidRuntime(605): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
.
.
.

In Eclipse:
Right click on your Project
Select Properties -> Java Build Path-> Order and Export
Check the Android Private Libraries and then click OK button.

You should import the library as an existing Android project into Eclipse workspace. Check in the properties that it is defined as a library.
Then you have to import it in your project. This is done in Properties => Android => Add (in the library section). Choose the library, and then it should be working

Please Replace android-support-v4.jar file. and put ActivityNot Found Exception.
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(
target, getString(R.string.chooser_title));
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
}

Related

How I can prompt a file manager into a known path in an android app?

I have the following activity in my application:
public class DisplaySettingsActivity extends AppCompatActivity implements View.OnClickListener {
Button saveIntoFile;
TextView msg;
private ActivityResultLauncher<String> requestPermissionLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_settings);
requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
Log.d("H300s","Permissions Callback");
if (isGranted) {
Log.d("H300s","Permission Accepted 2");
saveFile();
} else {
permissionSaveDenied();
}
});
this.saveIntoFile = (Button)findViewById(R.id.save);
this.saveIntoFile.setOnClickListener(this);
}
private void saveFile(){
Log.d("Η300s","Saving");
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("H300s","Unable to detect external storage");
saveMsgHandler(null);
return;
}
this.saveIntoFile.setEnabled(false);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyMMdd");
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File( file.getAbsolutePath(),"voip_h300s_"+pattern.format(LocalDate.now())+".txt");
Log.d("H300s",file.toString());
try {
file.createNewFile();
PrintWriter out = new PrintWriter(new FileWriter(file));
out.println("SOME VALUES");
out.close();
saveMsgHandler(file.getAbsolutePath());
} catch (Exception e) {
saveMsgHandler(null);
}
}
#Override
public void onBackPressed() {
return;
}
private void saveMsgHandler(String savePath){
if (savePath == null) {
msg.setText(R.string.could_not_save_settings);
int errorColor = ContextCompat.getColor(this, R.color.error);
msg.setBackgroundColor(errorColor);
} else {
String string = String.format(getString(R.string.save_success),savePath);
msg.setText(string);
int success = ContextCompat.getColor(this, R.color.success);
msg.setBackgroundColor(success);
}
msg.setVisibility(View.VISIBLE);
this.saveIntoFile.setEnabled(true);
}
private void permissionSaveDenied(){
msg.setVisibility(View.VISIBLE);
msg.setText(R.string.could_not_save_settings);
int errorColor = ContextCompat.getColor(this, R.color.error);
msg.setBackgroundColor(errorColor);
this.saveIntoFile.setEnabled(true);
}
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("H300s","Permission Accepted");
saveFile();
} else {
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE );
}
}
}
And I want once I save the file to be able to prompt into androids file manager and list the saved file. Any provided solution tells me hot to select a path before saving as seen in this answer or in this question, but instead I want just to show the file into device's file manager after I successfully saving it.
So far, what I've developed is this method:
public void displayFileIntoFileManager(String path){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivity(intent, 7);
}
As a method to call from a button, once I saved the file in saveFile method. But how I can provide the path to the intent in order to be shown?
I just want to list the file into device's file manager.
I want just to show the file into device's file manager after I successfully saving it.
There is no standard Intent action for "open a file manager on a directory containing a specific file", sorry.
So far, what I've developed is this method
ACTION_GET_CONTENT is to allow the user to select a piece of content. If you are not looking to have the user do that, then this is not a suitable Intent action.
How I can prompt a file manager into a known path in an android app?
Wrong question.
You should have asked:
How can i let ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT and ACTION_OPEN_DOCUMENT_TREE open in a pre determined directory?
That question has been answered before.
The trick is to use extra INITIAL_URI.

Deleting a file given a Storage Access Framework uri and using content resolver fails

I am trying to delete a file using Storage Access Framework.
Below are some elements of code:
public class MyActivity extends AppCompatActivity
{
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
int n_requestCode;
switch(menuItem.getItemId())
{
[...]
case R.id.delete_file:
n_requestCode = 108;
startSAFActionOpenDocumentTree(n_requestCode);
break;
[...]
}
[...]
}
public void startSAFActionOpenDocumentTree(int n_requestCode)
{
Intent intent;
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, n_requestCode);
}
private void startSAFActionOpenDocument(int n_requestCode)
{
Intent intent = null;
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, n_requestCode);
}
protected void onActivityResult(int n_requestCode, int n_resultCode, Intent data)
{
android.net.Uri uri;
ContentResolver contentResolver;
if(n_requestCode == 108)
{
n_requestCode = 109;
startSAFActionOpenDocument(n_requestCode);
}
else if(n_requestCode == 109)
{
uri = data.getData();
contentResolver = getContentResolver();
try
{
contentResolver.delete(uri, null, null);
}
catch(Exception exn)
{
exn.printStackTrace();
}
}
}
}
Hence, the use case is the following:
The user taps the activity menu entry which id is R.id.delete_file.
Then the user has to select a directory
and then a file in this directory. This is where an android.net.Uri is retrieved in the code.
Given this uri, I would like to delete the corresponding file.
The problem is the following:
The contentResolver.delete(uri, null, null); raises the following exception:
W/System.err: java.lang.UnsupportedOperationException: Delete not supported
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.delete(ContentProviderNative.java:544)
at android.content.ContentResolver.delete(ContentResolver.java:1330)
at [...]MyActivity.onActivityResult(MyActivity.java:[...])
at android.app.Activity.dispatchActivityResult(Activity.java:6490)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.access$1400(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Note that, at another place in the code, I use the delete() method of the java.io.File class with an argument that is a file path (a String), not an android.net.Uri and the deletion works for the very same file.
Can you please help me solve that problem? Thanks.
The operation is not supported is the message.
Try instead:
DocumentFile srcDoc = DocumentFile.fromSingleUri(context, data.getData());
if ( srcDoc.delete() )
{
}
Your answer may work but code is too complicated.
Also the user does not have to select the directory first.
I found this solution using the class DocumentFile instead of ContentResolver.
The file is deleted.
public class MyActivity extends AppCompatActivity
{
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
int n_requestCode;
switch(menuItem.getItemId())
{
[...]
case R.id.delete_file:
n_requestCode = 109;
startSAFActionOpenDocument(n_requestCode);
break;
[...]
}
[...]
}
private void startSAFActionOpenDocument(int n_requestCode)
{
Intent intent = null;
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, n_requestCode);
}
protected void onActivityResult(int n_requestCode, int n_resultCode, Intent data)
{
DocumentFile srcDoc;
if(n_requestCode == 109)
{
srcDoc = DocumentFile.fromSingleUri(this, data.getData());
try
{
srcDoc.delete();
}
catch(Exception exn)
{
exn.printStackTrace();
}
}
}
}

Java Android studio Application - How to rename correctly photos after taking them with the camera?

I've a little problem. There are 2 days that I am trying to solve it without success.
I am trying to create an app that name every photo taken by a predefined name (ex : "coucou.jpg" instead of "IMG_20191119_201907.jpg").
So I've applyed some tutorials on the internet (https://developer.android.com/training/camera/photobasics.html#TaskPhotoView - https://www.youtube.com/watch?v=8890GpBwn9w (in french))
And it works !... Almost !
The photo are well created in the folder "Pictures".
But the problem that I have is the following : Created files don't receive the name that I gave to them. They are named 1574245595878.jpg - 1574245714222.jpg - 1574358229963.jpg - etc.
And I don't know where I'm wrong... I give you my code, normally, they should be called "coucou.jpg")
Can someone help me to give them the good name (or at least to rename them after creation in the same code) please ? It would be wonderful !
public class MainActivity extends AppCompatActivity {
private static final int RETOUR_PRENDRE_PHOTO = 1;
private Button btnPrendrePhoto;
private ImageView imgAffichePhoto;
private String photoPath = null;
private Bitmap image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initActivity();
}
private void initActivity(){
btnPrendrePhoto = (Button)findViewById(R.id.btnPrendrePhoto);
imgAffichePhoto = (ImageView)findViewById(R.id.imgAffichePhoto);
btnPrendrePhoto.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
prendreUnePhoto();
}
});
}
private void prendreUnePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
File photoDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File photofile = File.createTempFile("coucou",".jpg",photoDir);
photoPath = photofile.getAbsolutePath();
Uri photoUri = FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName()+".fileprovider", photofile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, RETOUR_PRENDRE_PHOTO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RETOUR_PRENDRE_PHOTO && resultCode==RESULT_OK){
image = BitmapFactory.decodeFile(photoPath);
imgAffichePhoto.setImageBitmap(image);
MediaStore.Images.Media.insertImage(getContentResolver(), image, "coucou.jpg", "description");
}
}
}
When you say createTempFile() it will append timestampInMillis to end of created File, that's the numbers you are looking at in your case, so try creating a normal File
replace
File photofile = File.createTempFile("coucou",".jpg",photoDir);
with
File image = new File(photoDir, "coucou.jpg");

launch Camera causing crash Android

I followed this simple app AndroidScannerDemo which has two main button open camera and open gallery. The Camera is working fine on my phone API 19, but when I try to launch the camera on other devices or emulator the app crash.
From what I could understand this could be due to permission
Edit : Apparently this was asked here awhile ago as well but the issue remain
Wrong Update : the root problem coming from createImageFile method
I tried changing
//cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri); to
cameraIntent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
I'm able to start the camera but I get crash right after taking picture
Update 2 : I'm trying following this article provided the answer below the only issue I'm using fragment
So How do I change this line
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
to
tempFileUri = FileProvider.getUriForFile(PickImageFragment.this,
getString(R.string.file_provider_authority),
file); inside a fragment !
Wrong First argument PickImageFragment
EDIT : Changed openCamera() method inside PickImageFragment
What Im I missing ?
Stack trace
2019-11-29 23:45:05.750 27993-27993/com.nabeeltech.capturedoc E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nabeeltech.capturedoc, PID: 27993
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nabeeltech.capturedoc/com.scanlibrary.ScanActivity}: java.lang.SecurityException: UID 10091 does not have permission to content://com.scanlibrary.provider/external_files/scanSample/IMG_20191129_224505.jpg [user 0]
Caused by: java.lang.SecurityException: UID 10091 does not have permission to content://com.scanlibrary.provider/external_files/scanSample/IMG_20191129_224505.jpg [user 0]
at com.scanlibrary.PickImageFragment.openCamera(PickImageFragment.java:131)
at com.scanlibrary.PickImageFragment.handleIntentPreference(PickImageFragment.java:79)
at com.scanlibrary.PickImageFragment.init(PickImageFragment.java:60)
at com.scanlibrary.PickImageFragment.onCreateView(PickImageFragment.java:50)
PickImageFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.pick_image_fragment, null);
init();
return view;
}
private void init() {
cameraButton = (ImageButton) view.findViewById(R.id.cameraButton);
cameraButton.setOnClickListener(new CameraButtonClickListener());
galleryButton = (ImageButton)
view.findViewById(R.id.selectButton);
galleryButton.setOnClickListener(new GalleryClickListener());
if (isIntentPreferenceSet()) {
handleIntentPreference();
} else {
getActivity().finish();
}
}
private void handleIntentPreference() {
int preference = getIntentPreference();
if (preference == ScanConstants.OPEN_CAMERA) {
openCamera();
} else if (preference == ScanConstants.OPEN_MEDIA) {
openMediaContent();
}
}
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri tempFileUri = null;
File file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
} else {
tempFileUri = Uri.fromFile(file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
}
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
cameraIntent.setClipData(ClipData.newRawUri("", tempFileUri));
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
private void clearTempImages() {
try {
File tempFolder = new File(ScanConstants.IMAGE_PATH);
for (File f : tempFolder.listFiles())
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
ScanConstants
public class ScanConstants {
public final static int PICKFILE_REQUEST_CODE = 1;
public final static int START_CAMERA_REQUEST_CODE = 2;
public final static String OPEN_INTENT_PREFERENCE = "selectContent";
public final static String IMAGE_BASE_PATH_EXTRA = "ImageBasePath";
public final static int OPEN_CAMERA = 4;
public final static int OPEN_MEDIA = 5;
public final static String SCANNED_RESULT = "scannedResult";
public final static String IMAGE_PATH = Environment
.getExternalStorageDirectory().getPath() + "/scanSample";
public final static String SELECTED_BITMAP = "selectedBitmap";
}
You've written the code Fileprovider.getUriforFile which is fine, but have you declare the permissions required.
The only way to solve this is to grant permissions to all of the packages that might need it, like this:
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
If above doesn't solve issue i'd suggest to refer this article by Lorenzo Quiroli that solves this issue for older Android versions.
He discovered that you need to manually set the ClipData of the Intent and set the permissions for it, like so:
if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP ) {
takePictureIntent.setClipData( ClipData.newRawUri( "", photoURI ) );
takePictureIntent.addFlags( Intent.FLAG_GRANT_WRITE_URI_PERMISSION|Intent.FLAG_GRANT_READ_URI_PERMISSION );
}

Android - try to connect to Dropbox API version 2

I'm try to connect to Dropbox api version 2 via Android Studio but I get this exception:
04-27 23:49:33.356 6482-6482/com.example.user.trackyournevi
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.trackyournevi, PID: 6482
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.trackyournevi/com.example.user.trackyournevi.Drop
boxActivity}: android.content.ActivityNotFoundException: Unable to find
explicit activity class
{com.example.user.trackyournevi/com.dropbox.client2.android.AuthActivity};
have you declared this activity in your AndroidManifest.xml?
My Dropbox Activity:
public class DropboxActivity extends AppCompatActivity implements
View.OnClickListener {
private LinearLayout container;
private boolean isUserLoggedIn;
private Button btnLogin;
private Button btnUpload;
private Button btnDownload;
private DropboxAPI<AndroidAuthSession> mDropboxApi;
private final static String DROPBOX_FILE_DIR = "/TrackYourNevi/";
private static final int IMAGE_GALLERY_REQUEST = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dropbox);
loggedIn(false);
//callback method
initializeSession();
}
private void initializeSession() {
//store app key and secret key
AppKeyPair appKeys = new AppKeyPair(getResources().getString(R.string.DROPBOX_APP_KEY),
getResources().getString(R.string.DROPBOX_APP_SECRET));
AndroidAuthSession session = new AndroidAuthSession(appKeys);
//Pass app key pair to new DropboxApi object
mDropboxApi = new DropboxAPI<AndroidAuthSession>(session);
//start session
mDropboxApi.getSession().startOAuth2Authentication(DropboxActivity.this);
}
#Override
public void onResume() {
super.onResume();
if(mDropboxApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the session
mDropboxApi.getSession().finishAuthentication();
String accessToken = mDropboxApi.getSession().getOAuth2AccessToken();
loggedIn(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.dxbLoginButton:
if(isUserLoggedIn) {
mDropboxApi.getSession().unlink();
loggedIn(false);
} else
mDropboxApi.getSession().startOAuth2Authentication(DropboxActivity.this);
break;
case R.id.dxbUploadButton:
//invoke the image gallery using an implict intent
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Where do we want to find the data
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDitrectoryPath = pictureDirectory.getPath() + "/" + getResources().getString(R.string.image_folder_name);
//Get URI representation
Uri data = Uri.parse(pictureDitrectoryPath);
//Set the data and type. get all images from jpg type
photoPickerIntent.setDataAndType(data, "image/jpg");
startActivityForResult(photoPickerIntent, IMAGE_GALLERY_REQUEST);
break;
case R.id.dxbDownloanButton:
break;
default:
break;
}
}
}
And my manifiest.xml contains the following data:
activity android:name=".DropboxActivity" android:launchMode="singleTask"
intent-filter
data android:scheme="db-key"
action android:name="android.intent.action.VIEW"
category android:name="android.intent.category.BROWSABLE"
category android:name="android.intent.category.DEFAULT"
intent-filter
activity
It looks like I defined everything as I saw in other tutorials but still it's not working.
Is someone see the problem and can help me?

Categories

Resources