jquery mobile and phonegap addJavascriptInterface - android

I am developing an Android app with jQuery Mobile and PhoneGap. This is my activity:
public class xxx extends DroidGap {
/** Called when the activity is first created. */
private String FILENAME = "";
private static final String HTML_ROOT = "file:///android_asset/www/";
private Handler handler = null;
private static WebView webView = null;
public MyTeam team = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
handler = new Handler();
FILENAME = getString(R.string.fileName);
//parsing data from file
String json = readFile();
team = parseJson(json);
appView.addJavascriptInterface(this, "MyTeam");
super.loadUrl("file:///android_asset/www/menu.html");
}
public String HW(){
return team.getTeamName();
}
And this is my Javascript code in menu.html:
$(document).ready(function(){
alert(MyTeam.HW()); // work perfectly
alert("name "+MyTeam.team.getTeamName()); //doesn't work!
});
So the problem is:
I can access the HW function that returns me team.getTeamName();
I don't have access to the team variable name in my activity because MyTeam.team.getTeamName() doesn't work.
It seems that I can access only functions but not directly public variables.
What I am doing wrong?
Thanks.

You can't access the Java objects fields directly. It's right there in the documentation of addJavaScriptInterface. Also, if you are using PhoneGap then you should just write a plugin and let us worry about the cases where addJavaScriptInterface falls down.

Related

android embedding unity: ways to initialize and call a SQLite java DB object from unity, which needs "Context"?

I have a SQLite helper class like:
public class GameDbHelper extends SQLiteOpenHelper {...}
If in the android java world, I have to initialize it in the body of an activity like:
public class MainActivity extends AppCompatActivity {
...
GameDbHelper gameDBHelper;
protected void onCreate(Bundle savedInstanceState) {
...
gameDBHelper = new GameDbHelper(this);// "this" being the Context
// database: what ultimately is needed to perform CRUD
database = databaseHelper.getWritableDatabase();
}
I want to initialize this gameDBHelper in Unity side and from there call, say, database.insert(...);
From Unity documentation I learned it is possible to initialize an object to call it's methods:
void Start() {
AndroidJavaObject jo = new AndroidJavaObject("android.content.res.Configuration");
jo.Call("setToDefaults");
}
I think that perhaps I must first initialize the "gameDBHelper = new GameDbHelper(this);" in the Unity Activity:
- export the Unity project into Android Studio
- in the UnityPlayerActivity, define object and initialize it
- "somehow" call it from Unity code (defined before exporting)
A different approach:
- to export the database class as a lib from Android studio into Unity
it is more comfortable for me in Android studio, because in this project I have, Unity is not to be the launcher activity.
Please instruct me how to properly do this.
I try to document relevant parts of my own solution, just in case that may help someone. Please if you see any problem in it, let me know (I'm only learning).
I didn't know that I could pass (inject) "Context" to the constractor of a java class that need it, from Unity side. I found it on this forum, thaks to the forum!
Unity side:
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
AndroidJavaObject jo = new AndroidJavaObject("com.my.package.MyDbHelper", context);
string word = jo.Call<string>("returnData");
tx.text = word;
This will pass context to an Android studio java class constructor, which will then initialize a SQLite database and a helper class that will manipulate it. The class relevant data as example, in Android studio:
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
// implement as documentation describes, link is provided bellow
}
// this is the class, addressed from Unity
public class MyDbHelper{
String str = null;
private SQLiteDatabase db;
MySQLiteOpenHelper mySQLiteOpenHelper;
public myDbHelper(Context context) {
mySQLiteOpenHelper = new mySQLiteOpenHelper(context);
db = mySQLiteOpenHelper.getWritableDatabase();
}
// this is the method that unity calls
public String returnData(){
return queryAndDisplayAll();
}
private String queryAndDisplayAll() {
// using Cursor and db perform query and get the result, say, in a str, and return it, that is like:
// Cursor cursor = db.query(DicSQLiteOpenHelper.TABLE_NAME,...
// str = ...result from Curson...
return (str == null ? "No result!" : str);
}
Here you could read about the SQLiteOpenHelper:
Link to SQLiteOpenHelper documentation.

How can I use Java Plugin in Unity

I try make a plugin in android studio to use in Unity.
So I make this method in android studio.
public class MainActivity extends UnityPlayerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static String SendMessage(){
return "Message";
}
}
and in Unity,
public class PluginWrapper : MonoBehaviour {
// Use this for initialization
void Start () {
TextMesh textMesh = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass ("com.thewell_dev.beaconf.MainActivity");
textMesh.text = plugin.CallStatic<string> ("ReturnMessage");
}
}
to use SendMessage() method in unity, using AndroidJavaClass and CallStatic.
It is success.
I can check message in device by unity.
But, one error occurs.
If I change method like this,
public class MainActivity extends UnityPlayerActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String SendMessage(){
return "Message";
}
}
change SendMessage method type.(static String to String)
and in Unity,
public class PluginWrapper : MonoBehaviour {
// Use this for initialization
void Start () {
TextMesh textMesh = GetComponent<TextMesh> ();
var plugin = new AndroidJavaClass ("com.thewell_dev.beaconf.MainActivity");
textMesh.text = plugin.Call<string> ("ReturnMessage");
}
}
change plugin.CallStaic to plugin.Call
In case, I just delete Static, but it returns no result.
https://docs.unity3d.com/kr/current/ScriptReference/AndroidJavaClass.html
I just change the type. But no returns.
I think I mistake to Call method by AndroidJavaClass,
but I can't find it.
If you know about it, Please help me.
You can use "types" to invoke static methods, as static things are bound to their defining types. You can't, however, use instance methods (non-static methods, that is) without an instance of the type. That's why your second attempt fails. To invoke instance methods, you must get an instance of the type, either by making one yourself by invoking the java constructor like this:
var object = new AndroidJavaObject ("com.some.class", constructor_param1, constructor_param2, constructor_param3, ...);
result = object.Call<string> ("SomeMethod");
Or, to get as instance of something like an activity which is constructed outside the scope of your C# script, you use static methods to retrieve the instance you're looking for:
var type = new AndroidJavaClass ("com.some.class");
var object = type.CallStatic<AndroidJavaObject>( "SomeStaticGetterMethod" );
result = object.Call<string> ("SomeMethod");

In libgdx on Android, how do I save game state in case app is killed?

In Android, we usually save all of our state variables in the onSaveInstanceState() callback by putting them in the Bundle provided.
How do people deal with saving/loading game state variables with libGDX as the classes can't use/return a Bundle object?
This is quit simple! You can use Preferences for that. You can store values in the Preferences. On android the backend uses the SharedPreferences from Android itself. On desktop its saved as an xml somewhere in the user folder.
I wrote a simple Helper to save options and get the options of my game. Here is some code out of it. (Note, dont forget to flush after saving something)
public class PreferencesHelper {
public final static String PREF_NAME_OPTION = "options";
private final static String VOLUMEN = "volumen";
private final static String VIBRATE = "vibrate";
private final static String EFFECT_VOLUMEN = "effect";
private final static String FIRST_START = "start";
private Preferences optionPref = Gdx.app.getPreferences(PREF_NAME_OPTION);;
public PreferencesHelper() {
optionPref = Gdx.app.getPreferences(PREF_NAME_OPTION);
}
public float getVolumen() {
return optionPref.getFloat(VOLUMEN);
}
public void setVolumen(float vol) {
optionPref.putFloat(VOLUMEN, vol);
optionPref.flush();
}
public boolean getVibrate() {
return optionPref.getBoolean(VIBRATE);
}
public void setVibrate(boolean vibr) {
optionPref.putBoolean(VIBRATE, vibr);
optionPref.flush();
}
public float getEffectVolumen() {
return optionPref.getFloat(EFFECT_VOLUMEN);
}
public void setEffectVolumen(float eff) {
optionPref.putFloat(EFFECT_VOLUMEN, eff);
optionPref.flush();
}
}
This is how i save my options. To save an character you do the same but save all importand stuff you need, to recreate your character when loading the game again. You can also have more than one prefrerence!
I hope this helped.

How to use global class variables in android

Hi I am doing one app here. I'm using global class varibles. It's working well, but if I'm using more globalclass variables I'm getting memory exceptions some times.
I tried this:
public class SecondClass extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText("Global String : " + GlobalClass.myVal);
}
}
class GlobalClass extends Application {
static String myVal;
}
Is this correct or not?
First thing, you dont need Static Variable to declare global variable in Application Class,
so Change your code to:
class GlobalClass extends Application {
public String myVal;
}
then whereever you need to access this data, get Application object by:
GlobalClass global=(GlobalClass)context.getApplication();
global.myVal="anything";
You can use like this
public class GlobalVar {
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
private int myVar = 0;
private static GlobalVar instance;
static {
instance = new GlobalVar();
}
private GlobalVar() {
}
public static GlobalVar getInstance() {
return GlobalVar.instance;
}
}
then you can call like
GlobalVar.getInstance().setMyVar(int);
You can also use Global Variable Activity class wise. As for example
public class SecondClass extends Activity {
String S1,S2,S3;
EditText edt1,Edt2,Edt3;
Button btn1,btn2,btn3;
//like this wat Declare all variable you want to use in your Present Activity Class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
edt1= (EditText)findViewById(R.id.tv);
}
}
Take a look at the post Singletons vs. Application Context in Android?
There are a lot of discussion about Singletons vs Application objects in the forum.
I'm personally inclined to Application object with properties. If you dont want to keep in memory a lot of objects use a LruCache (there is a pre v11 implementation in the compatibility package) to low your memory requirements.
Take into account you will eat the same amount of memory using Singletons than using the Application object, all objects will be keep in memory until you free them (remove any refrence to them and let the GC purge them from memory).

android - How to backup the data without using database even if the app closes

In my application i want to maintain data without using the local DB even if the application closes. For this i created one class in my app, in that i created static variables so we can access them anywhere in the app. But here some times data is gone i don't know why it's happen. this process is good or any better is there? Somewhere i read that Shared Preferences is useful but i don't know about that.please can anyone share your ideas.
public class AJ_Constant {
//New Food Item
public static String strEntrySavedFoodItem = "";
public static String strReportsSavedFoodItem = "";
public static ArrayList<String> arrFoodItems = new ArrayList<String>();
}
public class ReportsContentActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = LayoutInflater.from(getParent()).inflate(R.layout.reports_content, null);
setContentView(contentView);
AJ_Constant.arrFoodItems.add("Sample"); }}
thanks
Visit http://android-er.blogspot.in/2011/01/example-of-using-sharedpreferencesedito.html
you can save your data by creating shared preferences.
you can have a look here. there are samples how to use SharedPreferences

Categories

Resources