I wrote a solution for renaming files, but nothing happens in Android 10, although in 11 and above it is renamed normally.
public class PathDiv {
public static String dev(String path){
return path.replaceAll("^(.*)/.*?$","$1");
}
public static void renameFilesInDir(String path, String dirIn, String ext) {
File checkFile = new File(path);
if (checkFile.isFile()) {
try {
checkFile.renameTo(new File(dirIn, ext));
} catch (Exception e) {
e.printStackTrace();
}
}
}
path: /storage/emulated/0/Music/04. Kasger - Highland.mp3 dirIn: /storage/emulated/0/Music ext: Highland.mp3
PathDiv.renameFilesInDir(songItem.realUri,PathDiv.dev(songItem.realUri),newName.toString())
What's the problem?
In Android 10 and Higher Version of android, you can't Rename or Delete directly.
For Rename or Delete a media file you want to send a request.
Here Read Android Official Document how to create a request
For your information, to Delete a media file Dependency Available here you can use it easily it's created by me
checkFile.renameTo(new File(dirIn, ext)); It Also Works for this you want to add ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION permission in your app but before using this permission please refer to Google Play Police Update
I've finished an app and have been attempting to have that app log some data in a text file. I have a few questions about creating files and file paths with Android Studio. I'm not well versed in the editor so perhaps my questions are simple. I'm logging the data in an activity that extends MainActivity, declared as LoggerActivity.
public class LoggerActvitivty extends MainActivity{
public boolean bNewUser = true;
public String sFileName;
public void writeToFile(HashMap hmSaleToSave) {
if (bNewUser) {
System.out.println(hmSaleToSave);
sFileName = Environment.DIRECTORY_DOWNLOADS + "/Sales-" + LocalDateTime.now() + ".txt";
try {
if(!Files.exists(Paths.get(sFileName))) {
Files.createFile(Paths.get(sFileName));
Files.write(Paths.get(sFileName), sFileName.getBytes(StandardCharsets.UTF_8));
}
System.out.println("FILE WRITE EXECUTED");
System.out.println("Location" + sFileName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
}
}
Nothing crash's, but I believe I'm providing a null directory resulting in this logcat error
W/System.err: java.nio.file.NoSuchFileException: Download/Sales-2021-08-16T07:44:36.321.txt
I would like the logs to go to my tablets download directory. My first question is should I be using a different method to get my directory rather than through Enviornment.DIRECTORY_DOWNLOADS? Additionally if the path doesn't exist Files.createFile(....) should create the path too? Or does that just create the file at the specified path (sFileName)?
I have downloaded all the firebase maven dependencies jar files (that we get when using groupID com.google.firebase with artifactID firebase-admin, with version 6.2.0) into a dynamic web project.
I then used the code given in firebase documentation for Java to connect to firebase. Here is the documentation code:
public class FirebaseUpdater {
public static void main(String[] args){
FileInputStream serviceAccount;
try {
serviceAccount = new
FileInputStream("C:/Users/Asus/workspace/"
+ "school1/schoolbackup_service.json");
//FileInputStream("path/to/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://schoolbackup-f2429.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
// As an admin, the app has access to read and write all data, regardless of Security Rules
DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference("restricted_access/secret_document");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
Object document = dataSnapshot.getValue();
System.out.println(document);
}
public void onCancelled(DatabaseError error) {
}
});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
However, I get the following error for the function FirebaseOptions.Builder:
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.Iterables.getFirst(Ljava/lang/Iterable;Ljava/lang/Object;)Ljava/lang/Object;
at com.google.auth.oauth2.OAuth2Credentials.getFromServiceLoader(OAuth2Credentials.java:291)
at com.google.auth.oauth2.ServiceAccountCredentials.<init>(ServiceAccountCredentials.java:165)
at com.google.auth.oauth2.ServiceAccountCredentials.fromPkcs8(ServiceAccountCredentials.java:266)
at com.google.auth.oauth2.ServiceAccountCredentials.fromJson(ServiceAccountCredentials.java:195)
at com.google.auth.oauth2.GoogleCredentials.fromStream(GoogleCredentials.java:160)
at com.google.auth.oauth2.GoogleCredentials.fromStream(GoogleCredentials.java:127)
at FirebaseUpdater.main(FirebaseUpdater.java:25)
Here is the folder that contains the list of my dependencies for com.google.firebase. They have all been added to my reference libraries.
enter image description here
enter image description here
enter image description here
What am I doing wrong? Is it some missing jar? Should the jars not be in the reference libraries? Should I not use maven dependencies for a dynamic web project? Or is it that I cannot even use firebase connectivity in non-gradle and non-maven projects? And what is the workaround for this problem? Because I am in desperate need of Java-Firebase connectivity.
Please help!!! Thank you in advance
I'm having some troubles when I try to generate a library that contains another one in Android Studio. First of all I am using Android Studio 2.0 and Unity 5.3.4f1. What I want to do is integrate FFMpeg in Unity so I decided to create my own library that use FFMpeg library as an intermediary. The FFMpeg library is here.
To start I created a new empty project in Android Studio and inside of it, created a new module, which will be my library, using New->Module->Android Library and named it "ffmpegcodec". After that I opened build.gradle file inside the new module folder and paste:
compile 'com.writingminds:FFmpegAndroid:0.3.2'
inside dependencies brackets, and click Sync (It did not show any error).
After that create a new Java Class inside src/main/java/package-name/ and named it FFMpegCodec. Inside this paste this code:
public class FFMpegCodec {
private static FFmpeg ffmpeg;
private static Context context;
private static FFMpegCodec INSTANCE = null;
public FFMpegCodec(){
INSTANCE = this;
}
public static FFMpegCodec instance(){
if(INSTANCE == null){
INSTANCE = new FFMpegCodec();
}
return INSTANCE;
}
public void setContext(Context ctx){
this.context = ctx;
}
public void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(context);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onFailure() {
Log.e("FFMPEG", "ffmpeg : NOT correct Loaded");
}
#Override
public void onSuccess() {
Log.e("FFMPEG", "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
} catch (Exception e) {
}
}
public void execFFmpegCommand(final String[] command) {
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onFailure(String s) {
Log.e("FFMPEG", "FAILED with output : " + s);
}
#Override
public void onSuccess(String s) {
Log.e("FFMPEG", "SUCCESS with output : " + s);
}
#Override
public void onProgress(String s) {
Log.e("FFMPEG", "Started command : ffmpeg " + command);
Log.e("FFMPEG", "progress : " + s);
}
#Override
public void onStart() {
Log.e("FFMPEG", "Started command : ffmpeg " + command);
}
#Override
public void onFinish() {
Log.e("FFMPEG", "Finished command : ffmpeg " + command);
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}
It basically generates an instance of FFmpeg and makes calls of ffmpeg commands.
Once I have my lib done I decided to test it in my project so I include my lib in my app graddle using:
compile project(':ffmpegcodec')
After that I just paste this code to my MainActivity:
public class MainActivity extends AppCompatActivity {
FFMpegCodec ffmpeg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button execCommandButton = (Button) findViewById(R.id.execCommandButton);
ffmpeg = FFMpegCodec.instance();
execCommandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "This is a Toast!!", Toast.LENGTH_SHORT).show();
ffmpeg.setContext(MainActivity.this);
ffmpeg.loadFFMpegBinary();
String []cmd = new String[1];
cmd[0] = "-version";
ffmpeg.execFFmpegCommand(cmd);
}
});
}
After that, I run my project and when I press the button it returns that everythings its ok, showing ffmpeg version.
Once I have check that my lib works I decide to move it to Unity so copy the ffmpegcodec-realese.arr file inside ffmpegcodec/build/outputs/aar folder and paste it into my Unity project. Then I wrote an C# script to use my lib that contains this:
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using System.Collections;
using System.Diagnostics;
public class ScreenRecorder {
private AndroidJavaObject unityActivity = null;
private AndroidJavaObject captureObject = null;
// Use this for initialization
public ScreenRecorder () {
try{
using (AndroidJavaClass unityPlayerActivityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
unityActivity = unityPlayerActivityClass.GetStatic<AndroidJavaObject>("currentActivity");
}
AndroidJavaClass captureClass = new AndroidJavaClass ("com.promineostudios.ffmpegcodec.FFMpegCodec");
if (captureClass != null) {
captureObject = captureClass.CallStatic<AndroidJavaObject>("instance");
captureObject.Call("setContext", unityActivity);
captureObject.Call("loadFFMpegBinary");
}
}catch(Exception ex){
UnityEngine.Debug.Log(ex);
}
}
}
The problems comes here. When I create a class instance using:
AndroidJavaClass captureClass = new AndroidJavaClass ("com.promineostudios.ffmpegcodec.FFMpegCodec");
It creates an instance correctly, and also when I create an object using:
captureObject = captureClass.CallStatic<AndroidJavaObject>("instance");
But when I try to get access to FFMpeg library methods like in "setContext" it fails and returns this:
UnityEngine.AndroidJavaException: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/github/hiteshsondhi88/libffmpeg/FFmpeg;
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/github/hiteshsondhi88/libffmpeg/FFmpeg;
at com.promineostudios.ffmpegcodec.FFMpegCodec.loadFFMpegBinary(FFMpegAndroidCodec.java:39)
at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
at com.unity3d.player.UnityPlayer.a(Unknown Source)
at com.unity3d.player.UnityPlayer$b.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.github.hiteshsondhi88.libffmpeg.FFmpeg" on path: DexPathList[[zip file "/data/app/com.promineostudios.ffmpegmodule-1/base.apk"],nativeLibraryDirectories=[/data/app/com.promineostudios.ffmpegmodule-1/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at com.promineostudios.ffmpegcodec.FFMpegCodec.loadFFMpegBinary(FFMpegAndroidCodec.java:39)
at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
at com.unity3d.player.UnityPlayer.a(Unknown Source)
at com.unity3d.player.UnityPlayer$b.run(Unknown Source)
I think that the problem is in when I export my lib into Unity but I do not know what is going wrong. If anybody could help me I will be really appreciated.
Thanks and excuse me for my English.
I know you're no longer working on this project Nestoraj, however I have figured out a solution:
The error you're getting is caused by the UnityPlayerActivity not finding the source for com/github/hiteshsondhi88/libffmpeg/FFmpeg so in order to fix that you must put the 'com.writingminds:FFmpegAndroid:0.3.2' jar file inside your Unity project's Assets/Plugins/Android folder
After doing that and running the project, you're still going to get an error loading the ffmpeg binary file, this is because it's also not properly packaged in Unity, to fix this you need to export your project to Gradle/Android Studio, and then inside your src/main/jniLibs directory you have to place the ffmpeg .so binary files, according to each architecture so jniLibs/armeabi-v7a/libARM_ARCH.so jniLibs/armeabi/libARM_ARCH.so etc. Then you must also place the ffmpeg object files inside src/main/assets and again according to each architecture like so : src/main/assets/armeabi-v7a/ffmpeg etc.
Once those 2 steps are done you should be able to run your project in Android Studio and load the ffmpeg binary inside your Unity project
I'm trying to integrate posting to one's wall from within my app. I already have an area where the user can save his/her username and password (encrypted). I would like my program to recall the saved username and password, pass that to Facebook for authentication, and then allow the app to post simple text (maybe a link too) to the user's wall.
That said, I've read everything on the developer pages at Facebook (the api looks completely foreign to me... I've never done any type of web app development before... just desktop apps), and experimented with the Java libraries here but to be honest, I don't understand any of the various implementations. Some claim to be simple to use, but apparently they are all way above my head.
I've even tried messing with the official Facebook Android SDK, but that uses a webview interface, and I can't pass in the username and password for easy authentication. Plus, I'm still clueless as to how to post to the wall even after correct authentication.
Please help.
Thanks.
Oh, btw I already have a Facebook API key and Application ID.
[UPDATE 1]
For further clarification:
If I use the following code snippet with the official Facebook Android SDK http://github.com/facebook/facebook-android-sdk what should I do next (after the user has logged-in)? This is unclear to me.
Facebook facebookClient = new Facebook();
facebookClient.authorize(this, "[APP ID]", new String[] {"publish_stream", "read_stream", "offline_access"}, this);
where "this" is an Activity that implements a DialogListener, and "[APP ID]" is my Facebook application ID.
Thanks.
[UPDATE 2]
I found a solution (see below), though the only thing missing is the ability to auto-populate the login text boxes with the data I have stored in the app. The official Facebook Android SDK may not allow for this. I'll keep looking into it.
I figured it out, with Tom's help (thanks). The key was creating a dialog with the "stream.publish" API call, using the Facebook Android SDK. Here are the steps:
Download the official Facebook Android SDK : http://github.com/facebook/facebook-android-sdk
Import the project files into Eclipse.
Export the project as a *.jar file. (this might cause a conflict)
[UPDATE]
Facebook recently updated the source code and I noticed the icon file caused resource id conflicts with my projects (Android 1.5+). My solution is to forget about exporting as a jar. Instead, copy the Facebook "com" folder directly into your app's "src" folder (i.e. "com.facebook.android" should be a package in your app... right alongside your source files). If you already have a "com" folder in your "src" folder, don't worry about any dialog boxes that appear about overwriting files, none of your source files should be overwritten. Go back into Eclipse, and refresh the "src" folder and "com.facebook.android" should now be listed as a package. Copy one of the included Facebook icons to your app's "drawable" folder and refresh that as well. Eclipse will complain about the "FbDialog.java" file... just add an import pointing to your app's "R" file to the header of that file (e.g. if your app's package name is "com.android.myapp," then add this: "import com.android.myapp.R;"). Go to #5 if you needed to do this.
Add the .jar file to your project's build path
Look at the following simplified example code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import com.facebook.android.*;
import com.facebook.android.Facebook.DialogListener;
public class FacebookActivity extends Activity implements DialogListener,
OnClickListener
{
private Facebook facebookClient;
private LinearLayout facebookButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test);//my layout xml
facebookButton = (LinearLayout)this.findViewById(R.id.Test_Facebook_Layout);
}
#Override
public void onComplete(Bundle values)
{
if (values.isEmpty())
{
//"skip" clicked ?
return;
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "post_id" is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("post_id"))
{
try
{
Bundle parameters = new Bundle();
parameters.putString("message", "this is a test");// the message to post to the wall
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
#Override
public void onError(DialogError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onCancel()
{
}
#Override
public void onClick(View v)
{
if (v == facebookButton)
{
facebookClient = new Facebook();
// replace APP_API_ID with your own
facebookClient.authorize(this, APP_API_ID,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
}
}
AsyncFacebookRunner mAsyncRunner;
Facebook facebook =new Facebook("Your app id");
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = facebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
Here is an objective answer to your new question, "What do I do next?"
A quick look at the source code leads me to believe this is what you do:
Check this URL for the REST (http://en.wikipedia.org/wiki/Representational_State_Transfer) API methods you can use to leave a comment/post:
http://developers.facebook.com/docs/reference/rest/
Specifically this: http://developers.facebook.com/docs/reference/rest/links.post
Check out lines 171 through 295 of Facebook.java
http://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/android/Facebook.java
To see how to use the API to make these requests.
You'll probably want this method (it's overloaded, see the code).
/**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
*
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* String response = request(parameters);
* </code>
*
* #param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* #throws IOException
* if a network error occurs
* #throws MalformedURLException
* if accessing an invalid endpoint
* #throws IllegalArgumentException
* if one of the parameters is not "method"
* #return JSON string representation of the response
*/
public String request(Bundle parameters)
To those who have problems, in the new facebook(); , the string is you App_id, and just delete the APP_ID in the authorized call.
Don't know why the error message is shown, but I guess that facebook updated the facebook SDK.