mono for android get html source code - android

I want to get html source code in c# (mono for android)
I add webview in my project. webview name is web.
my code:
WebView webView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main); webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetSupportZoom(true);
webView.Settings.BuiltInZoomControls = true;
webView.Settings.LoadWithOverviewMode = true; //Load 100% zoomed out
webView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
webView.ScrollbarFadingEnabled = true;
webView.VerticalScrollBarEnabled = true;
webView.HorizontalScrollBarEnabled = true;
webView.SetWebViewClient(new AwesomeWebClient());
webView.SetWebChromeClient(new AwesomeWebChromeClient(this));
webView.LoadUrl(#"http://www.google.com");
}
private class AwesomeWebClient : WebViewClient { }
private class AwesomeWebChromeClient : WebChromeClient
{
private Activity mParentActivity;
private string mTitle;
private string username;
private string password;
private string oldurl="";
public AwesomeWebChromeClient(Activity parentActivity)
{
mParentActivity = parentActivity;
mTitle = parentActivity.Title;
}
public override void OnProgressChanged(WebView view, int newProgress)
{
mParentActivity.Title = string.Format("Loading {0}%", newProgress);
mParentActivity.SetProgress(newProgress * 100);
if (newProgress==100) mParentActivity.Title=mTitle;
}
}
I open www.google.com in webview component and I want to see html source code

I don't believe that there is a way to obtain the HTML from the WebView.
Instead, you should grab the HTML yourself with a WebRequest, e.g. this handy StackOverflow answer.

Related

WebViewClient return data to Activity onPageFinished

I need to collect browser cookies from a WebView and return them to another Activity. Collecting the cookies works already but happens within a class that extends WebViewClient, and I don't know how to return the data from there.
There are 2 Activities; MainActivity and LoginActivity, respectively. MainActivity has a single button that creates an Intent and starts LoginActivity, which has a single WebView. OnCreate(), the WebView is directed to the login page of a website. When the user successfully logs into this site, it stores data in the browser cookies - data that I need for an API call later. How can I return this data to MainActivity?
The WebView has a custom WebViewClient with an overridden OnPageFinished() method, which if the URL is the one expected, will collect the browser cookies, as shown below.
class TempWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
// If page URL is the Home page (ie., you logged in successfully), collect cookies.
if (url.equals("https://slate.sheridancollege.ca/d2l/m/home")) {
String cookies = CookieManager.getInstance().getCookie(url);
String[] cookies2 = cookies.split(";");
String key1 = "";
String key2 = "";
// Find Keys placed in browser cookies.
for (String c : cookies2) {
String[] c2 = c.split("=");
if (c2[0].equals(" phrase1")) {
key1 = c2[1];
}
if (c2[0].equals(" phrase2")) {
key = c2[1];
}
}
}
}
}
LoginActivity should not call finish() (returning to MainActivity) until I've received the keys from the cookies. How can I achieve this, given what I have already? I don't know how LoginActivity can hold off returning to MainActivity until it has the data from its WebView.
public class LoginActivty extends Activity {
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
setupViews();
setContentView(webview);
}
public void setupViews() {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
CookieManager.getInstance().setAcceptCookie(true);
webview = new WebView(this);
webview.setWebViewClient(new TempWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("website");
}
}
Create reference of login activity in TempWebclient to pass the result once you get your cookie.
class TempWebViewClient extends WebViewClient {
LoginActivty mDelegate;
public TempWebViewClient(LoginActivty ref) {
this.mDelegate = ref;
}
#Override
public void onPageFinished(WebView view, String url) {
// perform task
String cookie;// get from CookieManager
mDelegate.sendCookieAndFinish(cookie);
}
}
Create function in your login activity
public class LoginActivty extends Activity {
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
}
public void setupViews() {
....
// send activity reference to webclient
webview.setWebViewClient(new TempWebViewClient(this));
}
public void sendCookieAndFinish(String cookie){
setResult(ResultCode,ResultIntent); // set result for your main activity
// store cookie to storage
finish();
}
}
From Main Activity start your LoginActivity for result

Android: unable to lauch new Activity from an inner class

Android: someone help:
I notice this kind of question has been asked before by other people but the answers have not been useful to my my case; I need to launch a new activity from an inner
class but all I get is the error bellow:
04-05 15:00:43.851: E/AndroidRuntime(3288): Caused by: java.lang.InstantiationException: com.school.School$StudentProfile
Here is my code snippet:
public class School extends Activity{
ProgressDialogue progressDialogue;
protected WebViewTask _webTask;
String path = "http://www.school.com/student/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.school);
progressDialogue = new ProgressDialogue(School.this);
_webTask = new WebViewTask();
_webTask.execute();
}
//rest of the code
/** The inner class */
public class StudentProfile {
Context context;
/** Instantiate the interface and set the context */
public StudentProfile(Context c) {
context=c;
}
/** launch student activity */
public void lauchProfile() {
School.this.startActivity(new Intent(School.this, StudentProfile.class));
//Intent intent = new Intent(School.this, StudentProfile.class);
//startActivity(intent);
}
}
void webView(){
String url = path +"student.php";
WebView wv = (WebView) findViewById(R.id.trivia_webview);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.addJavascriptInterface(new StudentProfile (this), "Student");
wv.loadUrl(url);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// open URL in the web view itself
if (url.contains(url))
return super.shouldOverrideUrlLoading(view, url);
// open URL in an external web browser
else {
return true;
}
}
});
}
// rest of the code
NOTE: there is a 'student' button on the web view that is supposed to launch the StudentProfile activity.
Your StudentProfile is not an Activity, so you can not start it that way. It needs to be a separate class, and declared in AndroidManifest.xml.

load textfile in webview android

so far i have read how to load "normal" html webpages in a webview ..
so far I pass the URL containing the path of my text file but it loads nothing.
this is my method:
#Override
public void onSelected(String url) {
ViewerFragment viewer = (ViewerFragment) getSupportFragmentManager()
.findFragmentById(R.id.view_fragment);
if (viewer == null || !viewer.isInLayout()) {
Intent showContent = new Intent(getApplicationContext(),
ViewerFragment.class);
showContent.setData(Uri.parse(url));
startActivity(showContent);
} else {
viewer.updateUrl(url);
}
}
and the viewer fragment got this:
public class ViewerFragment extends Fragment{
private WebView viewer = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
viewer = (WebView) inflater
.inflate(R.layout.details_fragment, container, false);
return viewer;
}
public void updateUrl(String newUrl) {
if (viewer != null) {
viewer.loadUrl(newUrl);
}
}
}
but keep getting this screen:
any ideas how to do this? =/ I already tried googling a bit but didnt find much info about it... actually found almost none. So any help would be appreciated.
Try reading the contents of the text file and prefixing the text with <html><body> then append </body></html> then use the WebView method loadData(...).
Example:
StringBuilder sb = new StringBuilder("<html><body>");
sb.append(readTextFile());
sb.append("</body></html>");
myWebView.loadData(sb.ToString(), "text/html", "UTF-8");
public String readTextFile(String filename) {
// Open and read the contents of <filename> into
// a single string then return it
}

WebView: how to preserve the user's zoom settings across sessions?

My app uses a WebView, and users sometimes adjust the zoom level to make the text larger. However the zoom level setting is lost when the Activity is closed and another one started.
I can't see how to get and set the zoom level programatically on WebView, can anyone suggest a way this could be done?
its me Jorge from Grupo Reforma, this is my implementation using SharedPreferences..
static final String PREFS_Zoom = "PREFS_Zoom";
private String zoomlevel;
private int Default_zoomlevel=100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
GetZoom();
mWebView.setInitialScale(Default_zoomlevel);
FrameLayout mContentView = (FrameLayout) getWindow().getDecorView().findViewById(android.R.id.content);
View zoom = mWebView.getZoomControls();
mContentView.addView(zoom, ZOOM_PARAMS);
zoom.setVisibility(View.VISIBLE);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
mWebView.loadUrl("http://www.elnorte.com");
}
private void GetZoom(){
try{
SharedPreferences settings = getSharedPreferences(PREFS_Zoom,0);
zoomlevel = settings.getString("zoom_level","");
if (zoomlevel.length() >0)
Default_zoomlevel = Integer.parseInt(zoomlevel);
else
Default_zoomlevel =100;
}catch(Exception ex){
Log.e("******ZOOM ! ", "Exception GetZoom() ::"+ex.getMessage());
}
}
private void SaveZoom(){
try{
SharedPreferences settings = getSharedPreferences(PREFS_Zoom,0);
SharedPreferences.Editor editor = settings.edit();
Default_zoomlevel = (int) (mWebView.getScale() *100);
editor.putString("zoom_level",""+ Default_zoomlevel);
editor.commit();
}catch(Exception ex){
Log.e("******ZOOM ! ", "Exception SaveZoom() ::"+ex.getMessage());
}
}
public void finish() {
SaveZoom();
super.finish();
}
I hope this help
The answer Jorge gave is spot on, except that SaveZoom ideally should not be called on finish() (which is when the activity is destroyed). A better zoom preference saving approach would be to extend the WebView's WebViewClient, and override onScaleChanged(). So continuing Jorge's onCreate method:
public void onCreate(Bundle savedInstanceState)
{
....
class MyWebViewClient extends WebViewClient
{
#Override
public void onScaleChanged(WebView wv, float oldScale, float newScale)
{
SaveZoom();
}
}
mWebView.setWebViewClient(new MyWebViewClient());
}
Perhaps you could try:
http://d.android.com/reference/android/webkit/WebSettings.html#setDefaultZoom(android.webkit.WebSettings.ZoomDensity)
&
http://d.android.com/reference/android/webkit/WebSettings.html#getDefaultZoom()
I haven't tried it myself but that looks like it might work

twitter integration on android app

I would like to integrate Twitter into my Android application so that I can post messages to Twitter.
This is how I do it
First i made a Dialog for the webview
Twitter_Dialog.java
public class Twitter_Dialog extends Dialog
{
static final int BLUE = 0xFF6D84B4;
static final float[] DIMENSIONS_DIFF_LANDSCAPE =
{ 20, 60 };
static final float[] DIMENSIONS_DIFF_PORTRAIT =
{ 40, 60 };
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
static final String DISPLAY_STRING = "touch";
private String mUrl;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
public Twitter_Dialog(Context context, String url)
{
super(context);
mUrl = url;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
int orientation = getContext().getResources().getConfiguration().orientation;
float[] dimensions = (orientation == Configuration.ORIENTATION_LANDSCAPE) ? DIMENSIONS_DIFF_LANDSCAPE : DIMENSIONS_DIFF_PORTRAIT;
addContentView(mContent, new LinearLayout.LayoutParams(display.getWidth() - ((int) (dimensions[0] * scale + 0.5f)), display.getHeight() - ((int) (dimensions[1] * scale + 0.5f))));
}
private void setUpTitle()
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Website");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(BLUE);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView()
{
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new Twitter_Dialog.DialogWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
System.out.println(" mURL = "+mUrl);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class DialogWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
Twitter_Dialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0){
mTitle.setText(title);
if(title.equals("Twitter")){
//This will close the Dialog after tweeting
Twitter_Dialog.this.dismiss();
}
}
mSpinner.dismiss();
}
}
}
//And then into your Main.java
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Twitter_Dialog(Main.this,"http://twitter.com/?status="+Uri.encode("Twitter Post")).show();
}
}
In addition to d.'s solid choices, you could:
Use ACTION_SEND Intents with createChooser(), and if the user has a Twitter application installed (Twidroid) they can use it to update their status
Use an existing Twitter Java API, like JTwitter
Everything you need to know about communicating with Twitter is here.
For sending HTTP requests from your application, check out this guide.
You can use Twitter Helper for integrating Twitter into your Android app. Its very simple.
Try with this simple client TwitterEasyClient
Just add permissions in your manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And use it in this way:
//setup
TwitterDialogFragment twitterDialog = new TwitterDialogFragment.Builder("message","url.com") //
.callbackUrl("http://www.website.com") //
.consumerKey("XXXXXXXXXXXXXXXXXXXXXX") //
.consumerSecret("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") //
.urlOAuth("oauth_verifier") //
.build();
//show the dialog
twitterDialog.show(getSupportFragmentManager(), TwitterDialogFragment.class.getSimpleName());
Always go for the latest technologies as twitter integration can be done easily using Twitter4j, also the APIs provided by twitter does change from time to time. Twiter sdk would a good option. U can find the details for it here for twitter4j.
For some people who want to use twitter4j and DialogFragment also support orientation changing check out my gist
https://gist.github.com/zeroarst/10071064adcf171277f9

Categories

Resources