Android Service reads localStorage? - java

I have developed a PhoneGap application for Android.
The application is composed by the webapp (HTML/jQuery) and a background service (Java code) that's started by the webapp.
This webapp writes to window.localStorage like
<script>
window.localStorage.setItem("name","MyName");
</script>
Is it possible to read this name that is in the localStorage from my Java code?

This is possible. To execute JavaScript and get response you can do as follows:
Define JavaScript callback interface in your code:
class MyJavaScriptInterface {
public void someCallback(String jsResult) {
// this will be passed the local storage name variable
}
}
Attach this callback to your WebView:
MyJavaScriptInterface javaInterface = new MyJavaScriptInterface();
webView.addJavascriptInterface(javaInterface, "HTMLOUT");
Run your JavaScript calling window.HTMLOUT.someCallback from the script:
webView.loadUrl("javascript:( function () { var name = window.localStorage['name']; window.HTMLOUT.someCallback(name); } ) ()");
Note - window.localStorage['name'] is the same as window.localStorage.getItem('name')
This post here on stackoverflow helped me
You might need to use super.webView.addJavascriptInterface or super.addJavascriptInterface to add the interface. You might need to use super.webView.loadUrl or super.loadUrl to invoke this. It all depends on where you are going to be calling these from.

Use cordova-plugin-nativestorage plugin to read localstorage in android java file.
it's for IOS,Android Plateform
this plugin use nativeStorage
Cordova Syntax:
NativeStorage.setItem("reference", obj, setSuccess, setError);
function setSuccess(obj){
}
function setError(obj){
}
Anroid JAVA:
SharedPreferences sharedPreferences = getSharedPreferences("MainActivity", MODE_PRIVATE);
System.out.println("********--------- shared pref values... " + sharedPreferences.getString("myid", "no value"));

Related

How to do event handling for android and iOS in react native's new architecture for fabric components?

I am trying to create a Fabric component. I have got it working for the most part. The only issue I am facing is I am not able to get click listener to work for a fabric component.
I created a spec file
import type {HostComponent, ViewProps} from 'react-native';
import type {DirectEventHandler} from 'react-native/Libraries/Types/CodegenTypes';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
type Event = Readonly<{
value: string;
}>;
interface NativeProps extends ViewProps {
text: string;
onClickHandler?: BubblingEventHandler<Event>; ////Event name should start with on
}
export default codegenNativeComponent<NativeProps>(
'MyButtonView',
) as HostComponent<NativeProps>;
For android my fabric component looks like as follows
public class MyButtonView extends androidx.appcompat.widget.AppCompatButton {
public MyButtonView(Context context) {
super(context);
configureViews();
}
private void configureViews(){
setBackgroundColor(Color.YELLOW);
setOnClickListener(view -> {
onReceiveNativeEvent();
});
}
public void onReceiveNativeEvent() {
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTModernEventEmitter.class)
.receiveEvent(getId(),getId(),"onClickHandler",true,0,event,1);
}
}
Not sure what to pass first param as int, canCoalesceEvent, customCoalesceKey and category in receiveEvent
In ViewManager I did add following code as well
#Nullable
#Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
Log.i("here55","999999");
return MapBuilder.of("onClickHandler",
MapBuilder.of("registrationName", "onClickHandler")
);
}
For android I am not getting the callback from native android to js side
I am following https://reactnative.dev/docs/native-components-android but it was for the old architecture and I think is not applicable for fabric components
Same for iOS https://reactnative.dev/docs/native-components-ios, the doc is not very helpful for the new architecture
For iOS, I created the header and objective-c++ file
Typically if we want to add property we do this
RCT_EXPORT_VIEW_PROPERTY(text, NSString)
Not sure how to do it for event handler
iOS
Assuming native spec you posted is correct (I'm not really familiar with TypeScript + Codegen duo) when you run pod install command in your ios/ directory codegen should generate EventEmitters cpp file (+ header) in React-Codegen pod (you can see below how to find it in XCode)
link to the screenshot with Pods structure
You can then use these classes in your Objective-C++ code to emit the events:
if (_eventEmitter != nullptr) {
std::dynamic_pointer_cast<const facebook::react::$$NAME OF YOUR EVENT EMITTER TYPE$$>(_eventEmitter)
->onEvent(facebook::react::$$NAME OF YOUR EVENT EMITTER TYPE::OnEvent{.value = $$VALUE$$});
}
See links below to see how it is done in react-native-screens
Native component spec in Flow
Event emission in Obj-C++ code
Event exposure in screen manager - I'm not quite sure if this line is necessary, haven't tested it out yet.
Android
To trigger codegen just run native build.
Define native event class as done here
Take a look here for how to dispatch event
Export your event types

Unity AndroidJavaObject not working without showing errors

I have been trying to call a Java method in unity. Not working for me, even the simplest example from the docs
using System.Collections;
using UnityEngine;
public class ExampleClass : MonoBehaviour {
void Start () {
AndroidJavaObject jo = new AndroidJavaObject ("java.lang.String", "some string");
int hash = jo.Call<int> ("hashCode");
Debug.Log ("hash=" + hash);
}
}
Unity console prints hash=0, which is not the hash code for provided String. Even if I change and use java.lang.StringInvalidClass as class name, unity still reports same result to the console without notifying errors. I can even try to call toString, toStringa, toInvalid2 and they always return empty string without showing errors.
This is a brand new 2d project with only script displayed above, attached to camara object. I am using Ubuntu, Unity 2019.4 and project platform is Android.
Thanks for the assistance.
Answering myself after some time working with unity.
All examples in the web and unity documentation doesn't mention it, which is weird since it is something simple to mention and about confusions: code needs to run as an android application. Editor or even unity remote does not work, in order to use AndroidJavaObject and related classes, your code needs to run as an android application installed in the phone.

Cannot insert object in Parse.com with parse4j API in JAVA

I am using Parse.com for communicating with iOS application and Web Browser. I have registered in parse.com and created an application. Now I have an iOS application ready to insert an object in that application which is working fine. Now comes the backend part, I am using JAVA for web application. Now,
https://parse.com/docs/api_libraries
According to this link, I can see the API/ Libraries I can use in JAVA is
Almonds
mobile-parse-api
Parse4j
ParseFacade
Among this 4, I have selected Parse4j to build web application with.
I am using Eclipse, I have installed GWT plugin, created a web application. Now I am adding this parse4j.jar file to that project, Added it to the build path also. And then I try to write this code
try {
Parse.initialize("my app id", "my rest app id");
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.save();
return "OK";
} catch(IllegalArgumentException e){
e.printStackTrace();
return "KO";
}
catch(ParseException e){
e.printStackTrace();
return "KO";
}
It doesn't insert the object to parse cloud. Please help why isn't working? Am I missing anything to write?
As far as I see, the code is correct. However, if Parse4j does not save the entry
this means that you write wrong the attribute name or class name. Just check the names
and class name then reply back.
Regards.
One way to validate is the do a Query, get the object and print all the attributes / data types. Then store these as static class level constants and use them throughout your class for setting values in new objects to persist.
If the get query doesn't work (without any filters), which means your class name is incorrect.
Good Luck!

Using Telegram API for Java Desktop App?

I am not that new to Java Programming, but I have never worked with external libraries etc. Now I want to develop a desktop client for the "Telegram" open-source messaging platform, and I'm stuck when it comes to API-Usage.
There is pretty much documentation about the Telegram API, found at https://core.telegram.org/api, and I've already downloaded mtproto, telegram-api and tl-core from github, and compiled my own library jar from source by using gradle. As well, I've already written a small application, where the user clicks a button and is promted to enter his phone number, I'm using the Java-swing-Libraries and an ActionListener for this.
The phone number entered by the user should now be checked if it is already registered, the auth.checkPhone method seems to be capable for that. But how can I refer to it within my eclipse project? I don't see any method "checkPhone" in any of the classes! What should I do?
Please help me, I can't help myself and I am desperately stuck in my project. Even a small hint would help.
Thanks in Advance,
Lukas
Essentially you will have to fill out the blanks in the code given on GitHub in the ex3ndr/telegram-api repository. If you've got the library Jar file you built and the tl-api-v12.jarfile on your Eclipse project's Java build path, then look at the RPC Calls section of the README and
First you need to set up an AppInfo object with your API credentials, then you will also have to create some new classes that implement the AbsApiState and ApiCallback interfaces. Once these are available, you can create the TelegramApi object and make an RPC call to the Telegram service as follows; in this case using the suggested auth.checkPhone method:
// TODO set up AbsApiState, AppInfo and ApiCallback objects
TelegramApi api = new TelegramApi(state, appInfo, apiCallback);
// Create request
String phoneNumber = "1234567890";
TLRequestAuthCheckPhone checkPhone = new TLRequestAuthCheckPhone(phoneNumber);
// Call service synchronously
TLCheckedPhone checkedPhone = api.doRpcCall(checkPhone);
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
The TelegramApi object represents your connection to the remote service, which is a request response style of API. RPC calls are made via the doRpcCall method, which takes a request object from the org.telegram.api.requests package (the TLRequestAuthCheckPhone type in the example) filled in with the appropriate parameters. A response object (TLCheckedPhone above) is then returned with the result when it is available.
In the case of an asynchronous call the method returns immediately, and the onResult callback method is executed when the result is available:
// Call service aynchronously
api.doRpcCall(checkPhone, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() { }
public void onResult(TLCheckedPhone result) {
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
}
public void onError(int errorCode, String message) { }
});
Or just look at this API https://github.com/pengrad/java-telegram-bot-api
It is really simple to use

android: call javascript from java problem

I want to know if there is way to call javascript from java on android?
In my program, I interact java and javascript together. I am using java to receive response(json data) from TCP server and save them into a file. In webview I am using javascript jQuery getJSON() function to retrieve that file and using jQuery plot chart library to draw chart. Now, there is no relationship between java and javascript. Every time when I update data and file, I still need to click a button in webview to trigger the draw function. I want the programmes to be smart and handy. Is that a way to call or execute javascript from java. I know one way:
Button update = (Button)findViewById(R.id.update);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
wv.loadUrl("javascript:document.write('hello')");
}
});
But the problem is I already do a index page by loadurl().
final WebView wv = (WebView) findViewById(R.id.webkankan);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/index.html");
When I trigger this click event, all contents were gone only a string "hello" there. Another thing is why I need to change webview's type to final to avoid eclipse error. Does this is the problem to trigger my main problem? If so, how can I fix it?
Thanks for you patience.
Cheers!
For instance you have a javascript method in the index.html called loadData() which reads the file you saved in the java, then what you can do is wv.loadUrl("javascript:loadData()");. This actually call the javascript method and you can then read the file in that method. Hope this solves your problem.
or in simple terms. jus do this webView.loadUrl("javascript:jsmethodname()"); to execute javascript from java.
You can try to communicate java with javascript registering a java object to the webview that is executing the javascript.
The method addJavascriptInterface from Webview will allow you to make available a Java object to the Javascript scope, something like this:
WebView mWebView = new WebView(mContext);
//... webview initialization, js enabling etc.
MyProxyObject obj = new MyProxyObject(); //This object can interchange just basic types, but Strings are basic types
mWebView.addJavascriptInterface(obj,"myproxyobj");
With that code what you will have in the Javascript context you will have an object 'myproxyobj' that is actually a Java object.
Remember, you can interchange just basic types.
For more info check the following url:
http://developer.android.com/guide/webapps/webview.html
Specially check the section: Binding JavaScript code to Android code
Cheers,
Francisco

Categories