Error in Webview app - android

I am very new to Java and Android programming. Just want a simple browser that enables users to visit my forum. I got this error in my java code:
>> Code: Webview webview; << Simple object code at the top of app. Causes: Syntax error on token "WebView", import expected.
Here's the full .java file code:
package com.droidisland.app;
WebView webview;
import android.app.Activity;
public class DroidIslandActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://droidisland.net");
}
}

You are declaring a WebView variable above your import statements and outside of the class. Move that declaration after the class declaration line, like this
public class DroidIslandActivity extends Activity {
WebView webview;

In your activity you can have this code:
/*
* entry point of the application starting the index.html of PhoneGap
* */
package com.capgemini.gm.myapp;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.util.Log;
import com.google.analytics.tracking.android.EasyTracker;
public class MyAppMainActivitiy extends DroidGap
{
String curPhoneNumber;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/app/index.html",15000);
}
#Override
public void onStart() {
super.onStart();
this.appView.addJavascriptInterface(new JsInterface(), "android");
Log.d("App start activity", "interface added");
curPhoneNumber = "test";
// The rest of your onStart() code.
EasyTracker.getInstance().activityStart(this); // Add this method.
}
#Override
public void onDestroy()
{
super.onDestroy();
com.google.analytics.tracking.android.EasyTracker.getInstance().activityStop(this);
}
public class JsInterface{
public String getPhoneNumber()
{
return curPhoneNumber;
}
}
}
and in your index.html you can have this script:
<script type="text/javascript">
alert(android.getPhoneNumber());
</script>

Related

Webview hide CSS elements

I've been trying to alter my Webview app to not show the header of the source url that it loads. I've gone trough all the methods provided in Stack Overflow's history and havent't got any of them working - so i'm doing something right, or those aren't working anymore?
My goal is to find a way to affect the CSS of the page loaded to the webview app (hide the header and footer for example). Most of the methods provided here earlier based on Javascript, which is not familiar with me. I'm open for any help, since it is my first project that i'm building, and my knowledge at this point is not too good.
Here's my MainActivity.java at the moment:
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.setWebViewClient(new WebViewClient());
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
WebView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};", null);
} else {
WebView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('random-postaus')[0].style.display='none';}catch(e){}"
+ "};");
}
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}
Okay finally found a way to hide the CSS elements. Added the whole code below and the key was to use the onPageFinished method. While it is not perfect, and only activates after the whole page is loaded, it's still a valid method to hide elements in my case.
package com.U247;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView WebView;
/* dawdaw */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = (WebView)findViewById(R.id.U247);
WebView.getSettings().setJavaScriptEnabled(true);
/* HIDE UNWANTED CSS ELEMENTS */
WebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// hide element by class name
WebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('class-name-here')[0].style.display='none'; })()");
// hide element by id
WebView.loadUrl("javascript:(function() { " +
"document.getElementById('header').style.display='none';})()");
}
});
WebView.loadUrl("https://thewebsite.com");
}
#Override
public void onBackPressed() {
if (WebView.canGoBack()){
WebView.goBack();
} else {
super.onBackPressed();
}
}
}

Android. WebView reset on rotate

I'm making my own android app some people using my app says the app resets on rotate. But I cannot figure out whats wrong? I'm pretty new to app development thanks for the help!
App Mainactivity.java
package com.danielchr.hukeplan;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView wb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wb = (WebView) findViewById(R.id.webView);
WebSettings webSettings = wb.getSettings();
webSettings.setJavaScriptEnabled(true);
wb.loadUrl("https://www.hukeplan.com/");
wb.setWebViewClient(new WebViewClient());
if (savedInstanceState != null) {
wb.restoreState(savedInstanceState);
} else {
wb.loadUrl("https://hukeplan.com");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
wb.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
}
#Override
public void onBackPressed() {
if (wb.canGoBack()) {
wb.goBack();
} else {
super.onBackPressed();
}
}
}
I don't know how to fix the rotate problem.
if you want to show the WebView in only portrait mode than you may write this in your
android:screenOrientation="portrait"
or you may write below in your tag in your AndroidManifest
android:configChanges="keyboardHidden|orientation|screenSize"
This will prevent activity from loading again on orientation changes
or you may also override this method in your activity to handle orientation changes.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

On Button Click Get contents from a WebView textarea Android

I've searched on google and stackoverflow but cannot find any solutions relevant to Android API 17 and above.
I like to retrieve data from a webview on Button Click.
I like to achieve something similar to what ios has:
myText.stringByEvaluatingJavaScriptFromString
("document.getElementById('chapter-description').value")
my source code is:
package com.xyz.webviewtest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity4 extends AppCompatActivity {
TextView textView;
#SuppressLint("JavascriptInterface")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
// new MyJavaScriptInterface(this).showHTML("HtmlViewer");
webview.loadUrl("http://www.xsoftech.com");
}
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
public void showHTML(String html) {
new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
.setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
}
}
}
http://developer.android.com/ states that the constructor is deprecated
This constructor was deprecated in API level 17. Private browsing is
no longer supported directly via WebView and will be removed in a
future release. Prefer using WebSettings, WebViewDatabase,
CookieManager and WebStorage for fine-grained control of privacy data.
Webview have textarea so i can write something after writing i want able to get data on button click. Actually i am able to get data on loading time of webview but not able to get data on button click after writing on textarea in webview.
I found a possible solution, but I am not able to get any data on button click.
The solution is:
package example.xsoftech.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class Main2 extends Activity {
WebView webview1;
public static String data;
Button button;
String sUrl = "http://www.facebook.com/";
// String sUrl = "http://www.xsoftech.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
webview1 = (WebView)findViewById(R.id.myWebview);
webview1.getSettings().setJavaScriptEnabled(true);
webview1.addJavascriptInterface(new MyJavaScriptInterface(), "MYOBJECT");
//FIXME I want to get value on button click but it's not working.So plz give me solution for work it?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Main2.this, "click is done: "+data, Toast.LENGTH_SHORT).show();
data= "";
webview1.loadUrl(sUrl);
}
});
webview1.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("lifecyle", "shouldOverrideUrlLoading");
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("lifecyle", "onpagefinished");
StringBuilder sb = new StringBuilder();
sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
sb.append("var objPWD, objAccount;var str = '';");
sb.append("var inputs = document.getElementsByTagName('input');");
sb.append("for (var i = 0; i < inputs.length; i++) {");
sb.append("if (inputs[i].type.toLowerCase() === 'password') {objPWD = inputs[i];}");
sb.append("else if (inputs[i].name.toLowerCase() === 'email') {objAccount = inputs[i];}");
sb.append("}");
sb.append("if (objAccount != null) {str += objAccount.value;}");
sb.append("if (objPWD != null) { str += ' , ' + objPWD.value;}");
sb.append("window.MYOBJECT.processHTML(str);");
sb.append("return true;");
sb.append("};");
view.loadUrl("javascript:" + sb.toString());
}
});
webview1.loadUrl(sUrl);
}
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
data = html;
AlertDialog.Builder builder = new AlertDialog.Builder(Main2.this);
builder.setTitle("AlertDialog from app")
.setMessage(html)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setCancelable(false).show();
}
}
}
any help is appreciated.
I am really happy to giving answer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
final WebView browser = (WebView)findViewById(R.id.myWebview);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// This call inject JavaScript into the page which just finished loading.
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('textarea')[0].innerHTML);");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementById('chapter-description').value);");
}
});
/* load a web page */
browser.loadUrl(sUrl);
}
Enable javascript
Add your own javascript
Register your own webviewClient, overriding the onPageFinished to insert a bit of javascript
In the javascript, acquire the element.innerText of the tag, and pass it to your javascript interface.

SuperNotCalledException running unit test

I am trying to run this Android unit test, following this tutorial ::
http://developer.android.com/resources/tutorials/testing/helloandroid_test.html
and in doing so get a SuperNotCalledException
Here's the test class code ::
package com.example.helloandroid2.test;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;
import com.example.helloandroid2.HelloAndroid2Activity;
public class HelloAndroid2Test extends ActivityInstrumentationTestCase2<HelloAndroid2Activity>
{
private HelloAndroid2Activity mActivity;
private TextView mView;
private String resourceString;
public HelloAndroid2Test()
{
super("com.example.helloandroid2", HelloAndroid2Activity.class);
}
#Override
protected void setUp() throws Exception
{
super.setUp();
mActivity = this.getActivity();
mView = (TextView) mActivity.findViewById(com.example.helloandroid2.R.id.textview);
resourceString = mActivity.getString(com.example.helloandroid2.R.string.hello);
}
public void testPreconditions()
{
assertNotNull(mView);
}
public void testText()
{
assertEquals(resourceString,(String)mView.getText());
}
}
The class I'm actually testing ::
package com.example.helloandroid2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
}
}
I've set the project API levels at 2_3_1 and am using an avd set at the same.
Am running Eclipse with ADT on Windows Vista.
All wisdom greatfully recieved. Thanks in advance.
Chris
Your onCreate() method in HelloAndroid2Activity needs to call super.onCreate(savedInstanceState);
public class HelloAndroid2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Read elements in HTML loaded form webview Android

I need to read elements from an HTML file. I loaded them from webview but I haven't found the best way to read.
Code: content_html
package com.android.webview;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ViewLink extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
/*
read elements in content_html
*/
}
});
browser.loadUrl("http://vnexpress.net/gl/rss/");
}
final Context myApp = this;
Builder builder;
String content_html;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
builder = new AlertDialog.Builder(myApp);
builder.setTitle("HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
content_html = html;
Log.i("html", html+" ");
}
}
Try this one that work for me
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
System.out.println("Html...."+html);
}
}
In Activity
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setPluginsEnabled(true);
browser.getSettings().setSupportZoom(true);
browser.getSettings().setBuiltInZoomControls(true);
browser.setBackgroundColor(Color.TRANSPARENT);
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
browser.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
browser.loadUrl(link);

Categories

Resources