In OOP, I can use the object to call its methods. So I want to do that in android using the same concept. However, it doesn't work. I used context to call the function updateLvl(int), but it said the method cannot be resolved. I want to know how can I use the context to call the method updateLvl?
public class MainActivity extends Activity {
private WebView webview;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPref = this.getPreferences(0);
editor = sharedPref.edit();
webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebViewJavaScriptInterface2(this), "app");
public void updateLvl(int newLvl){
sharedPref = this.getPreferences(0);
editor = sharedPref.edit();
int be4Level = sharedPref.getInt("currLevel", 1);
if (newLvl >= be4Level){
editor.putInt("currLevel", newLvl);
editor.commit();
}
}
}
class WebViewJavaScriptInterface2{
private Context context;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface2(Context context){
this.context = context;
}
@JavascriptInterface
public void openLvl(int lvl){
context.updateLvl(lvl);
}
}