calling activity from webview with #JavascriptInterface - javascript

I'm stuck on my project and requesting your help!
I'm trying to call an Activity(BarcodeScannerActivity.java) from webview in MainActivity.java with button click using javascript call. I think I messed up with parameters somewhere... I'm not sure where I've made mistake, I just copied and modified the codes from blogs and stackoverflow.
I'm having this error in my Android Studio logcat:
[INFO:CONSOLE(315)] "Uncaught Error: Error calling method on NPObject.", source: http:// .........
this is my server side html:
<input type="button" value="Scanner" id="BtnScan" class="btn_dark" onclick="callActivity();" />
<script>
function callActivity() {
Android.openBarcodeScanner();
}
</script>
this is my MainActivity.java containing webview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
//getActionBar().hide();
setContentView(R.layout.activity_main);
MainWebView = (WebView) findViewById(R.id.mainWebview);
MainWebView.setWebViewClient(new WebViewClient());
//-- add javascript listener
MainWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
MainWebView.getSettings().setJavaScriptEnabled(true);
MainWebView.loadUrl(WebViewURL);
}
..skipped for brevity..
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void openBarcodeScanner(String str) {
Intent barcodeScanIntent = new Intent(mContext, BarcodeScannerActivity.class);
mContext.startActivity(barcodeScanIntent);
}
}
and last, the BarcodeScannerActivity.java that wants to be called:
public class BarcodeScannerActivity extends Activity implements View.OnClickListener {
// private static final R = ;
// use a compound button so either checkbox or switch widgets work.
private CompoundButton autoFocus;
private CompoundButton useFlash;
private TextView statusMessage;
private TextView barcodeValue;
private static final int RC_BARCODE_CAPTURE = 9001;
private static final String TAG = "BarcodeMain";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_scanner);
statusMessage = (TextView)findViewById(R.id.status_message);
barcodeValue = (TextView)findViewById(R.id.barcode_value);
autoFocus = (CompoundButton) findViewById(R.id.auto_focus);
useFlash = (CompoundButton) findViewById(R.id.use_flash);
findViewById(R.id.read_barcode).setOnClickListener(this);
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
if (v.getId() == R.id.read_barcode) {
// launch barcode activity.
Intent intent = new Intent(this, BarcodeCaptureActivity.class);
intent.putExtra(BarcodeCaptureActivity.AutoFocus, autoFocus.isChecked());
intent.putExtra(BarcodeCaptureActivity.UseFlash, useFlash.isChecked());
startActivityForResult(intent, RC_BARCODE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_BARCODE_CAPTURE) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
statusMessage.setText(R.string.barcode_success);
barcodeValue.setText(barcode.displayValue);
Log.d(TAG, "Barcode read: " + barcode.displayValue);
} else {
statusMessage.setText(R.string.barcode_failure);
Log.d(TAG, "No barcode captured, intent data is null");
}
} else {
statusMessage.setText(String.format(getString(R.string.barcode_error),
CommonStatusCodes.getStatusCodeString(resultCode)));
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
and one last question is, would this javascript code work in my situation, too?
or do I need to modify a bit?
function callActivity(){
if(window.android){
console.info("android");
window.android.openBarcodeScanner(number.value);
}
else{
console.info("web");
document.form.submit();
}
}
}
Thank you so much in advance!

Your interface takes a string as a parameter:
#JavascriptInterface
public void openBarcodeScanner(String str) {
But your invocation doesn't pass any parameters:
Android.openBarcodeScanner();

Related

calling activity from webview with #JavascriptInterface? [duplicate]

I'm stuck on my project and requesting your help!
I'm trying to call an Activity(BarcodeScannerActivity.java) from webview in MainActivity.java with button click using javascript call. I think I messed up with parameters somewhere... I'm not sure where I've made mistake, I just copied and modified the codes from blogs and stackoverflow.
I'm having this error in my Android Studio logcat:
[INFO:CONSOLE(315)] "Uncaught Error: Error calling method on NPObject.", source: http:// .........
this is my server side html:
<input type="button" value="Scanner" id="BtnScan" class="btn_dark" onclick="callActivity();" />
<script>
function callActivity() {
Android.openBarcodeScanner();
}
</script>
this is my MainActivity.java containing webview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
//getActionBar().hide();
setContentView(R.layout.activity_main);
MainWebView = (WebView) findViewById(R.id.mainWebview);
MainWebView.setWebViewClient(new WebViewClient());
//-- add javascript listener
MainWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
MainWebView.getSettings().setJavaScriptEnabled(true);
MainWebView.loadUrl(WebViewURL);
}
..skipped for brevity..
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void openBarcodeScanner(String str) {
Intent barcodeScanIntent = new Intent(mContext, BarcodeScannerActivity.class);
mContext.startActivity(barcodeScanIntent);
}
}
and last, the BarcodeScannerActivity.java that wants to be called:
public class BarcodeScannerActivity extends Activity implements View.OnClickListener {
// private static final R = ;
// use a compound button so either checkbox or switch widgets work.
private CompoundButton autoFocus;
private CompoundButton useFlash;
private TextView statusMessage;
private TextView barcodeValue;
private static final int RC_BARCODE_CAPTURE = 9001;
private static final String TAG = "BarcodeMain";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_scanner);
statusMessage = (TextView)findViewById(R.id.status_message);
barcodeValue = (TextView)findViewById(R.id.barcode_value);
autoFocus = (CompoundButton) findViewById(R.id.auto_focus);
useFlash = (CompoundButton) findViewById(R.id.use_flash);
findViewById(R.id.read_barcode).setOnClickListener(this);
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
if (v.getId() == R.id.read_barcode) {
// launch barcode activity.
Intent intent = new Intent(this, BarcodeCaptureActivity.class);
intent.putExtra(BarcodeCaptureActivity.AutoFocus, autoFocus.isChecked());
intent.putExtra(BarcodeCaptureActivity.UseFlash, useFlash.isChecked());
startActivityForResult(intent, RC_BARCODE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_BARCODE_CAPTURE) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
statusMessage.setText(R.string.barcode_success);
barcodeValue.setText(barcode.displayValue);
Log.d(TAG, "Barcode read: " + barcode.displayValue);
} else {
statusMessage.setText(R.string.barcode_failure);
Log.d(TAG, "No barcode captured, intent data is null");
}
} else {
statusMessage.setText(String.format(getString(R.string.barcode_error),
CommonStatusCodes.getStatusCodeString(resultCode)));
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
and one last question is, would this javascript code work in my situation, too?
or do I need to modify a bit?
function callActivity(){
if(window.android){
console.info("android");
window.android.openBarcodeScanner(number.value);
}
else{
console.info("web");
document.form.submit();
}
}
}
Thank you so much in advance!
Your interface takes a string as a parameter:
#JavascriptInterface
public void openBarcodeScanner(String str) {
But your invocation doesn't pass any parameters:
Android.openBarcodeScanner();

How can a drop from Swing into JavaFX WebView be handled by HTML5 DnD Javascript

When dragging something from a Swing component (like JLabel for better control) I can't seem to find a way to have the drop handled by a HTML5 page in a JavaFX WebView. The WebView is inside a JFXPanel and is showing this page: http://html5demos.com/drag-anything
So the goal ist to have the drop handled by the Javascript of the page. The drag source in Swing has just the DataFlavor with mime-type 'text/plain'. It can't be dropped on the WebView, though drags from the WebView into a Swing drop component work fine. Of course on the WebView component the setOnDragOver and setOnDragDropped event handlers can be set, which works, but this way the drop never reaches the page in the view. Am I missing something here? Running Oracle JDK 1.8.0_51
I really think it should work like this, a workaround with capturing the events on the webview and injecting them into the html page with some custom javascript can't be the way to go.
Here's my little test code (imports simplified):
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import javafx.*;
import javax.swing.*;
import org.apache.commons.io.IOUtils;
public class JfxDndTest implements DragGestureListener {
public void initAndShowGUI() {
JFrame frame = new JFrame("WebView in JFXPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JFXPanel fxPanel = new JFXPanel();
fxPanel.setOpaque(false);
fxPanel.setPreferredSize(new Dimension(800, 600));
JLabel label = new JLabel(" TEST DRAG ");
label.setPreferredSize(new Dimension(200, 50));
label.setBorder(BorderFactory.createLineBorder(Color.RED, 3));
label.setTransferHandler(new TransferHandler() {
#Override
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
System.out.println("can import? flavors: " + Arrays.asList(transferFlavors));
for (DataFlavor df : transferFlavors) {
if (df.getMimeType().startsWith("text/plain")) {
return true;
}
}
return super.canImport(comp, transferFlavors);
}
});
DragSource dragSource = DragSource.getDefaultDragSource();
// Create a DragGestureRecognizer and
// register as the listener
dragSource.createDefaultDragGestureRecognizer(label, DnDConstants.ACTION_COPY, this);
JLabel label2 = new JLabel(" TEST DROP ");
label2.setPreferredSize(new Dimension(200, 50));
label2.setBorder(BorderFactory.createLineBorder(Color.RED, 3));
new DropTarget(label2, new DropTargetAdapter() {
#Override
public void drop(DropTargetDropEvent dtde) {
dtde.acceptDrop(DnDConstants.ACTION_COPY);
try {
InputStream is = (InputStream) dtde.getTransferable().getTransferData(new DataFlavor("text/plain"));
String s = IOUtils.toString(is);
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
dtde.dropComplete(true);
}
});
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getContentPane().add(fxPanel);
frame.getContentPane().add(label);
frame.getContentPane().add(label2);
frame.pack();
frame.setVisible(true);
// Init JFX
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
}
});
}
private void initFX(JFXPanel fxPanel) {
WebView webView = new WebView();
webView.getEngine().setOnError(new EventHandler() {
#Override
public void handle(WebErrorEvent event) {
System.out.println("ERROR: " + event.getMessage());
}
});
webView.getEngine().load("http://html5demos.com/drag-anything");
Scene scene = new Scene(webView, 800, 650);
fxPanel.setScene(scene);
}
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
dge.startDrag(null, new Transferable() {
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
System.out.println("supports? " + flavor.getMimeType());
return true;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
try {
return new DataFlavor[] { new DataFlavor("text/plain") };
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
System.out.println("getdata: " + flavor.getMimeType());
return IOUtils.toInputStream("TEST");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JfxDndTest().initAndShowGUI();
}
});
}
}

How to extract text from a WebPage

First off, yes, I have done research on this question. And yes, I have found an answer here. But the whole process still isn't working for me. All I need to do is grab text off of a webpage like Google, and create a string from the text it grabs. Here is my code with the aforementioned tutorials code in it:
public class Searching_Animation_Screen extends ActionBarActivity {
TextView loading_txt;
Animation blink;
public String pre_split;
public String[] split_string;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchinganimationscreen);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
int width = getWindowManager().getDefaultDisplay().getWidth();
loading_txt = (TextView)findViewById(R.id.loading);
text =(TextView)findViewById(R.id.textView);
Typeface pacifico_typeface = Typeface.createFromAsset(getAssets(), "fonts/pacifico.ttf");
loading_txt.setTypeface(pacifico_typeface);
loading_txt.setTextSize(width / 20);
blink = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
loading_txt.setAnimation(blink);
Begin();
}
private void Begin() {
Intent SEARCH_INTENT = getIntent();
pre_split=SEARCH_INTENT.getStringExtra("Search_Text");
split_string = pre_split.split(" ");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_searchinganimationscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String google_url ="https://www.google.com/#safe=active&q=";
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
text.setText(Html.fromHtml(result));
//throw into summarizer
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] {"www.google.com"});
}
}
}
Android studio is saying that readWebpage is never used, along with the actual DownloadWebPageTask class. Any ideas? I would like this class to run immediately on Create. Thanks!
#Ethan, sure, I hope this is what you want, just adding the readWebpage method in the onCreate method, but I modified it and removed the View object since it is not being used,
public class Searching_Animation_Screen extends ActionBarActivity {
TextView loading_txt;
Animation blink;
public String pre_split;
public String[] split_string;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchinganimationscreen);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
int width = getWindowManager().getDefaultDisplay().getWidth();
loading_txt = (TextView)findViewById(R.id.loading);
text =(TextView)findViewById(R.id.textView);
Typeface pacifico_typeface = Typeface.createFromAsset(getAssets(), "fonts/pacifico.ttf");
loading_txt.setTypeface(pacifico_typeface);
loading_txt.setTextSize(width / 20);
blink = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
loading_txt.setAnimation(blink);
Begin();
//* call webpage here,
//* note, i removed passing the view object since it is not being used
readWebpage()
}
//* (modify) by remvoving it from the code below
//* and removing the view object since it is not being used
public void readWebpage() {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] {"http://www.google.com"});
}
private void Begin() {
Intent SEARCH_INTENT = getIntent();
pre_split=SEARCH_INTENT.getStringExtra("Search_Text");
split_string = pre_split.split(" ");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_searchinganimationscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String google_url ="https://www.google.com/#safe=active&q=";
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
text.setText(Html.fromHtml(result));
//throw into summarizer
}
}
}

Android Webview irregular loading issue

Hi I would like to have an explanation regarding the following code. Here Sometimes my javascript functtion is working and sometime it is not. As a result, I don't really know where is the problem. Here my index.html file automatically loads a map position. Then I call the javascript function with current lat,lng as argument. SO, initially it loads the by default map. Then the map should be overridden by the javascript function. The problem is sometimes it happens and sometimes it doesn't. So, I would like to have an answer regarding this.
public class MapOptionsDemoModified extends Activity{
//Geocoder geocoder;
WebView mWebView;
LocationManager mlocManager=null;
LocationListener mlocListener;
private MyLocationOverlay myLocationOverlay;
protected MapView map;
private RadioButton mapButton;
private RadioButton satelliteButton;
private ToggleButton trafficToggle;
private ToggleButton labelsToggle;
private Configuration config;
EditText LOC;
Button routesbtn,settingsbtn;
public String location="State Street"
double lati,longi;
GeoPoint currentLocation;
double curlat,curlong;
InputMethodManager imm;
//String adrs;
double latitude=40.07546;
double longitude=-76.329999;
String adrs="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_options_modified);
lati=34.1161;
longi=-118.149399;
adrs="";
routesbtn=(Button)findViewById(R.id.mom_bt2);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/index.html");
//mWebView.loadUrl("http://www.google.com");
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
/* taking data from caller activity page */
// ###################Receiving data starts
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
lati=extras.getDouble("latitude");
longi = extras.getDouble("longitude");
adrs=extras.getString("adrs");
// ##### Receiving data ends
AlertDialog.Builder pdb=new AlertDialog.Builder(MapOptionsDemoModified.this);
pdb.setTitle("GPS");
pdb.setMessage(adrs+" "+Double.toString(lati)+" "+Double.toString(longi));
pdb.setPositiveButton("Ok", null);
pdb.show();
mWebView.loadUrl("javascript:getCurrentLocation("+lati+","+longi+")");
routesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
//while(j<cnt)
//{
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if(MyLocationListener.latitude>0)
{
latitude=MyLocationListener.latitude;
longitude=MyLocationListener.longitude;
//flag=1;
Geocoder gcd = new Geocoder(MapOptionsDemoModified.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(latitude,longitude, 5);
if (addresses.size() > 0)
{
adrs=addresses.get(0).getAddressLine(0)+" "+addresses.get(0).getAddressLine(1)+" "+addresses.get(0).getAddressLine(2);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//break;
finish();
Intent i = new Intent(MapOptionsDemoModified.this,RoutesPageOne.class);
i.putExtra("adrs", adrs);
i.putExtra("latitude", latitude);
i.putExtra("longitude", longitude);
startActivity(i);
}
else
{
AlertDialog.Builder pdb=new AlertDialog.Builder(MapOptionsDemoModified.this);
pdb.setTitle("GPS");
pdb.setMessage("GPS activation in progress");
pdb.setPositiveButton("Ok", null);
pdb.show();
}
//}
}
else {
AlertDialog.Builder pdb=new AlertDialog.Builder(MapOptionsDemoModified.this);
pdb.setTitle("GPS");
pdb.setMessage("GPS is not turned on..., please start gps");
pdb.setPositiveButton("Ok", null);
pdb.show();
}
}
});
LOC=(EditText)findViewById(R.id.mom_editText1);
LOC.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
location = LOC.getText().toString();
if (keyCode == KeyEvent.KEYCODE_ENTER && location.length() > 0) {
LOC.setText("");
imm.hideSoftInputFromWindow(LOC.getWindowToken(), 0);
mWebView.loadUrl("javascript:getLocation('" + location + "')");
/*AlertDialog.Builder edb=new AlertDialog.Builder(MapOptionsDemoModified.this);
edb.setTitle("gps");
edb.setMessage(location+" lat= "+lati+" long="+longi);
edb.setPositiveButton("Ok", null);
edb.show();*/
//searchBarcode(barcode);
return true;
}
return false;
}
});
//imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mWebView.setWebViewClient(new HelloWebViewClient());
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
The problem was in timing. Sometimes, the first url took more time to be loaded, as a result the 2nd url wasn't invoked. So I have included SystemClock.sleep(1000) in between loadUrl calls and it has worked like a charm.

Android: How to saveState of a WebView with an addJavascriptInterface attached?

I have an android WebView that has a JavaScript interface added with addJavajavascriptInterface().
Is it possible to save the state of the WebView (webpage state, html, css, javascript) and then restore it on onCreate? If yes, how?
The code I have so far keeps crashing:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
final WebBackForwardList list = mWebView.restoreState(savedInstanceState);
if (savedInstanceState.containsKey("currentPicture")) {
final File f = new File(savedInstanceState.getString("currentPicture"));
mWebView.restorePicture(savedInstanceState, f);
f.delete();
}
} else {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidApp");
mWebView.loadUrl(url);
}
}
public void onSaveInstanceState(Bundle outState) {
final WebBackForwardList list = mWebView.saveState(outState);
File mThumbnailDir = getDir("my-thumbnails", 0);
if (list != null) {
final File f = new File(mThumbnailDir, mWebView.hashCode() + "_pic.save");
if (mWebView.savePicture(outState, f))
outState.putString("currentPicture", f.getPath());
}
}

Categories