Why Android class is equal but values in class is not equal? - java

package com.custom.wangzhi.myapp;
import android.util.Log;
public class TestUtil {
public void print(Class clazz, int t) {
try {
Log.i("print 1 ", "result " + R.layout.class.equals(clazz)
+ " " + R.layout.class.getClassLoader().equals(clazz.getClassLoader())
);
Log.i("print 2 ", R.layout.act1 + " " + clazz.getDeclaredField("act1").get(null)+" "+t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.custom.wangzhi.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.latzc1);
Log.i("MainActivity1", "wangzhi app " + R.layout.act1);
new TestUtil().print(R.layout.class, R.layout.act1);
}
Log:
11-26 10:07:23.097 7999-7999/com.custom.dynamic.layoutcastdemo I/MainActivity1: wangzhi app 2130968577
11-26 10:07:23.097 7999-7999/com.custom.dynamic.layoutcastdemo I/print1 : result true true
11-26 10:07:23.097 7999-7999/com.custom.dynamic.layoutcastdemo I/print2 : 2130968576 2130968577 2130968577
MainActivity1 is a library module
if i run by the default in android studio is ok ,but when i use layoutcast (i do some change in this ) run,then print log in above
what layoutcast do:
1.it will find the code which is changed(compare the "projectdir/build/outputs/**.apk" 's time )
2.use aapt package all resource to generate a res.zip and R.java 3.use javac,dex all changed java file to generate a dex 4.then translate the res.zip and dex to android phone, 5. use DexClassloader load the dex and generate a new Resource which add res.zip to replace the system Resource .6.finally ,reboot the application.
my english is poor ,and first ask in stackoverflow,so if anyone don't know my mean ,please contact me . thanks very much

Related

How to manipulate files by ffmpeg in Android 31: permission denied

I am trying to use FFmpeg in my android app. So I want to test it if it works before moving on. I use an external library : github link
The code looks like this :
package net.omidn.aslanmediaconverter;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.arthenica.ffmpegkit.ExecuteCallback;
import com.arthenica.ffmpegkit.FFmpegKit;
import com.arthenica.ffmpegkit.FFmpegSession;
import com.arthenica.ffmpegkit.Session;
import net.bramp.ffmpeg.job.FFmpegJob;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
FFmpegJob myjob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.text_view);
FFmpegJob job = null;
File inFile = new File("/storage/emulated/0/video_2021-05-29_17-50-20.mp4");
String inputName = Uri.fromFile(inFile).toString();
Log.d(TAG, inputName);
Log.d(TAG,"file exists : " + String.valueOf(inFile.exists()));
Log.d(TAG,"file canRead : " + String.valueOf(inFile.canRead()));
FFmpegSession fFmpegSession = FFmpegKit.executeAsync("-i file:///storage/emulated/0/video_2021-05-29_17-50-20.mp4 -c:v mpeg4 file:///storage/emulated/0/out.mp4",
new ExecuteCallback() {
#Override
public void apply(Session session) {
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
textView.setText("" + fFmpegSession.getState().name() + " " + fFmpegSession.getOutput());
}
}
As you can see I give the files with file:/// protocol. If I don't use that the resault is the same. The three lines of Log.d(...) will print :
2021-06-03 00:58:08.869 8376-8376/net.omidn.aslanmediaconverter D/MainActivity: file:///storage/emulated/0/video_2021-05-29_17-50-20.mp4
2021-06-03 00:58:08.869 8376-8376/net.omidn.aslanmediaconverter D/MainActivity: file exists : true
2021-06-03 00:58:08.869 8376-8376/net.omidn.aslanmediaconverter D/MainActivity: file canRead : false
The video file has read access on the storage :
I found a way to do this from the libraries wiki page.
I will quote it here:
If you want to use a file selected using Storage Access Framework (SAF) with FFmpegKit, you can use the following methods to convert a Uri to a file path defined with FFmpegKit's saf: protocol. That path can be safely used as input or output in FFmpegKit and FFprobeKit commands.
Input
Uri uri = intent.getData();
String inputPath = FFmpegKitConfig.getSafParameterForRead(requireContext(), uri);
FFmpegKit.execute("-i " + inputPath + " ... output.mp4");
Output
Uri uri = intent.getData();
String outputPath = FFmpegKitConfig.getSafParameterForWrite(requireContext(), uri);
FFmpegKit.execute("-i input.mp4 ... " + outputPath);
The wiki page on GitHub

Cannot find main class in bukkit plugin

I am having trouble with my plugin. The error is "Cannot find main class 'turtdle.abilities.Main'" (I know I spelled turtle wrong, but it is my username.)
This plugin is for my server. I have already tried completing the plugin.yml file (with author, version, etc.) I also tried changing the plugin name to "Main." I have also tried moving the yml around with no success.
package turtdle.abilities;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin{
public Permission playerPermission1 = new Permission("turtdle.abilities.get");
public Permission playerPermission2 = new Permission("turtdle.place.bedrock");
#Override
public void onEnable() {
getLogger().info("onEnable Has been enabled for abilities plugin! BOOP!");
new PlayerListener(this);
new BlockRestricter(this);
PluginManager pm = getServer().getPluginManager();
pm.addPermission(playerPermission1);
pm.addPermission(playerPermission2);
}
#Override
public void onDisable() {
getLogger().info("onDisable Has been triggered for abilities plugin");
}
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (cmd.getName().equalsIgnoreCase("hello") && sender instanceof Player) {
Player player = (Player) sender;
player.sendMessage("Hewwooo, " + player.getName());
return true;
}
return false;
}
}
package turtdle.abilities;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
public class PlayerListener implements Listener{
public PlayerListener(Main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
#EventHandler
public void onDeath (PlayerDeathEvent e) {
Player player = e.getEntity();
if (!player.hasPermission("turtdle.abilities.get")) {
player.sendMessage(ChatColor.AQUA + "OOF");
}
else {
{
player.sendMessage(ChatColor.AQUA + "you should've abused...");
}
}
}
}
package turtdle.abilities;
import org.bukkit.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class BlockRestricter implements Listener{
public BlockRestricter(Main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
#EventHandler
public void onBlockPlace (BlockPlaceEvent e) {
Player player = e.getPlayer();
Block block = e.getBlock();
if (!player.hasPermission("turtdle.place.bedrock") && block.getType().getId() == 7) {
player.sendMessage(ChatColor.RED + "You CAN'T PLACE THIS " + ChatColor.BOLD + "BLOCK! " + ChatColor.RESET + ChatColor.RED + " it is ILLEGAL");
e.setCancelled(true);
}
}
}
plugin.yml:
main: turtdle.abilities.Main
name: TurtdleAbilitiesCore
version: 0.2.9
author: CakeyTheTurtdle
description: ExclusiveWolfHuntplugin
commands:
hello:
description: When you're lonely
usage: /hello
Hey here is my whole error
https://pastebin.com/FAieE0Lr
The other answer is not correct, unfortunately.
In the Pastebin you linked, we can see that the error is the following:
Caused by: java.lang.ClassNotFoundException: turtdle.Main
When Bukkit is trying to load your main class, it is looking for the class turtdle.Main. The reason this is strange is your plugin.yml tells it to look for turtdle.abilities.Main, which it is not doing.
My guess for the cause of the issue is that sometimes when the project is being compiled, your IDE may not actually grab the edited plugin.yml file to put in the final jar. To fix this, complete the following steps:
Open your project folder and delete any/all of the following files/folders if they exist:
bin/
target/
YourPluginName.jar
Go to your server's folder and delete YourPluginName.jar there as well
Recompile your project and add the fresh jar file to your plugins folder.
Hopefully, this should resolve the issue. Your plugin.yml file and code both look fine and in theory should work. This is the only thing I can think of that would cause the issue.
Best of luck!

Android - Java - No Activity Found to Handle Intent

I am trying to create an Android / Java plugin for the cross-platform program Phonegap / Cordova 3.2. I am following several tutorials but can't get the simplest plugin to work.
Currently I am working on the idea that my Java code is just wrong somewhere.
Could someone please review the following code and advise if there is something obviously wrong?
The error I keep getting is
Exception: No Activity found to handle Intent { act=android.intent.action.MEDIA_SCANNER_SCAN_FILE dat=file:///{"fullPath":"media\/test.mp3"} }
Here is my .java file
package org.media.scan;
import java.io.File;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import android.net.Uri;
public class Scan extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if ( action.equals("addRemove") ) {
String filePath = args.getString(0);
filePath = filePath.replaceAll("^file://", "");
if (filePath.equals("")) {
callbackContext.error("null path passed");
return false;
}
File file = new File(filePath);
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(file));
this.cordova.getActivity().startActivity( scanIntent );
callbackContext.success("good");
return true;
} else {
callbackContext.error("invalid action phrase");
}
return false;
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
}
I am calling my Java code with this .js code
var Scan = {
createEvent:function (fullPath, successCallback, errorCallback) {
cordova.exec(
successCallback, // success callback function
errorCallback, // error callback function
'Scan', // mapped to our native Java class
'addRemove', // with this action name
[
{
"fullPath":fullPath
}
]
);
}
}
module.exports = Scan;
It's a broadcast action not activity action, you should use the send broadcast method for this kind of action!
http://developer.android.com/reference/android/content/Intent.html#ACTION_MEDIA_SCANNER_SCAN_FILE
This is the wrong line in code " this.cordova.getActivity().startActivity( scanIntent );
"

NullPointerException getDefaultSharedPreferences()

I keep getting NullPointerException on this line:
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
I ran some things through and I believe that I have the wrong context as it is in a subpackage of the main package so I don't think it can reference the XML preference files. I have used this in class's that are in the main package with no trouble but for some reason this causes an exception.
Full code:
package schoolBook.Icestone.Expandable;
import schoolBook.Icestone.Days;
import schoolBook.Icestone.Main;
import schoolBook.Icestone.SetPreference;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class Lesson1 extends Lessons {
public Lesson1(String name) {
super(name);
// setGroup(" " + Days.getLessonarray(0) + " ");
String key = "W" + Main.getWeek() + "_" + SetPreference.xmlday + "_L"
+ SetPreference.xmllesson + "_Lesson";
System.out.println(key);
try {
SharedPreferences myPreference = PreferenceManager
.getDefaultSharedPreferences(this);
String group = myPreference.getString(key, "def");
setGroup(" " + group + " ");
} catch (NullPointerException ex) {
ex.printStackTrace();
setGroup(" " + Days.getLessonarray(0) + " ");
}
}
}
Lessons class extends Activity so think that may be the source of my problem but im not sure.
File structure:
Icestone
Main.class and some other classes that use shared preference and it works fine
Lessons package (Lesson1 & Lesson are in this package)
XML folder with the preferences in it
if anyone could help shed some light on this problem it would be much appreciated
You can't do this inside the constructor.
If it extends Activity Class it should't has a constructor, you need to handle that inside the oncreate method.

Compilation error on Zxing

Since I don't own a G1 for development purposes, I am doing my best with the emulator.
This said, I am trying to scan a JPEG image or a PNG image in my sdCard, with the ZXing (Zebra Zrossing) library.
I tried to change the code in the Android project, so it would scan from an image in the sdCard, instead from the camera, without any luck.
What I did next is probably the root of my problem.
I tried to use the JAVASE code, within a new Android Project, to provide an image to the "modified" CommandLineRunner, and here is the thing:
Eclipse would build the project, but won't run it.
The VM log throuws me this message among others:
**02-08 20:47:45.916: WARN/dalvikvm(619): VFY: unable to resolve static method 939: Ljavax/imageio/ImageIO;.read (Ljava/io/File;)Ljava/awt/image/BufferedImage;
02-08 20:47:45.926: WARN/dalvikvm(619): VFY: rejecting opcode 0x71 at 0x0004
02-08 20:47:45.926: WARN/dalvikvm(619): VFY: rejected Lcom/magoco/fread/FRead;.decode2 (Ljava/io/File;Ljava/util/Hashtable;Ljava/lang/String;)Ljava/lang/String;
02-08 20:47:45.926: WARN/dalvikvm(619): Verifier rejected class Lcom/magoco/fread/FRead;
02-08 20:47:45.926: WARN/dalvikvm(619): Class init failed in newInstance call (Lcom/magoco/fread/FRead;)
02-08 20:47:45.926: DEBUG/AndroidRuntime(619): Shutting down VM
02-08 20:47:45.926: WARN/dalvikvm(619): threadid=3: thread exiting with uncaught exception (group=0x40010e28)
02-08 20:47:45.937: ERROR/AndroidRuntime(619): Uncaught handler: thread main exiting due to uncaught exception
02-08 20:47:45.946: ERROR/AndroidRuntime(619): java.lang.VerifyError: com.magoco.fread.FRead
**
I searched the web for an answer and I got someone saying that this is common error on the Dalvikvm due to the fact that there is might be a class or library that was precompiled (true, outside Eclipse) and the VM wouldn't be able to use it.
I am posting my code in the main Activity:
package com.magoco.fread;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.TextView;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MonochromeBitmapSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
public class FRead extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) this.findViewById(R.id.BarcodeResult);
try {
tv.setText(this.decodeOneArgument2("", false));
} catch (Exception e) {
e.printStackTrace();
}
}
public String decodeOneArgument2(String argument, boolean dumpResults)
throws Exception {
String barcode = "";
// File inputFile = new File(argument);
File inputFile = new File("sdcard/dcim/pueblo.JPG");
/* TESTING THAT I'VE GOT A FILE */
System.out.println("FILE " + inputFile.toString());
// decode(new URI(argument), hints);
decode2(inputFile, null, barcode);
return barcode;
}
public String decode2(File f, Hashtable<DecodeHintType, Object> hints,
String barcode) throws IOException {
/* IF I COMMENT THE NEXT LINE, IT RUNS BUT OF COURSE NO RESULT */
BufferedImage image;
try {
image = ImageIO.read(f);
} catch (IllegalArgumentException iae) {
throw new FileNotFoundException("Resource not found: " + f);
}
try {
MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(
image);
Result result = new MultiFormatReader().decode(source, hints);
ParsedResult parsedResult = ResultParser.parseResult(result);
barcode = " format: " + result.getBarcodeFormat()+ result.getText() + "\nParsed result:\n"+ parsedResult.getDisplayResult();
System.out.println(" format: " + result.getBarcodeFormat()+ result.getText() + "\nParsed result:\n"+ parsedResult.getDisplayResult());
//return result;
} catch (ReaderException e) {
System.out.println(": No barcode found");
return null;
}
return barcode;
}
}
Thanks in Advance
monn3t
Hai,
I tried to extract the data from the Barcodes and these are the steps i followed.
1.Download ZXing 1.3 and extract it.
2.Add the core/src and androidtest/src from the extracted zxing floder to the android application by setting the property.
use this link to set the property,http://groups.google.com/group/zxing/browse_thread/thread/7d8693e6e42408f2
Now include the following code,
package payoda.android.zxingApp;
import android.app.Activity;
import android.database.CursorJoiner.Result;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MonochromeBitmapSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.client.androidtest.*;
import com.google.zxing.common.BaseMonochromeBitmapSource;
public class ZXingApplication1 extends Activity
{
TextView tv;
com.google.zxing.Result result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.bar2);
MultiFormatReader reader1=new MultiFormatReader();//For all barcode formats
QRCodeReader reader=new QRCodeReader();//Only for QRCode format
try
{
result=reader1.decode(new RGBMonochromeBitmapSource(bitmap));
tv.setText(result.getText());
}
catch (Exception e)
{
tv.setText("Within Catch block");
}
}
}
This may be helps you.
This is Sean from the project in question.
You are trying to use the code intended for Java SE in Android. Some of the libraries in Java SE are not in Android, like ImageIO.
Look at the code in android/ which uses Android-specific classes to load images.

Categories

Resources