I am not very well versed with Kotlin and I am preferring Java over Kotlin while learning Android. But I am stuck at a piece of code which is as follows:
private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() } }
return if (mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}
The following function is called in onCreate method as var outputDirectory: File = getOutputDirectory();
Can you please help me convert the code into Java and in understanding it?
Thank you.
private File getOutputDirectory() {
File mediaDir = null;
if (getExternalMediaDirs().size > 0) {
mediaDir = new File(getExternalMediaDirs()[0], getResources().getString(R.string.app_name));
mediaDir.mkdirs();
}
return if (mediaDir != null && mediaDir.exists())
mediaDir
else
filesDir
}
Here is the process on how to convert Kotlin code to Java code.
https://www.geeksforgeeks.org/how-to-convert-kotlin-code-to-java-code-in-android-studio/
But I suggest you to learn Kotlin as it is faster and preferred for Android app development.
Related
I was just wondering how to use MediaStore.createDeleteRequest() to create a delete request for a music/mp3 file. Because of the new ScopedStorage I am not able to use File.delete() and I cannot find some examples on how to use MediaStore.createDeleteRequest(). It would really be helpful if someone gives me a example on how to use it delete music files. Thanks
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val pendingIntent = MediaStore.createDeleteRequest(context.contentResolver, mutableListOf(fileUri))
deleteResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())
}
private val deleteResultLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
Log.d("deleteResultLauncher", "Android 11 or higher : deleted")
}
}
I have this JavaJaxRs dictionary with my templates:
/templates/JavaJaxRs
I edited some of them. And want to use them for my API generation (Code was inspired from this approach from https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java):
System.out.println("Generating API for: " + location);
DefaultGenerator generator = new DefaultGenerator();
Swagger swagger = new SwaggerParser().read(location);
CodegenConfig config = CodegenConfigLoader.forName(this.language);
config.setOutputDir(new File(this.apiGeneratedSrcPath).getPath());
if (null != templateDirectory) {
config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory);
}
if (null != modelPackage) {
config.additionalProperties().put(MODEL_PACKAGE_PARAM, modelPackage);
}
if (null != apiPackage) {
config.additionalProperties().put(API_PACKAGE_PARAM, apiPackage);
}
if (null != invokerPackage) {
config.additionalProperties().put(INVOKER_PACKAGE_PARAM, invokerPackage);
}
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(),
configOptions.get(langCliOption.getOpt()));
}
}
}
if (null != configurationFile) {
Config genConfig = ConfigParser.read(configurationFile);
if (null != genConfig) {
for (CliOption langCliOption : config.cliOptions()) {
if (genConfig.hasOption(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt()));
}
}
} else {
throw new RuntimeException("Unable to read configuration file");
}
}
ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger);
input.setConfig(config);
generator.opts(input).generate();
Somehow i always get the code generated with the standard template file.
UPDATE:
When i remember correctly i had a conditional bug on:
if(null != templateDirectory)
config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory);
or somewhere else but with the right condition, code was working as intended.
I let the question stay here, maybe it will help some other users.
You can get the help options for the code generator like such:
java -jar swagger-codegen-cli.jar help generate
Which should tell you that you can override the template location with the -t parameter:
java -java swagger-codegen-cli.jar generate -l {language} -t path/to/templates
Regarding the above ava -java swagger-codegen-cli.jar generate -l {language} -t path/to/templates,
I've managed to make it work with current being-worked-on-release (2.2.0).
With 2.1.6 (current GA) it does not work.
I have posted the following on swagger-codegen at GitHub:
https://github.com/swagger-api/swagger-codegen/issues/3188
Did not get any attention though...
Any one can help me!
I have two videos.
I want to merge as one video(side by side) and i need to display side by side and also i don't want to merge two audio.
I want only one audio.So now i want sample codes or reference for video merging code
I don't have enough reputation to comment so I am writing this as answer.
Muting one video is a good idea as dbilz suggested.
For merging videos use ffmpeg. If both the files you want to concatenate are using similar encoding try mp4parser
Look this question for more merging two or more video files
Gradle Dependency
implementation "com.writingminds:FFmpegAndroid:0.3.2"
Code
Command to concate two video side by side into one
val cmd : arrayOf("-y", "-i", videoFile!!.path, "-i", videoFileTwo!!.path, "-filter_complex", "hstack", outputFile.path)
Note :
"videoFile" is your first video path.
"videoFileTwo" is your second video path.
"outputFile" is your combined video path which is our final output path
To create output path of video
fun createVideoPath(context: Context): File {
val timeStamp: String = SimpleDateFormat(Constant.DATE_FORMAT, Locale.getDefault()).format(Date())
val imageFileName: String = "APP_NAME_"+ timeStamp + "_"
val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_MOVIES)
if (storageDir != null) {
if (!storageDir.exists()) storageDir.mkdirs()
}
return File.createTempFile(imageFileName, Constant.VIDEO_FORMAT, storageDir)
}
Code to execute command
try {
FFmpeg.getInstance(context).execute(cmd, object : ExecuteBinaryResponseHandler() {
override fun onStart() {
}
override fun onProgress(message: String?) {
callback!!.onProgress(message!!)
}
override fun onSuccess(message: String?) {
callback!!.onSuccess(outputFile)
}
override fun onFailure(message: String?) {
if (outputFile.exists()) {
outputFile.delete()
}
callback!!.onFailure(IOException(message))
}
override fun onFinish() {
callback!!.onFinish()
}
})
} catch (e: Exception) {
} catch (e2: FFmpegCommandAlreadyRunningException) {
}
I am new in android development. I am try to build an custom player in android.
I am googling and find some code and try to build it everything is going good but i am not able to resolve PolicyManager (com.android.internal.policy.PolicyManager) & MetaData (android.media.Metadata) Class. I am also search about these class but not find any solution. I am still not resolve this. please help me how to resolve this problem
Code:- (Problem in Metadata Class)
Metadata data = MediaPlayerInternals.getMetadata(mp, false, false);
if (data != null) {
mCanPause = !data.has(Metadata.PAUSE_AVAILABLE)
|| data.getBoolean(Metadata.PAUSE_AVAILABLE);
mCanSeekBack = !data.has(Metadata.SEEK_BACKWARD_AVAILABLE)
|| data.getBoolean(Metadata.SEEK_BACKWARD_AVAILABLE);
mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE)
|| data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
} else {
mCanPause = mCanSeekForward = mCanSeekForward = true;
}
Code:- (Problem in PolicyManager Class)
mWindow = PolicyManager.makeNewWindow(mContext);
I'm using Google Drive SDK v2 on Android to get the list of root folders. Currently I see these required steps - which seem to load forever. Is there no faster way?
I tried to use the search with the q= parameter but I don't get it to work (FileList vs. Files.List) - different API levels?
FileList files = drive.files().list().setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false");
This is what I do currently:
About about = drive.about().get().execute();
if (about != null) {
ChildList childList = drive.children().list(about.getRootFolderId()).execute();
if (childList != null) {
List<ChildReference> listChildReference = childList.getItems();
for (ChildReference childReference : listChildReference) {
File file = drive.files().get(childReference.getId()).execute();
if (file != null) {
String fileExtension = file.getFileExtension();
String mimeType = file.getMimeType();
if (mimeType != null
&& mimeType.equals("application/vnd.google-apps.folder")
&& (fileExtension == null || fileExtension.equals(""))) {
Log.d(this.getClass().getName(), file.getTitle());
}
}
}
}
}
What's the fastest for an Android app?
Thanks in advance.
My personal opinion is avoid the Drive SDK and call the REST API directly. It's a fairly simple API, and the way the documentation is structured, you are forced to understand it anyway in order to use the SDK. You have the benefit that if something doesn't work, you can directly compare your app with what's happening on the wire and resolve any problems.
Found it:
#Override
protected ArrayList<File> doInBackground(final Void... voids) {
ArrayList<File> result = new ArrayList<File>();
Files.List request = null;
boolean ok = true;
do {
try {
request = drive
.files()
.list()
.setMaxResults(200)
.setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false");
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException exception) {
ok = false;
}
} while (ok && request.getPageToken() != null && request.getPageToken().length() > 0);
return result;
}