I have downloaded and installed the Dropbox Sync API for Android from here: https://www.dropbox.com/developers/sync
I couldn't understand much of their tutorial. It lacked a lot of crucial variables, so that I had to find them out myself. I now have a very messy code and a lot of things aren't there.
private DbxAccountManager mDbxAcctMgr;
static final int REQUEST_LINK_TO_DBX = 0; // This value is up to you // thanks for telling what it actually does, Dropbox!
DbxPath path = new DbxPath("/test.pdf");
public void onClickLinkToDropbox(View view) {
mDbxAcctMgr.startLink((Activity)this, REQUEST_LINK_TO_DBX);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_LINK_TO_DBX) {
if (resultCode == Activity.RESULT_OK) {
DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount()); // try /catch error
DbxFile testFile = dbxFs.open(path); //try/catch error
String contents = testFile.readString();
Log.d("Dropbox Test", "File contents: " + contents); // try / catch error
} else {
// ... Link failed or was cancelled by the user.
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
This gives me errors on the 3 lines, saying that I need to add try/catch.
But when I add try/catch, Eclipse tells me to null the variables, which would mean all the functions would only read nulls, thus not reading anything..
Could anyone help me any further? Dropbox only confused me more by giving wrong instructions etc. I am sure that even if I didn't have 3 try/catch errors it would still not work.
Anyone here who has experience with the Dropbox Sync API and could share an example program reading a txt file in a User's Dropbox folder?
Bart
For more info on REQUEST_LINK_TO_DBX, check out the Android documentation for onActivityResult: https://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent). It's there to help you differentiate between different activities.
For a working example, I'd suggest looking at the HelloDropbox example that comes with the SDK. Among other things, it reads a string from a file in Dropbox.
Here's the relevant code from HelloDropboxActivity.java:
try {
// ...
DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
// ...
String resultData;
DbxFile testFile = dbxFs.open(testPath);
try {
resultData = testFile.readString();
} finally {
testFile.close();
}
} catch (IOException e) {
// ...
}
Related
my code below worked with emulator (android 11 & api 30).
private void copy(File in, File out) throws IOException {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(in);
os = new FileOutputStream(out);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
Log.d("AAA", String.valueOf(out.length()));
}
} finally {
assert is != null;
is.close();
assert os != null;
os.close();
}
}
where i put this method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
String path = RealPathUtil.getRealPath(SetVoiceIntroActivity.this, data.getData());
File in = new File(path);
File out = new File(getFilesDir(), "record.mp3");
try {
copy(in, out);
Log.d(TAG, out.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
binding.voicePlayerView.setVisibility(View.VISIBLE);
binding.buttonDeleteVoice.setVisibility(View.VISIBLE);
binding.voicePlayerView.setAudio(out.getAbsolutePath());
}
}
but when i try with my phone it have a problem. how can i fix it?
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yolo.hopel, PID: 19152
java.lang.AssertionError
at com.yolo.hopel.Activities.SetProfile.SetVoiceIntroActivity.copy(SetVoiceIntroActivity.java:251)
at com.yolo.hopel.Activities.SetProfile.SetVoiceIntroActivity.onActivityResult(SetVoiceIntroActivity.java:64)
at android.app.Activity.dispatchActivityResult(Activity.java:8292)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5136)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5184)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2175)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7860)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
i catch it and i get the message
2021-08-03 19:29:10.310 25013-25013/com.yolo.hopel D/error: /storage/emulated/0/NCT/NgayKhacLa-DenDJGiangPhamTripleD-5393909.mp3: open failed: EACCES (Permission denied)
but i checked permission before
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermission();
}
});
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(intent, 0);
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
Toast.makeText(SetVoiceIntroActivity.this, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.check();
}
i'm sorry but my post is mostle code, i must add some text...
please help me, thanks everyone and have a nice day!
An AssertionError is thrown when the programmer thinks that something has happened which he/she didn't expect it to happen. So mostly this seems like a ScopedStorage issue to me since you explicitly mentioned the case with Android 11. You can try reading about the scoped storage in Android . Also the RealPathUtil that you used for github doesn't work for the scoped storage case
You can refer to this answer for some commonly needed operations for Files using Scoped Storage
Some other points you may need to know about Scoped Storage
The WRITE_EXTERNAL_STORAGE permission is deprecated and it is replaced by the MANAGE_EXTERNAL_STORAGE which is allowed on Play Store after manual approval by Google. You can now access all the publically available files in Android after Q without need the WRITE_EXTERNAL_PERMISSION. So you must not request the MANAGE_EXTERNAL_STORAGE permission unless you're building a File Explorer or anything like that
You can write to these public directories using the MediaStore class if you need explicit access to external storage, if not then you can use context.getFilesDir() which gives you app private access to the external storage under the /data/data/yourpackagename directory. You must manage this space explicitly
If you need temporary file storage, you should prefer using context.getCacheDir() and the space here will be managed by Android itself
Under no circumstances, you can get access to the app specific directory, even after you have MANAGE_EXTERNAL_STORAGE
You got a nice uri and then you mess around with all kind of untrusty code to obtain a file path to use FileInputStream for it.
Completely unnecessary.
Open an inputstream for the obtained uri and use it as it was your fileinputstream.
InputStream is = getContentResolver.openInputStream(data.getData());
I was surfing in Android code because I wanted to see what is into Activity.finish() method.
I just wanted to have the confirmation that in Activity.finish() there would be a call to onDestroy() method.
But what I found in this method (and in many others) was:
public void finish() {
throw new RuntimeException("Stub!");
}
So WHERE Can I find the code that really destroys the Activity?
Thanks!
This is because source code is not found in SDK.
To see the source code, you need to download source for Android SDK, so Android studio can display the respective code.
I don't know where you looked, but the code for finish() is this
/**
* Call this when your activity is done and should be closed. The
* ActivityResult is propagated back to whoever launched you via
* onActivityResult().
*/
public void finish() {
finish(DONT_FINISH_TASK_WITH_ACTIVITY);
}
which calls the private implementation
/**
* Finishes the current activity and specifies whether to remove the task associated with this
* activity.
*/
private void finish(int finishTask) {
if (mParent == null) {
int resultCode;
Intent resultData;
synchronized (this) {
resultCode = mResultCode;
resultData = mResultData;
}
if (false) Log.v(TAG, "Finishing self: token=" + mToken);
try {
if (resultData != null) {
resultData.prepareToLeaveProcess(this);
}
if (ActivityManagerNative.getDefault()
.finishActivity(mToken, resultCode, resultData, finishTask)) {
mFinished = true;
}
} catch (RemoteException e) {
// Empty
}
} else {
mParent.finishFromChild(this);
}
}
Important here is ActivityManagerNative.getDefault().finishActivity which you can find at line 3359 in this file https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/ActivityManagerNative.java
If you want to dive deeper, you can just follow the trail.
You are checking in .class not .java file.
I try to use Zxing to decode 128C (Code set C) barcodes. I have success when I read other types like QR_CODE, UPC_A.
These are barcodes that I trying to read:
Is possible read 128C barcodes (Not CODE 128 pure) with Zxing ?
Short aswer, yes, it should is possible. As 128C just is a subset of 128. Can scan the codes, might take a few seconds. And have XZing working in a app.
You have found out that 128 is supported, now you got to make an translation. 128C takes the same input as 128, just turns out numbers. So you could make a translation from the data you get back, and turn it into 128C. Check the second link for how that translates.
https://github.com/zxing/zxing/blob/master/README.md
https://en.wikipedia.org/wiki/Code_128
Get the needed classes from the XZing github, put them in a package in the java part of your project. I used only 2:
IntentIntegrator
IntentResult
Here is how it is initiated in my code:
/**
* Method called to intiate the scan (it's linked to a button)
*/
public void doScan(View view) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
// when you click the Scan Bar Code button
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) { // we have a result
String scanContent = scanningResult.getContents(); // set the content of the scan.
String scanFormat = scanningResult.getFormatName(); // set the type of scan.
// You will want to put this data somewhere else, globals, etc.
} else {
toast("No scan data received!"); // call to make a toast
}
}
I am developing an Android App to read the barcode by using the Zxing Barcode reader Plugin.
In the plugin there is an object named window.plugins.barcodeScanner with which we encode/decode the barcode.
I don't wanna use HTML to invoke things instead want the below Javascript function to be called from Java [on click of the image- the below function would be invoked].
function scanCode(){
window.plugins.barcodeScanner.scan(
function(result){
alert("Scanned Code: " + result.text
+ ". Format: " + result.format
+ ". Cancelled: " + result.cancelled);
},
function(error){
alert("Scan failed: " + error);
}
);
}
Kindly let me know how to achieve this.
Assumptions:
You've already setup the LibararyProject from https://github.com/wildabeast/BarcodeScanner/tree/master/src/android.
Your Activity is not extending CordovaActivity but is extending Activity.
Your main goal is really just to use the scanner. You were just trying to find an easy/quick way to do so and thought the PG plugin may do the trick.
All you have to do is pull out the scan and onActivityResult methods and some of the helper strings from https://github.com/wildabeast/BarcodeScanner/blob/master/src/android/com/phonegap/plugins/barcodescanner/BarcodeScanner.java and put them in your activity. You'll need to replace the references to cordova with your own activity.
End result may look something like this:
public static final int REQUEST_CODE = 0x0ba7c0de;
private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
public void scan() {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
this.startActivityForResult(intentScan, REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String barcode = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
//Do whatever you need with the barcode here
} else if (resultCode == Activity.RESULT_CANCELED) {
// handle a canceled scan
} else {
// throw an error or something
}
}
}
If that works for you, then you don't even need cordova as a dependancy.
You can invoke Javascript code from native side on Android using the sendJavascript function defined in CordovaWebView.
In your case you would do something like this. Considering that the you want to call the following function:
function scanSuccessCallback(result) {
//do something
}
on the native side in your plugin:
this.webView.sendJavascript("scanSuccessCallback('the result');");
I'm trying to learn Java right now and I've jumped in the deep end by starting with the Android Faceobok API. Right now, I'm trying to get some information from my graph data (a friend in this case) and display it in a text view. This seems rather trivial but it has been anything but.
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
The TextView doesn't change when I do this and I'm not exactly sure where I've gone wrong.
As an aside, there is a shortage of good Android Facebook API tutorials out there. Most are hundreds of lines of code; I don't have the energy or patience to consume all of that.
I have a feeling your initial request isnt working properly. you should try this line instead:
JSONObject response = Util.parseJson(facebook.request("me/friends"));
Firstly I think in your initial request, it should be "me/friends" rather than "/me/friends". Secondly you dont necessarily need the mBundleor "GET" parameters in what you're trying to achieve. Have you even defined parameters in mBundle? You're also getting information from the request method, so the "GET" parameter isn't necessary.
Try the line i just wrote, as it is simpler and will get your friends information. The rest of your code is fine.
Your assertion about being "trivial" is essentially true, but generally speaking "jumping into the deep end" rarely results in anything other than a drowning.
I'm going to be "that guy" and recommend you actually get to the point of having a general understanding and minimal competency in Java before tackling someone else's API. Once you know how Java works - the "PME" ... properties, methods, and events - learning anyone's API becomes just a question of following the proper steps.
Besides that little bit of PS, answer the following:
1) received data from your source?
2) what thread are you invoking this on?
3) any of the objects null?
4) any exceptions being thrown when you look in the Console or Log (print those out to the Log versus your current implementation)?
And, not for nothing, but if you don't have the time or patience to learn the "how's and why's" of an API or software dev in general then this will be a long exercise for you if the work ever becomes non-trivial.
Just one man's opinion who also has attempted to drink from fire hose before.
Update: Here's all of my code:
public class FriendsActivity extends Activity {
/** Called when the activity is first created. */
Facebook facebook = new Facebook("194653157245506");
TextView mText;
Bundle mBundle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText = (TextView) this.findViewById(R.id.text);
facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests"},
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
Log.i("friend is", name);
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
I may be a little off key. but I have done facebook api development in C#, and i am wondering if you have had the client login.
Facebook works with OAuth to allow you to authorize through them for a client. (Even your own account as the client) therefore you may need to login.
Another thing to look at is, do you have the TextView that is in the Activity that is being displayed..
Try putting in a breakpoint and looking over the code as it is executing, Debug View is great for that.
see if your response is being populated.
make sure you have the Text from the Activity.
mText = (TextView)findViewById(R.id.TextView1); //or whatever you named it.
Also the LogCat should show you the stack trace for any errors that occur, maybe posting some of the output would help