Webview javascript not working with javascript enabled - javascript

I'm trying to make the javascript work in android for this page:
http://test.swiss-impulse.com/scratch_card_game/index.html
But i have issues regarding the browser.
This is the parameters set for the webview:
webView1.setWebChromeClient(mClient);
webView1.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
webView1.addJavascriptInterface(new JavaScriptInterfaceForTitle(this, mPasswordStrength, webView1), "HtmlViewer");
webView1.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String cookie = CookieManager.getInstance().getCookie(url);
if (url.equals(getContentUrl() + "addcomment")) {
webView1.stopLoading();
Intent addcommentIntent = new Intent(mContext, AddCommentActivity.class);
addcommentIntent.putExtra("url", previousUrl);
startActivity(addcommentIntent);
} else {
previousUrl = url;
((BaseActivity) mContext).showLoadingDialog();
if (!urlStackList.contains(url)) {
urlStackList.add(url);
}
super.onPageStarted(view, url, favicon);
}
}
#Override
public void onPageFinished(WebView view, String url) {
((BaseActivity) mContext).hideLoadingDialog();
if (url.contains("content/shows/") || url.contains("content/tips/")) {
counter = 0;
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('" + mContext.getString(R.string.title_name) + "').innerHTML);");
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('name_en').innerHTML);");
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('name_zh').innerHTML);");
} else {
mStateBar.setShowTitle(mContext.getString(R.string.tv_drama));
}
super.onPageFinished(view, url);
}
});
webview1.setWebChromeClient(mClient);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.getSettings().setPluginState(PluginState.ON);
webView1.getSettings().setPluginsEnabled(true);
webView1.getSettings().setAppCacheMaxSize(httpCacheSize);
webView1.getSettings().setSupportZoom(false);
webView1.getSettings().setBuiltInZoomControls(false);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Am i missing some parameters to make this work on android webview ? I checked chrome browser and there it works with no problems, so i'm sure i missed something and cannot find what.
EDIT:
class MyChromeClient extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
mCustomViewCallback = callback;
mTargetView.addView(view);
mCustomView = view;
mContentView.setVisibility(View.GONE);
mTargetView.setVisibility(View.VISIBLE);
mTargetView.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
mCustomView.setVisibility(View.GONE);
mTargetView.removeView(mCustomView);
mCustomView = null;
mTargetView.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
mContentView.setVisibility(View.VISIBLE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
TvDramaActivity.this.startActivityForResult(Intent.createChooser(i, "Chooser"), 100);
}
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
}
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mClient.onHideCustomView();
}

This works for me :
In your WebView Activity class :
WebView webView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView1 = (WebView) findViewById(R.id.web);
webView1.setWebChromeClient(new WebChromeClient());
webView1.getSettings().setJavaScriptEnabled(true);
webView1.getSettings().setPluginState(PluginState.ON);
webView1.getSettings().setSupportZoom(false);
webView1.getSettings().setBuiltInZoomControls(false);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView1.loadUrl("http://test.swiss-impulse.com/scratch_card_game/index.html");
}
Your layout file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/web"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Don't forget to add <uses-permission android:name="android.permission.INTERNET"/> in manifest file.
Hope this helps.Thanks.

you can try below code
mWebView.setWebChromeClient(new WebChromeClient());
//support JavaScript
mWebView.getSettings().setJavaScriptEnabled(true);

Related

WebView not downloading pop-up file

I'm new to Android studio.
So I have been writing some code that helps my job.
When the imgView and Layout clicked the app will go into WebView
On the WebView they will fill the form, after that the web should automatically downloading the .pdf file.
When I Opened it with chrome, chrome will make a new tab/pop up with some link that triggers downloading files.
How this webView could download the pdf file too? because When I opened it on the Web View, the WebView will go back to previous activity.
public class biling extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biling);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 1);
}
}
webView = findViewById(R.id.bilingweb);
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// if want to download pdf manually create AsyncTask here
// and download file
return true;
}
return false;
}
});
webView.loadUrl("https://sse2.pajak.go.id");
webView.setDownloadListener(new DownloadListener()
{
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()){
v.requestFocus();
}
break;
}
return false;
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setDisplayZoomControls(true);
webSettings.setAllowFileAccess(true);
webSettings.setSupportMultipleWindows(true);
Toolbar toolbar = findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("e-Biling");
getSupportActionBar().setSubtitle("Bayar Pajak Online");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){webView.goBack();}
else
{super.onBackPressed();}
}
}

Having two webviews in my app one webview not unable to delete conent in webview

I have two webviews in my android app one webview deletes content based on given javascript function and other one is remaining same even I give javascript function by id. The main webview working perfectly and other one not and now i may integrating another webview if my second webview works perfectly.
here is my first webview it's working perfectly
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("url");
webView.getSettings().setDomStorageEnabled(true)
public class myWebClient extends WebViewClient
{
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() {document.getElementById('mainHeader').style.display='none';" + "document.getElementById('footerRights').style.display='none';" + "document.getElementById('navTrail').style.display='none';" + "document.getElementById('threeColumns').style.display='none';" + " })()");
}
#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);
}
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
my second webview
public class webview2 extends AppCompatActivity {
private WebView webVIEW;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
webVIEW = (WebView) findViewById(R.id.webVIEW);
webVIEW.setWebViewClient(new WebViewClient());
webVIEW.getSettings().setJavaScriptEnabled(true);
webVIEW.loadUrl("example url");
webVIEW.getSettings().setJavaScriptEnabled(true);
webVIEW.getSettings().setDomStorageEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public class webVIEW extends WebViewClient {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() { " + "var element = document.getElementById('hplogo');" + "element.parentNode.removeChild(element);" + " })()");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon ) {
super.onPageStarted(view, url, favicon);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed(){
if (webVIEW.canGoBack()) {
webVIEW.goBack();
}else {
super.onBackPressed();
}
}
}
webview2.java
its being remaining same no javascript excution now i need to integrate another webview and it also needs the same as first webview
Thanks in Advance
I have solved my question using kotlin class by this i can inject java script in one or more webviews
class webview2 : AppCompatActivity() {
private lateinit var webVIEW: WebView
#SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
webVIEW = findViewById<WebView>(R.id.webVIEW) as WebView
webVIEW.settings.javaScriptEnabled = true
webVIEW.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
injectJS()
}
}
webVIEW.loadUrl("https://example/login")
}
val progressBar = findViewById<ProgressBar>(R.id.progressBar3)
override fun onBackPressed() {
if (webVIEW.canGoBack()) {
webVIEW.goBack();
} else {
super.onBackPressed()
}
}
private fun injectJS() {
val jsContent: String?
jsContent = try {
val inputStream = assets.open("style.js")
val fileContent = inputStream.bufferedReader().use(BufferedReader::readText)
inputStream.close()
fileContent
} catch (e: Exception) {
null
}
jsContent?.let { webVIEW.loadUrl("javascript:($jsContent)()") }
}
}

webview android doesn't store session/cookies

I got an issue. When i set view.loadUrl("http://mysite"); and trying to login, app doesn't handle the session, and shows that I'm not logged in, but when I'm setting up view.loadUrl("http://google.com"); and loading my site via google search, the session is establishing correct, other site logins view.loadUrl("http://othersite") logging fine too;
Please help, I tried anything but nothing helps... Thank you.
P.S site works well in other browsers.
my xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.FrameLayout xmlns:android="http://schemas.android.com /apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gtr.rox.MainActivity"
android:background="#333333"
android:id="#+id/webview_frame">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.widget.FrameLayout>
Main activity
public class MainActivity extends AppCompatActivity {
private WebView mWebviewPop;
private WebView view;
private FrameLayout mContainer;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
view = (WebView) this.findViewById(R.id.webView);
mContainer = (FrameLayout) findViewById(R.id.webview_frame);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 4.4.2; ZTE T221 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Mobile Safari/537.36");
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setLoadWithOverviewMode(true);
view.getSettings().setUseWideViewPort(true);
view.getSettings().setDatabaseEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.getSettings().setSupportMultipleWindows(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setDomStorageEnabled(true);
view.invalidate();
view.setWebViewClient(new MyBrowser() {
});
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
view.loadUrl("http://mysite");
view.setWebChromeClient(new UriChromeClient() {
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 1);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.apply();
}
mContext=this.getApplicationContext();
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mailto:") || url.startsWith("mms:") || url.startsWith("mmsto:") || url.startsWith("market:") || url.startsWith("https://youtu")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
} else {
view.loadUrl(url);
return true;
}
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
//super.onReceivedSslError(view, handler, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
class UriChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.getSettings().setLoadWithOverviewMode(true);
mWebviewPop.getSettings().setUseWideViewPort(true);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new MyBrowser());
mWebviewPop.getSettings().setDatabaseEnabled(true);
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(true);
mWebviewPop.getSettings().setAppCacheEnabled(true);
mWebviewPop.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebviewPop.getSettings().setSupportMultipleWindows(true);
mWebviewPop.getSettings().setAllowFileAccess(true);
mWebviewPop.getSettings().setDomStorageEnabled(true);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
Solved by remove this line
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
And it works!

Return the button text from Javascript to Java using WebView

I need to read text on the button which is located on the website. I tried to parse the page using JSOUP, but JSOUP doesn't see Javascript object. That is why I decide to use WebView to read text. But it doesn't work. I need to return the button text from Javascript to Java. Is it possible?
public class MainActivity extends AppCompatActivity {
WebView mWebView;
Button mButton, mClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.web_view);
mButton = (Button) findViewById(R.id.start_URL);
mClick = (Button) findViewById(R.id.click);
}
#Override
protected void onResume() {
super.onResume();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebViewClient(new PersonalWebView());
mWebView.setWebChromeClient(new PersonalWebChrome());
mWebView.addJavascriptInterface(new JSInterface(), "JSInterface");
mWebView.loadUrl(URL);
mClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWebView.loadUrl("javascript: window.JSInterface.callFromJS('buttonText')");}
}
private class JavaScriptInterface {
#JavascriptInterface
public void callFromJS(String buttonText) {
Log.d("JScript","callFromJS "+ buttonText);
}
}
private class PersonalWebView extends 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);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
}
private class PersonalWebChrome extends WebChromeClient {
private PersonalWebChrome() {
super();
}
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
}
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d("TAG", consoleMessage.message()+" "+consoleMessage.sourceId());
return super.onConsoleMessage(consoleMessage);
}
}
I tried to change code, but it doesn't work:
mClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWebView.addJavascriptInterface(new JSInterface(), "JSInterface");
ValueCallback<String> result = new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
Log.d("TAG", value);
}
};
mWebView.evaluateJavascript("javascript: window.JSInterface.callFromJS('buttonText')",result);}}
In the Log I see:
D/TAG: Uncaught TypeError: Cannot read property 'callFromJS' of undefined
This is not the correct way of dealing with injected Java objects:
mWebView.addJavascriptInterface(new JavaScriptInterface(), "javaCallback");
mWebView.loadUrl("javascript:window.javaCallback.callFromJS('buttonText')";
Injected objects only become "visible" on the next page load after calling addJavascriptInterface. Loading javascript: URIs doesn't count as a page load.
Check out the sample from the docs:
webView.addJavascriptInterface(new JsObject(), "injectedObject");
webView.loadData("", "text/html", null);
webView.loadUrl("javascript:alert(injectedObject.toString())");
The loadData in between is what actually makes the object to be inserted. You can as well use loadUrl but it needs to be a real page (from the network, assets, about:blank, whatever), but not a javascript: URI.
The problem should be in trying to call callFromJS method before registering interface. You register the JS interface only on the button click:
mClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWebView.addJavascriptInterface(new JSInterface(), "JSInterface");
}
}
But you try to call the callFromJS immediately.
Instead of doing this, move your mWebView.evaluateJavascript("javascript: window.JSInterface.callFromJS('buttonText')",result); inside onClick()

not able to call web service from webview

I am not able to call web service or no alert is being shown:
my activity code:
mWebView = (WebView)findViewById(R.id.webViewRootAciviy);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.loadUrl("file:///android_asset/splashscreen.html");
html code:
<html>
<body>
this is a demo html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
$.ajax({
type: 'GET',
url: 'http://192.168.11.50/ar/service.svc/ProductCategories?$format=json',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
alert("success");
},
error: function (error)
{
alert("error");
}
});
</script>
</body>
</html>
Also given the Internet permission. Please help me find what i missed.
Edit:
We have our own server in our company and service is hosted on it. I am using wifi to access internet and server is also connected to the same wifi router with ethernet cable.
Update: I dont know why this happened. The problem was arised due to the type of service created. The web service was created using WCF Data service, but after creating web service again using normal WCF Service, the URL is working fine now.
apply this to your webview.
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
} else {
return false;
}
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(give your url);
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}

Categories

Resources