I want to use the BluetoothA2DPSink service in android,
it's a hidden class but I built a modified SDK and ROM and now Android studio can see it.
The problem is I can't use it, whenever i try
'BluetoothA2DPSink sink = new BluetoothA2DPSink()'
I get this error: "BluetoothA2DPSink() is not public in 'android.bluetooth.BluetoothA2dpSink'. Connot be accesed from outside package".
I verified it and it is in fact public:
"public final class BluetoothA2dpSink implements BluetoothProfile{..."
How can I use its methods?
Any help would be much appreciated.
If you pasted your error message correctly, the problem is not with the class, but with the constructor. Note the parentheses in "BluetoothA2DPSink() is not public in 'android.bluetooth.BluetoothA2dpSink'. Connot be accesed from outside package" — that is a reference to a constructor, not a class. Make sure the zero-argument constructor is public.
Try the below code. It is done using reflection. You can not simply create an object by calling the constructor for BluetoothA2DPSink. You also need to use another class BluetoothProfile.java.
Object mBluetoothA2DPSink;
/**
* This function will connect to A2DPsink profile of the server device to manage audio profile connection
*/
public void getBluetoothA2DPsink() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
try {
final int A2DPprofile = BluetoothProfile.class.getField("A2DP_SINK").getInt(null);
BluetoothProfile.ServiceListener mProfileListener1 = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == A2DPprofile) {
mBluetoothA2DPSink = proxy;
}
}
public void onServiceDisconnected(int profile) {
if (profile == A2DPprofile) {
mBluetoothA2DPSink = null;
try {
mContext.unregisterReceiver(mA2DPReciever);
} catch (IllegalArgumentException e) {
Log.e(TAG, e.getMessage());
}
}
}
};
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(mContext, mProfileListener1, A2DPprofile);
} catch (NoSuchFieldException | IllegalAccessException e) {
Log.e(TAG, e.getMessage());
}
}
Related
I have an app with many endpoints. I made a change to functionWhoIsCallingMe(). I want to find which controller endpoints call this function (directly or hierarchically) so I can test it.
#RequestMapping("/a")
someEndpoint(){
anyFunction()
}
#RequestMapping("/b")
anotherEndpoint(){
functionWhoIsCallingMe()
}
anyFunction(){
functionWhoIsCallingMe()
}
Given this code I want to know ["/a", "/b"] is calling functionWhoIsCallingMe().
I tried "Call Hierarchy" but that's not practical here because it would take to long to open all the tabs. I also tried filtering like suggested here, but that doesn't work because you can only specify one type of class to NOT match and if it doesn't match it wont show the calling method. I can't say only show files with Controller in the file name.
#RequestMapping("/b")
public void someEndpoint() {
anyFunction(1);
}
#RequestMapping("/b")
public void anotherEndpoint() {
functionWhoIsCallingMe(1);
}
public void anyFunction(int val/** init val=1*/) {
functionWhoIsCallingMe(val + 1);
}
public void functionWhoIsCallingMe(int val/** init val=1*/) {
try {
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
String defName = ste[val + 1].getMethodName();
String[] path = this.getClass().getMethod(defName).getAnnotation(RequestMapping.class).value();
System.out.println("Url path:" + path[0]);
} catch (Exception ex) {
}
}
I've just started to go away from tasks of the university and do my own projects.
I want to program a Java Telegram Bot to interact with further classes. Unfortunately I'm not able to add the dependency right or it just cant import all of the functions. I tried to follow multiple tutorials but I got errors in either of them. One of the most promising tutorials was the following: https://github.com/rubenlagus/TelegramBots/wiki/Getting-Started
I followed the instructions (added the library with Maven) and put in the code. After this I imported the needed librarie. However the program isn't able to call the method "execute" and I don't know why.
I hope I specified the topic detailled enough.
Thank you in advance.
Main Class:
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.meta.generics.LongPollingBot;
public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
try {
botsApi.registerBot((LongPollingBot) new Bot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
Bot Class
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
public class Bot extends TelegramLongPollingBot {
#Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message has text
if (update.hasMessage() && update.getMessage().hasText()) {
SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields
.setChatId(update.getMessage().getChatId())
.setText(update.getMessage().getText());
try {
execute(message); // Call method to send the message
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
#Override
public String getBotUsername() {
return null;
}
#Override
public String getBotToken() {
return null;
}
#Override
public void onClosing() {
}
}
Error
Error:(16, 17) java: cannot find symbol
symbol: method execute(org.telegram.telegrambots.meta.api.methods.send.SendMessage)
location: class Bot
in the POM.xml file I added the follow dependency:
<!-- https://mvnrepository.com/artifact/org.telegram/telegrambots -->
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>4.9.2</version>
</dependency>
You can also download directly the jar.
You must create and define the bot with BotFather, use a username, take the token and create the class that extends TelegramLongPollingBot.
Your problem is on the token and username that return always null. You must return the configuration created with BothFather.
You must set in the getters botToken and botUsername the token and username of bot.
return "<token>";
return "<username_of_bot>";
at least minimum the token.
I'm doing an android app and trying to integrate social login into the application using Azure Mobile Services.
public class SocialLogin extends Activity implements UserAuthenticationCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
// on create code
}
// All the code
#Override
public void onCompleted(MobileServiceUser user, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
//Take user to the logged in view
cacheUserToken(user);
} else {
Log.e("SocialLogin", "User did not login successfully");
}
}
}
I'm getting two errors because of the onCompleted method.
Error:(176, 5) error: method does not override or implement a method from a supertype
Error:(37, 8) error: SocialLogin is not abstract and does not override abstract method onCompleted(MobileServiceUser,Exception,ServiceFilterResponse) in UserAuthenticationCallback
Edit: Fixed the problem by deleting away the .jar file in my lib.
Per my understanding, 'UserAuthenticationCallback' is not an interface since many of samples are coding like this:
MobileServiceClient mClient = new MobileServiceClient(
"MobileServiceUrl",
"AppKey",
this).withFilter(new ProgressFilter());
mClient.login(MobileServiceAuthenticationProvider.MicrosoftAccount,
new UserAuthenticationCallback() {
#Override
public void onCompleted(MobileServiceUser user,
Exception exception, ServiceFilterResponse response) {
synchronized(mAuthenticationLock)
{
if (exception == null) {
cacheUserToken(mClient.getCurrentUser());
} else {
createAndShowDialog(exception.getMessage(), "Login Error");
}
}
}
});
Since it is not an interface, we cannot implement it as you did. You can either create a class that inherits UserAuthenticationCallback (but the class cannot inherit Activity as we can only inherit one class), or simply create a new instance of UserAuthenticationCallback like the code in the sample.
Also, I'd like to suggest you to check https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-get-started-users/ and https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-get-started-data/ for a completed sample of how to add authentication to your Mobile Services Android app.
This question already has answers here:
Better understaning - Class.forName("com.mysql.jdbc.Driver").newInstance ();
(4 answers)
Closed 10 years ago.
I am a java beginner and trying to insert a row in db. This is first time in java i am performing insertion operation. For around 2 Hrs i was googling and frustated and cannot solve my error. I called my friend and he gave live support for me in team viewer and added just one line of code to my program.
Class.forName("com.mysql.jdbc.Driver")
Can anyone please explain why we need to include this in my code before connection string. Is it necessary to place my code there each and every time. Please Explain me in Detail.
Here is some very simplified code that illustrates how driver initialization works. There are 3 classes, please put each one in an appropriately-named file.
import java.util.HashMap;
import java.util.Map;
public class DriverMgr {
private static final Map<String, Class<?>> DRIVER_MAP = new HashMap<String, Class<?>>();
public static void registerDriver(final String name, final Class<?> cls) {
DRIVER_MAP.put(name, cls);
}
public static Object getDriver(final String name) {
final Class<?> cls = DRIVER_MAP.get(name);
if (cls == null) {
throw new RuntimeException("Driver for " + name + " not found");
}
try {
return cls.newInstance();
} catch (Exception e) {
throw new RuntimeException("Driver instantiation failed", e);
}
}
}
public class MysqlDriver {
static {
// hello, I am a static initializer
DriverMgr.registerDriver("mysql", MysqlDriver.class);
}
#Override
public String toString() {
return "I am the mysql driver";
}
}
public class TestProg {
public static void main(final String... args) {
try {
Class.forName("MysqlDriver"); // try with or without this
} catch (Exception e) {
throw new RuntimeException("Oops, failed to initialize the driver");
}
System.out.println(DriverMgr.getDriver("mysql"));
}
}
When you call Class.forName, the driver class gets loaded and the static initializer gets executed. That in turn registers the driver class with the driver manager, so that the manager is now aware of it. Obviously, this only needs to be done once.
Class.forName("com.mysql.jdbc.Driver")
It must be required to load the driver of database which you are using.
the forNmae() method in this line load the driver of mysql database.
Yes , it's necessary to include every time .
but you can use a method for not repeating the codes .
for example
public void connectToMYSQL(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase","username",""password);
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
and before writing any sql statement , just call the method for example
public void insert(String sql)
{
connectToMYSQL();
//.. then do your stuffs
}
The basic idea is that this action forces the driver class to be registered in JDBC's driver manager.
The method Class.forName("fully qualified class name) is used to initialize the static fields of the class and load the JDBC driver class, MySQL driver in your case, to your application. When it is instantiated, it gets registered with the DriverManager. By the latter you create connections, using Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","login","password");, which you later use to query the database.
I have Java-related question:
I want to know is there a way to create path to class (in program) by using a variable(s).
Im making a program that will download pictures from certain sites and show them to a user. However, different sites have different forms, that's why I have to define a series of functions specific to each. They cannot be put in the same class because functions that preform same job (just for another site) would have to have same names. I'm trying to make adding support for another site later as simple as possible.
Anyway, the question is, could I call a function in program using a variable to determine its location.
For example: code.picturesite.functionINeed();
code is the package containing all of the coding, and picturesite is not a class but rather a variable containing the name of the desired class - that way I can only change value of the variable to call a different function (or the same function in a different class).
I don't really expect that to be possible (this was more for you to understand the nature of the problem), but is there another way to do what I'm trying to achieve here?
Yes, there is a way. It's called reflection.
Given a String containing the class name, you can get an instance like this:
Class<?> c = Class.forName("com.foo.SomeClass");
Object o = c.newInstance(); // assuming there's a default constructor
If there isn't a default constructor, you can get a reference to one via c.getConstructor(param1.getClass(), param2.getClass(), etc)
Given a String containing the method name and an instance, you can invoke that method like this:
Method m = o.getClass().getMethod("someMethod", param1.getClass(), param2.getClass(), etc);
Object result = m.invoke(o, param1, param2, etc);
I'm not immediately seeing anything in your question that couldn't be solved by, instead of having a variable containing a class name, having a variable containing an instance of that class -- to call a function on the class, you would have to know it implements that function, so you could put the function in an interface.
interface SiteThatCanFoo {
void foo();
}
And
class SiteA extends Site implements SiteThatCanFoo {
public void foo() {
System.out.println("Foo");
}
}
Then:
Site currentSite = getCurrentSite(); // or getSiteObjectForName(siteName), or similar
if (SiteThatCanFoo.isAssignableFrom(currentSite.class)) {
((SiteThatCanFoo)currentSite).foo();
}
So you want to do something like this (check ImageDownloader.getImageFrom method)
class SiteADownloader {
public static Image getImage(URI uri) {
System.out.println("invoking SiteADownloader on "+uri);
Image i = null;
// logic for dowlnoading image from siteA
return i;
}
}
class SiteBDownloader {
public static Image getImage(URI uri) {
System.out.println("invoking SiteBDownloader on "+uri);
Image i = null;
// logic for dowlnoading image from siteB
return i;
}
}
// MAIN CLASS
class ImageDownloader {
public static Image getImageFrom(String serverName, URI uri) {
Image i = null;
try {
// load class
Class<?> c = Class.forName(serverName + "Downloader");
// find method to dowload img
Method m = c.getDeclaredMethod("getImage", URI.class);
// invoke method and store result (method should be invoked on
// object, in case of static methods they are invoked on class
// object stored earlier in c reference
i = (Image) m.invoke(c, uri);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException
| InvocationTargetException | ClassNotFoundException e) {
e.printStackTrace();
}
return i;
}
// time for test
public static void main(String[] args) {
try {
Image img = ImageDownloader.getImageFrom("SiteB", new URI(
"adress"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}