I am developing the hybrid application in android. In this application I am trying to get the image (either from camera or gallery) as user profile picture. Here is the code that i use to get the image.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webview);
try {
WebSettings webSettings = webView.getSettings();
webSettings.setDatabaseEnabled(true);
webSettings.setDatabasePath("/data/data/"
+ getApplicationContext().getPackageName() + "/databases");
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setRenderPriority(RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setSupportZoom(false);
webSettings.setBuiltInZoomControls(false);
webSettings.setDisplayZoomControls(false);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(false);
webView.addJavascriptInterface(_jsInterface, "JSInterface");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url,
String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
private void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType) {
mUploadMessage = uploadMsg;
try {
File imageStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"AndroidImageFolder");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator
+ "CAPTURE_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i,
"Pick your avatar");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
new Parcelable[] { captureIntent });
startActivityForResult(chooserIntent,
REQUEST_CODE_FILE_CHOOSER);
} catch (Exception e) {
}
}
});
if (savedInstanceState == null) {
webView.loadUrl("file:///android_asset/index.html");
}
} catch (Exception ex) {
Log.d(TAG, ex.getCause().toString());
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_CANCELED) {
//Intent returnIntent = new Intent();
//setResult(RESULT_CANCELED, returnIntent);
} else if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_FILE_CHOOSER:
if (null == mUploadMessage)
return;
Uri result = (data == null || resultCode != RESULT_OK) ? mCapturedImageURI
: data.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
if (result != null) {
String imagePath = "";
String[] imgData = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor imgCursor = managedQuery(result, imgData, null,
null, null);
if (imgCursor != null) {
int index = imgCursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
imgCursor.moveToFirst();
imagePath = imgCursor.getString(index);
} else {
imagePath = result.getPath();
}
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
bitmap = ExifUtil.rotateBitmap(imagePath, bitmap);
// Here goes the bitmap to base64 conversion
try {
handler.post(new Runnable() {
public void run() {
webView.loadUrl("javascript:myJSFunction()"); // Here I return the base64 code (after bitmap conversion)
}
});
} catch (Exception Ex) {
}
}
break;
}
}
} catch (Exception ex) {
}
}
It successfully open the 'FileChooser' window with Camera and Gallery option. If I choose the image then the application works perfectly. The problem is, when i coming back to app without choosing any file (via back press or click the screen on app) then the application is stuck (Not able to click any of the link in webview).
For test purpose (Whether webview Activity is in active state) i tried to call the JS function in RESULT_CANCELED condition. Here is my test code
if(resultCode == Activity.RESULT_CANCELED){
try {
handler.post(new Runnable() {
public void run() {
webView.loadUrl("javascript:myJSFunction()");
}
});
} catch (Exception Ex) {
}
}
else if(resultCode == Activity.RESULT_OK){
..... // Rest of the code
}
This function is also not called. (but function is called when the resultCode is RESULT_OK)
Test Device OS version: Android JB 4.3
I stuck in this situation. Can you guys please help me to handle the RESULT_CANCELED situation and mark this problem solved. Thanks in advance.
You still need to call mUploadMessage.onReceiveValue when you get RESULT_CANCELLED.
I think you can pass null in this case.
Related
I need to get a link address from a webpage that is generated by javascript clicking on a button.
I click on the link in this way
webView.loadUrl("javascript:(function(){" +
"var All = document.getElementsByTagName('img');\n" +
"for (var i = 0; i < All.length; i++) {\n" +
"if (All[i].getAttribute('title') == 'Download') {\n" +
"var imgButton=All[i];\n" +
"e=document.createEvent('HTMLEvents');\n" +
"e.initEvent('click',true,true);\n" +
"imgButton.dispatchEvent(e);\n" +
"}\n" +
"}})()");
the problem is that after running this code, the event OnPageFinished is never called. I had try with OnProgressChanged using WebChromeClient but I had the same result.
I need to obtain the html code of the webpage after that the javascript is runned Any idea about how can I do it?
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressDialog = new ProgressDialog(Activity.this);
progressDialog.setMessage("Loading...Please wait");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
view.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! "+description , Toast.LENGTH_SHORT).show();
super.onReceivedError(view, errorCode, description,failingUrl);
}
});
Here is the method
#SuppressWarnings("unused")
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
#Keep
#JavascriptInterface
public void showHTML(String html) {
try {
Log.d("html",html);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
I'm loading data from website to a webview in my application.And i need to make the video plays inside the webview.my problem is when i don't use setJavaScriptAsEnable the images and the video loads just fine but i can't play the video inside the webview it gives me the following error
An error occurred. try watching this video on youtube or enabe JavaScript.
however when i use setJavaScriptAsEnable(true) all the images and videos inside the webview disappears like the following image.
here's my code for the webview
void setupWebView(final WebView webView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
} else {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// add padding to the html page
webView.loadUrl("javascript:(function(){ document.body.style.paddingBottom = '30px'})();");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request) {
if (request.contains("http")) {// TODO: 14/08/2017 use regs
Log.d("url", request);
new CheckIfImageAsyncTask().execute(request);
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains("http")) {
new CheckIfImageAsyncTask().execute(url);
return true;
}
return false;
}
});
// settings
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
String data = "<div>" + post.getContent() + " </div>";
webView.loadDataWithBaseURL("file:///android_asset/", getHtmlData(data), "text/html", "utf-8", null);
}
private class CheckIfImageAsyncTask extends AsyncTask<String, Void, Boolean> {
private String url;
#Override
protected Boolean doInBackground(String... strings) {
url = strings[0];
URLConnection connection = null;
boolean isImage = false;
try {
connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
isImage = contentType.startsWith("image/");
} catch (IOException e) {
e.printStackTrace();
}
return isImage;
}
#Override
protected void onPostExecute(Boolean isImage) {
try {
if (isImage) {
Intent intent = new Intent(PostDetailsActivity.this, FullScreenImageActivity.class);
intent.putExtra("coverImage", url);
startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
FirebaseCrash.report(new Exception(e.getMessage()));
}
}
}
i searched a lot and i can't figure it out. any help will be appreciated. thanks in advance.
I am trying to pass a value from a custom javascript file I have included after loading a URL in a webview.
I have checked this reference but it doesn't work when I am loading a website apart from a local index.html file.
Here is my activity code where I have created the Javacript Interface:
public class MainActivity extends AppCompatActivity {
public static String URL = "https://www.ornativa.com";
private WebView mWebView;
private RelativeLayout mLoader;
private Toolbar mToolbar;
JSInterface JSI = new JSInterface(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createWebView();
}
#SuppressLint("SetJavaScriptEnabled")
public void createWebView(){
mWebView = (WebView)findViewById(
R.id.webView);
mToolbar = (Toolbar)findViewById(R.id.toolbar);
mToolbar.setTitle(getResources().getString(R.string.app_name)+" | "+getResources().getString(R.string.app_name_hindi));
mLoader = (RelativeLayout) findViewById(R.id.loader);
// Add javascript support to the webview
mWebView.getSettings().setJavaScriptEnabled(true);
// Enable pinch zoom controls on webview
mWebView.getSettings().setBuiltInZoomControls(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE))
{ WebView.setWebContentsDebuggingEnabled(true); }
}
// Add a WebViewClient
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Inject CSS when page is done loading
injectCSS();
injectJS();
super.onPageFinished(view, url);
mLoader.setVisibility(View.GONE);
}
});
mWebView.addJavascriptInterface(JSI, "Android");
// Load a webpage
mWebView.loadUrl(URL);
}
public void injectCSS(){
try {
InputStream inputStream = getAssets().open("styles.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
mWebView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
private void injectJS() {
try {
InputStream inputStream = getAssets().open("script.js");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
mWebView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle(R.string.app_name);
builder.setMessage("Do you really want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//if user pressed "yes", then he is allowed to exit from application
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public class JSInterface {
private Context mContext;
public JSInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String message) {
Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
}
}
And this is my script.js file:
document.getElementById("aadhaarNo").type= 'tel';
var myElem = document.getElementById('actionMessages');
Android.showToast("Hello World!");
if (myElem === null) {
console.log('does not exist');
}
else{
if (myElem.classList.contains('success')){
console.log('success');
}
}
I am trying to call the function from the script file to send the value to the Toast but the Toast doesn't appear.
Change "Context" to "Activity" in class JSInterface. Check the below edited code..
public class JSInterface {
private Activity mContext;
public JSInterface(Activity c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String message) {
Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
}
I have a Webpage loading into my WebView. This webpage loads a login page for the website. As the user enters his credentials he gets redirected to a certain page. I want to stop the loading of the webpage after user enters his credentials and get redirected to another activity instead of the default redirected page.
My idea of doing this is to catch the redirected url and compare it with the url created by me, if both match it should stop loading the default webpage and load another activity. However, Iam able to catch the redirected Urls and show them in a AlertDialog, but cannot stop the loading of the default web page.
Can anyone help me on this?
This is what I have tried:-
myWebView.loadUrl(url);
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
String absoluteUrl = view.getUrl();
absoluteUrl = Uri.decode(absoluteUrl);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"Authorize/index"+myId;
//int redirectedCount = redirectedUrl.length();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(absoluteUrl);
alert.show();
if(absoluteUrl!=null && absoluteUrl.contains(redirectedUrl))
{
view.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
HttpClient httpClient = new DefaultHttpClient();
URL myUrl;
URLConnection connection;
try
{
myUrl = new URL(url);
connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
int size = connection.getContentLength();
}
catch (Exception e) {}
String htmlContent = "";
HttpPost httpGet = new HttpPost(url);
HttpResponse response;
HttpContext httpContext = new BasicHttpContext();
try
{
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
}
catch (Exception e) {}
return true;
}
EDIT:- Suggested by #SimplePlan
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
}
private void showAlert2(String Url)
{
// TODO Auto-generated method stub
Url = Uri.decode(Url);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"/AuthorizeDevice/index"+deviceId;
//int redirectedCount = redirectedUrl.length();
if(Url!=null && Url.contains("redirect_uri"+redirectedUrl+"?{StandardTokens}"))
{
myWebView.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(Url);
alert.show();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
showAlert2(url);
return true;
}
Try to implement like:
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
showAlert2(url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
HttpClient httpClient = new DefaultHttpClient();
URL myUrl;
URLConnection connection;
try
{
myUrl = new URL(url);
connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
int size = connection.getContentLength();
}
catch (Exception e) {}
String htmlContent = "";
HttpPost httpGet = new HttpPost(url);
HttpResponse response;
HttpContext httpContext = new BasicHttpContext();
try
{
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
}
catch (Exception e) {}
return true;
}
And showAlert2(url) method:
public void showAlert2(String Url) {
//String absoluteUrl = view.getUrl();
Url = Uri.decode(Url);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"Authorize/index"+myId;
//int redirectedCount = redirectedUrl.length();
if(Url!=null && Url.contains(redirectedUrl))
{
myWebView.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(Url);
alert.show();
}
}
Try as per my answer and give me feedback on this
could someone please help me. I'm having difficulty with LoadUrl and javascript.
The code below seems to work sorta ok (killing the app then trying again makes it work) on my old HTC running 2.3 however, my Xperia Z which runs the latest Android gets stuck on "Attempting to get Comments".
The section of code it is sticking on is InjectJavaScript() wherein this fails to LoadUrl (I know this as onPageFinished is never called). The strange thing is statistics part of the code works fine and its identical.
Sorry its pretty messy code...
#SuppressLint("SetJavaScriptEnabled")
public class MyIceland extends SherlockActivity {
private static class FetchMyIceland extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
setDialog("Checking Farera for WoW Data....",2);
switch(FETCHFROMMYICELAND){
case 0: //contact Farera for information.
Log.i("IcePlan","Farera Check/Empathica Front Page Retrieval...");
MyIceland.url = MainActivity.BASE_URL+"android_get.php?action=myiceland&store="+MainActivity.STORE;
try {
String Result = HTTPGET();
if(Result.startsWith("no")){ //content for today?
setDialog("No WoW Data Available for Today\nAbout to contact Empathica.com....",2);
activity.runOnUiThread(new Runnable(){#Override public void run() {MyIceland.FetchFromEmpathica("http://www.iceland.empathica.com/LogonIceland.aspx");;}}); }
else{FETCHFROMMYICELAND = 100;} //we do have content...
} catch (IOException e1) {Log.i("IcePlan",e1.toString());} catch (Exception e1) {Log.i("IcePlan",e1.toString());
} //we have data for today, so download and sort it.
break;
case 1: //get comments
setDialog("About to Contact Empathica.com for Comments....",2);
try {Thread.sleep(1000);} catch (InterruptedException e) {Log.i("IcePlan",e.toString());}
activity.runOnUiThread(new Runnable(){#Override public void run() {MyIceland.FetchFromEmpathica("http://v2.empathica.com/Reporting1/ClientReporting/LiveDataReporting.aspx?RID=1&PID=Comments&TID=1a");}});
break;
case 2: //POST data
setDialog("Posting all data to Farera.com \n So we don't have to do this again today....",2);
List<NameValuePair> params = new ArrayList<NameValuePair>();
try {params.add(new BasicNameValuePair("frontpage", URLEncoder.encode(FRONTPAGE, "utf-8")));} catch (UnsupportedEncodingException e) {Log.e("IcePlan",e.toString());}
try {params.add(new BasicNameValuePair("comments", URLEncoder.encode(COMMENTS, "utf-8")));} catch (UnsupportedEncodingException e) {Log.e("IcePlan",e.toString());}
MyIceland.url = MainActivity.BASE_URL+"android_get.php?action=store_myiceland&store="+MainActivity.STORE;
String POST = HTTPPOST(params);
if(POST != null){FETCHFROMMYICELAND = 100; }
break;
}
return null;
}
#Override
protected void onPreExecute(){super.onPreExecute();}
#Override
protected void onPostExecute(Void arg0){
if(FETCHFROMMYICELAND == 100) new MyIceland.DisplayMyIceland().execute();
}
}
//------------------------------------------------------
//-----------------------------------------------------
//-----------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_iceland);
ctx = getApplicationContext();
activity = this;
//webView2 = (WebView) findViewById(R.id.myIwebview2_widget);
/********************************************************/
/****************** ABS ********************************/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().show();
// This is a workaround for http://b.android.com/15340 from
// http://stackoverflow.com/a/5852198/132047
BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
R.drawable.bg_striped);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setBackgroundDrawable(bg);
BitmapDrawable bgSplit = (BitmapDrawable) getResources().getDrawable(
R.drawable.bg_striped);
bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
/************************************************************/
try {
ov_e = (TextView) findViewById(R.id.overall_exp_tx);
ov_r= (TextView) findViewById(R.id.overall_rank_tx);
s_e= (TextView) findViewById(R.id.storeexp_tx);
st_e= (TextView) findViewById(R.id.staffexp_tx);
t_e= (TextView) findViewById(R.id.tillexp_tx);
res= (TextView) findViewById(R.id.responses_tx);
res_r= (TextView) findViewById(R.id.resp_rank_tx);
MyIceland.list = (ListView) findViewById(R.id.wow_lv); // set list
MyIceland.adapter = new SeparatedListAdapter(ctx, false); // initialise adapter
//authenticate
CookieSyncManager.createInstance(this);
SetUp(); //Set up webView
setDialog("Loading MyIceland data...\n Please be Patient...",0);
new FetchMyIceland().execute(); //get data
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("IcePlan",e.toString());
}
}
private static String HTTPPOST(List<NameValuePair> params){
String Resp = null;
try {
HttpClient client = new DefaultHttpClient();
String postURL = MyIceland.url;
HttpPost post = new HttpPost(postURL);
//List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("user", "kris"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Resp = "not null";
}
} catch (Exception e) {
Log.e("IcePlan HTTPPOST",e.toString());
}
return Resp;
}
private static String HTTPGET() throws Exception, IOException{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
Log.i("IcePlan",str.toString());
return str.toString();
}
private void SetUp(){
webView = (WebView) findViewById(R.id.myIwebview_widget); //load custom webview
webView.clearView(); //clear view of browser
webView.clearFormData(); //clear form data
webView.setNetworkAvailable(MainActivity.isOnline(ctx)); //set network state
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setPluginsEnabled(false); //no flash
webView.getSettings().setJavaScriptEnabled(true); // enable javascript
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webView.getSettings().setSavePassword(false); //don't show password dialog
webView.setVerticalScrollBarEnabled(false); //no scrolling!
webView.setHorizontalScrollBarEnabled(false); //no scrolling!
webView.getSettings().setLoadsImagesAutomatically(false); // NO Images
webView.getSettings().setSaveFormData(false); //Don't save form data
//webView.setVisibility(View.VISIBLE);
return;
}
private static void FetchFromEmpathica(String EmpathURL){
/*****************************************************
* setWebViewClient to load pages
*****************************************************
*****************************************************
*/
webView.loadUrl(EmpathURL);
MyIceland.page = 0;
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Log.i("IcePlan",url);
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("IcePlan","Starting...");
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.i("IcePlan","Loaded...");
switch(FETCHFROMMYICELAND){
case 0:
if(MyIceland.page == 0){
MyIceland.page=1;
try {Thread.sleep(500);}catch (InterruptedException e) {Log.e("IcePlan",e.toString());}
view.loadUrl("javascript: {" +
"document.forms[0].elements['userNameBox'].value = 'xxx.xxxxx';" +
"setTimeout(function(){document.forms[0].elements['passwordBox'].value = 'xxxxxxx';},300);" +
"setTimeout(function(){document.forms[0].elements['loginButton'].click();},300); };");
}else if(MyIceland.page == 1){
MyIceland.page=2;
try {Thread.sleep(1000);}catch (InterruptedException e) {Log.e("IcePlan",e.toString());}
String oAuthUrl=("v2.empathica.com");
if(url.indexOf(oAuthUrl) > -1)
{
Log.i("Contains","Auth URL");
InjectJavaScript(view);
}else{view.loadUrl("javascript:{};");}
}else if (MyIceland.page ==2){
if(MyIceland.FRONTPAGE == null){
Log.i("IcePlan","Inject");
InjectJavaScript(view);
}else{MyIceland.page=3;}
}
break;
case 1:
if(MyIceland.COMMENTS == null){
Log.i("IcePlan","Inject Comments");
InjectJavaScript(view);
}else{MyIceland.page=100;} //else end
break;
}
super.onPageFinished(view, url);
}
});
return;
}
}
private static void setDialog(final String msg, final int dothis){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
switch(dothis){
case 0: //set up and show
if (dlg == null) {
dlg = new ProgressDialog(activity);
dlg.setTitle("Loading...");
dlg.setMessage(msg);
dlg.setCancelable(activity.isFinishing());
dlg.show();
}
break;
case 1: //remove and reset to null
if (dlg.isShowing() || dlg!=null) {
dlg.hide();
dlg = null;
}
break;
case 2:
if (dlg.isShowing() || dlg!=null) {
dlg.setMessage(msg);
}
}
}});
return;
}
/*********************************************************
* HACK - Inject Javascript to get the HTML we want!
*********************************************************/
private static void InjectJavaScript(WebView view){
switch(FETCHFROMMYICELAND){
case 0: //get front page
setDialog("Attempting to get Statistics...",2);
view.loadUrl("javascript:{" +
"var element = document.getElementById('ReportDivFPRank');"+
"if (typeof(element) != 'undefined' && element != null)"+
"{" +
"var e=document.getElementById(\"ReportDivFPCR\");"+
"var content=e.innerHTML;"+
"window.HTMLOUT.processHTML(content);"+// exists.
"}" +
"};");
break;
case 1: //get comments
setDialog("Attempting to get Comments....",2);
view.loadUrl("javascript:{" +
"var element = document.getElementById('AddNPSDetails');"+
"if (typeof(element) != 'undefined' && element != null)"+
"{" +
"var e=document.getElementById(\"_ctl1_ReportDiv\");"+
"var content=e.innerHTML;"+
"window.HTMLOUT.processHTML(content);"+// exists.
"}" +
"};");
break;
}
return;
}
/*********************************************************
* Class injected into Empathica website to get HTML
* Continues onto our controlling AsyncTask
* #author Vince
*
********************************************************/
public static class MyJavaScriptInterface
{
public void processHTML(final String html)
{
setDialog("Caught RAW data....",2);
if(html != ""){
//MyIceland.webView2.loadDataWithBaseURL("notreal/", html, "text/htm", "utf-8",null);
if(FETCHFROMMYICELAND == 0){ setDialog("Retrieved Area Statistics....",2); MyIceland.FRONTPAGE = html;}
else if(FETCHFROMMYICELAND == 1){ setDialog("Retrieved Area Comments....",2); MyIceland.COMMENTS = html;}
FETCHFROMMYICELAND++;
new MyIceland.FetchMyIceland().execute();
}
return;
}
}
}
I see that FetchFromEmpathica is going to be called again when you load the second page, and you set again a new WebViewClient() to the webview, put it on the setup() method so it is going to be called once.
Make sure that your Xperia is 4.1.2, nonetheless look what is mentioned on
Reference: JavascriptInterface methods in WebViews must now be annotated
Beginning in Android 4.2, you will now have to explicitly annotate public methods with #JavascriptInterface in order to make them accessible from hosted JavaScript. Note that this also only takes effect only if you have set your app's minSdkVersion or targetSdkVersion to 17 or higher.
Add it and import android.webkit.JavascriptInterface
So the code will be up-to-date to last versions.
#JavascriptInterface
public void processHTML(final String html)
{
//code
}