JavaFX WebView up call from JavaScript doesn't work - javascript

I have a JavaFX WebView and want to call the method "hello" of the class "JavaBridge" from "test.html" displayed in the webview.
Why doesn't this work? I making sure that the "bridge" object only be added to the window.object when the page has been fully rendered, so that is probably not the problem. I can't see any problem with the HTML either.
Here is the HTML code ("test.html"):
<html>
<head>
</head>
<body>
call java
</body>
</html>
And here is the Java Code:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
java.net.URI uri = java.nio.file.Paths.get("test.html").toAbsolutePath().toUri();
WebView root = new javafx.scene.web.WebView();
root.getEngine().load(uri.toString());
root.getEngine().
getLoadWorker().
stateProperty().
addListener(new ChangeListener < State > () {
#Override public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
System.out.println("READY");
JSObject jsobj = (JSObject) root.getEngine().executeScript("window");
jsobj.setMember("bridge", new JavaBridge());
}
}
});
primaryStage.setScene(new javafx.scene.Scene(root, 800, 600));
primaryStage.show();
}
}
class JavaBridge {
public void hello() {
System.out.println("hello");
}
}

When using this bridge feature on Java 10.0.2, I noticed that it was not working consistently. Javascript upcalls wasn't working all the times.
After researching, I found out this OpenJDK bug related to Java Garbage Collector, which seems to happen on regular JDK as well:
https://bugs.openjdk.java.net/browse/JDK-8170085
Indeed, according to https://docs.oracle.com/javase/9/docs/api/javafx/scene/web/WebEngine.html, it's recommended to store the bridge into a variable to avoid Java GC to collect the object.
After adding a private variable to the class, the JS to Java calls started to work all the time in my Application.

Your inner class should be inside the main class. And it should be public. Like this:
import java.net.URL;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
final URL url = getClass().getResource("test.html");
WebView root = new javafx.scene.web.WebView();
root.getEngine().load(url.toExternalForm());
root.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
#Override
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
System.out.println("READY");
JSObject jsobj = (JSObject) root.getEngine().executeScript("window");
jsobj.setMember("bridge", new JavaBridge());
}
}
});
primaryStage.setScene(new javafx.scene.Scene(root, 800, 600));
primaryStage.show();
}
public class JavaBridge {
public void hello() {
System.out.println("hello");
}
}
}

I had the same problem and the only way to fix it was storing the Bridge on a static variable.
this is an example to use the javafx FileChooser.
public class Controller implements Initializable {
#FXML private WebView webview;
#FXML private JFXButton btn_insertimg;
#FXML private AnchorPane anchorpane;
private WebEngine webEngine;
public static Bridge bridge; //it's important to be static
#Override
public void initialize(URL location, ResourceBundle resources) {
webEngine = webview.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(
(ov, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
//todo when the document is fully loaded
FileChooser fileChooser=new FileChooser();
bridge=new Bridge(webview,fileChooser);
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("myFileChooser", bridge);
System.out.println("member "+window.getMember("myFileChooser").toString());;
}//end of SUCCEEDED state
});
webEngine.load(getClass().getResource("/patient/texteditor/summernote.html").toExternalForm());
}
public class Bridge{
FileChooser fileChooser;
WebView webView;
Bridge(WebView webView,FileChooser fileChooser){
this.webView=webView;
this.fileChooser=fileChooser;
}
public void display(){
fileChooser.showOpenDialog(webView.getScene().getWindow());
}
}
}

Related

Main Activity Using onStart, onStop, onResume Not Showing the Appropriate XML/Interface

I'm following a guide on coding by Easy Tuto, currently on part 7 at the end where the recycler_note_item.xml would show up on the interface. In the video, he fixed the problem by adding the onStart, onStop, onResume commands and adding `noteAdapter.startListening' in between the lines as shown here: image In the video, it worked and showed the item however nothing showed up for me as can be seen here . I tried scouring the video trying to find what I did wrong. I'm pretty new to coding and I was using his video as a base to learn more about it. I added those lines myself but it diddn't work for me it seems. Can someone please help me? It would be greatly appreciated. Here is my code for MainActivity.Java:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageButton;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.Query;
public class MainActivity extends AppCompatActivity {
FloatingActionButton addNoteBtn;
RecyclerView recyclerView;
ImageButton menuBtn;
NoteAdapter noteAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNoteBtn = findViewById(R.id.add_note_btn);
recyclerView = findViewById(R.id.recyler_view);
menuBtn = findViewById(R.id.menu_btn);
addNoteBtn.setOnClickListener((v)-> startActivity(new Intent(MainActivity.this,NoteDetailsActivity.class)) );
menuBtn.setOnClickListener((v)->showMenu());
setupRecyclerView();
}
void showMenu(){
//TODO Display menu
}
void setupRecyclerView(){
Query query = Utility.getCollectionReferenceForNotes().orderBy("timestamp",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query,Note.class).build();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
noteAdapter = new NoteAdapter(options,this);
recyclerView.setAdapter(noteAdapter);
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.stopListening();
}
#Override
protected void onResume() {
super.onResume();
noteAdapter.notifyDataSetChanged();
}
}
I think the other relevant codes is my NoteAdapter which is this:
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import io.grpc.okhttp.internal.Util;
public class NoteAdapter extends FirestoreRecyclerAdapter<Note, NoteAdapter.NoteViewHolder>{
Context context;
public NoteAdapter(#NonNull FirestoreRecyclerOptions<Note> options, Context context) {
super(options);
this.context = context;
}
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder holder, int position, #NonNull Note note) {
holder.titleTextView.setText(note.title);
holder.contentTextView.setText(note.content);
holder.timestampTextView.setText(Utility.timestamptoString(note.timeStamp));
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_note_item,parent,true);
return new NoteViewHolder(view);
}
class NoteViewHolder extends RecyclerView.ViewHolder{
TextView titleTextView,contentTextView,timestampTextView;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.note_title_text_view);
contentTextView = itemView.findViewById(R.id.note_content_text_view);
timestampTextView = itemView.findViewById(R.id.note_timestamp_text_view);
}
}
}
Please tell me if there are any other relevant codes I can give to help give more context on my problem. Thanks for helping me out if anyone!

Only image text is showing from firebase in recyclerview fragment Image is not loading [duplicate]

This question already has an answer here:
My recycler view is not showing any firebase images
(1 answer)
Closed 2 years ago.
My images from firebase are not showing in image view but the name of an image is showing in the above text view of the recycler view. Here is my code please help.
FragmentActivity
package com.example.bbeast.HomeActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.bbeast.R;
import com.example.bbeast.Upload;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class fragmentHealthTips extends Fragment {
private RecyclerView mRecyclerView;
private DatabaseReference mDataRef;
private Uri mImageuri;
View view;
public void fragmentHealthTips() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.healthtips_fragment, container, false);
mRecyclerView =(RecyclerView)view.findViewById(R.id.healthtips_recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mDataRef = FirebaseDatabase.getInstance().getReference().child("Uploads");
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<HealthTips>()
.setQuery(mDataRef, HealthTips.class)
.build();
FirebaseRecyclerAdapter<HealthTips, hViewHolder> adapter= new FirebaseRecyclerAdapter<HealthTips, hViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final hViewHolder holder, int i, #NonNull final HealthTips healthTips) {
//directly get the values like this
String Iname = healthTips.getName();
String Uimage = healthTips.getImage();
holder.hName.setText(Iname);
Picasso.get()
.load(Uimage)
.into(holder.hImageview);
}
#NonNull
#Override
public hViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_healthtips, parent, false);
hViewHolder viewHolder = new hViewHolder(view);
return viewHolder;
}
};
mRecyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class hViewHolder extends RecyclerView.ViewHolder{
TextView hName;
ImageView hImageview;
public hViewHolder(#NonNull View itemView) {
super(itemView);
hName = itemView.findViewById(R.id.healthtips_name);
hImageview = itemView.findViewById(R.id.healthtips_imageView);
}
}
}
Xml file of items.
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/healthtips_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"/>
<ImageView
android:id="#+id/healthtips_imageView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="20dp"
android:background="#drawable/imageview_bg"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Model class, Healthtips activity.
package com.example.bbeast.HomeActivity;
import java.util.jar.Attributes;
public class HealthTips {
public String name, image;
public HealthTips(){
}
public HealthTips(String name, String image){
this.name = name;
this.image = image;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getImage(){
return image;
}
public void setImage(String image){
this.image= image;
}
}
Gradle dependencies.
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.bbeast"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
dataBinding {
enabled = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/java/Admin Activity', 'src/main/java/com.example.bbeast/ui.main/Admin Activity']
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-storage:16.0.4'
implementation 'com.firebaseui:firebase-ui-database:3.2.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.firebase:firebase-analytics:16.0.5'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.squareup.picasso:picasso:2.6.0-SNAPSHOT'
}
Please help me in getting an image in the image view. Thank you in advance.
Check
of the UImage is a valid path, normally I would do something like this..
P.S Not a RecyclerView but you get the idea
imageview1 = (ImageView) findViewById(R.id.imageview1);
_path_child_listener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot _param1, String _param2) {
GenericTypeIndicator<HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap<String, Object>>() {};
final String _childKey = _param1.getKey();
final HashMap<String, Object> _childValue = _param1.getValue(_ind);
Glide.with(getApplicationContext()).load(Uri.parse(_childValue.get("imageUrl").toString())).into(imageview1);
//imageUrl is pushed to Firebase Storage onUploadCompleted
}
#Override
public void onChildChanged(DataSnapshot _param1, String _param2) {
GenericTypeIndicator<HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap<String, Object>>() {};
final String _childKey = _param1.getKey();
final HashMap<String, Object> _childValue = _param1.getValue(_ind);
}
#Override
public void onChildMoved(DataSnapshot _param1, String _param2) {
}
#Override
public void onChildRemoved(DataSnapshot _param1) {
GenericTypeIndicator<HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap<String, Object>>() {};
final String _childKey = _param1.getKey();
final HashMap<String, Object> _childValue = _param1.getValue(_ind);
}
#Override
public void onCancelled(DatabaseError _param1) {
final int _errorCode = _param1.getCode();
final String _errorMessage = _param1.getMessage();
}
};
path.addChildEventListener(_path_child_listener);
}
private void initializeLogic() {
}

How can I display a PDF file in a WebView (JavaFX) panel using PDF.js?

I got this (https://stackoverflow.com/a/42040344/3789572) solution, which code is below, but it isn't working. When I press the button, nothing is shown.
You can change the file paths and try it for yourself.
Can you help me?
Controller code:
package sample.principal;
import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
import java.io.File;
import java.net.URL;
import java.util.Base64;
import java.util.ResourceBundle;
import org.apache.commons.io.FileUtils;
public class WebController implements Initializable {
#FXML
private WebView web;
#FXML
private Button btn;
public void initialize(URL location, ResourceBundle resources) {
WebEngine engine = web.getEngine();
String url = getClass().getResource("..\\resources\\web\\viewer.html").toExternalForm();
// connect CSS styles to customize pdf.js appearance
engine.setUserStyleSheetLocation(getClass().getResource("..\\resources\\web\\viewer.css").toExternalForm());
engine.setJavaScriptEnabled(true);
engine.load(url);
engine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
// to debug JS code by showing console.log() calls in IDE console
JSObject window = (JSObject) engine.executeScript("window");
window.setMember("java", new JSLogListener());
engine.executeScript("console.log = function(message){ java.log(message); };");
// this pdf file will be opened on application startup
if (newValue == Worker.State.SUCCEEDED) {
try {
// readFileToByteArray() comes from commons-io library
byte[] data = FileUtils.readFileToByteArray(new File("C:\\Users\\Felipe\\Documents\\" +
"Programação\\Java\\" +
"IdeaProjects\\PDFviewerStackOverFlow\\src\\sample\\principal\\teste.pdf"));
String base64 = Base64.getEncoder().encodeToString(data);
// call JS function from Java code
engine.executeScript("openFileFromBase64('" + base64 + "')");
} catch (Exception e) {
e.printStackTrace();
}
}
});
// this file will be opened on button click
btn.setOnAction(actionEvent -> {
try {
byte[] data = FileUtils.readFileToByteArray(new File("teste.pdf"));
String base64 = Base64.getEncoder().encodeToString(data);
engine.executeScript("openFileFromBase64('" + base64 + "')");
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
The Main code:
package sample.principal;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch();
}
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("PDF test app");
primaryStage.setScene(new Scene(root, 1280, 576));
primaryStage.show();
}
}
and the other one:
package sample.principal;
public class JSLogListener {
public void log(String text) {
System.out.println(text);
}
}
I would be very grateful for your help.
Thanks.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage stage) {
stage.setTitle("HTML");
stage.setWidth(500);
stage.setHeight(500);
Scene scene = new Scene(new Group());
VBox root = new VBox();
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(browser);
webEngine.loadContent("<b>asdf</b>");
root.getChildren().addAll(scrollPane);
scene.setRoot(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

React Native app first shows white screen, then goes to app

I am running React Native 0.56. When I start my app, it first shows a white screen for 1 second then goes to the app. My files are:
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new BlurViewPackage(),
new OrientationPackage(),
new ReactVideoPackage(),
new RNDeviceInfo(),
new LinearGradientPackage()
);
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
and
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "CONtv";
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = new Intent("onConfigurationChanged");
intent.putExtra("newConfig", newConfig);
this.sendBroadcast(intent);
}
}
and index.js
import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
How do I make the white screen not appear? This is happening on Android.
As a solution for the white screen add a splash screen.
Check with this https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565

Want to pass the cookies to the webview to load a webpage

I had Successful login to a website using jsoup and I obtained cookies from Jsoup cookies function in Map but I am struck at something.After successful login I Want to open a webpage of the website in the webview but the webpage redirects to the login page because cookies are not successfully passed to the webview and I don't know why. The page wants cookies of successful login to load that page
Here is the login page url.
http://111.68.99.8/StudentProfile/
and page I want to load after Successful Login
http://111.68.99.8/StudentProfile/PersonalInfo.aspx
Here is the MainActivity.java
package com.example.ebad.bu;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends ActionBarActivity {
String url = "http://111.68.99.8/StudentProfile/";
Map<String, String> logingcookies;
HashMap<String,String> hashMap;
ProgressDialog progressDialog,progressDialoge;
Button login, personal;
TextView Enrollement, password, E;
String enrol = "";
String pass = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login_button);
personal = (Button) findViewById(R.id.pers);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Enrollement = (TextView) findViewById(R.id.Enrollment);
enrol = Enrollement.getText().toString();
password = (TextView) findViewById(R.id.password);
pass = password.getText().toString();
new Title().execute();
}
});
}
private class Title extends AsyncTask<Void, Void, Void> {
String title;
String father;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Title");
progressDialog.setMessage("Loading");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Connection.Response loginForm = Jsoup.connect(url).method(Connection.Method.GET).timeout(1000).execute();
Document doc = loginForm.parse();
String viewstate = doc.select("input[name=__VIEWSTATE]").attr("value");
String stategenerator = doc.select("input[name=__VIEWSTATEGENERATOR]").attr("value");
String Eventvalidation = doc.select("input[name=__EVENTVALIDATION]").attr("value");
doc = Jsoup.connect(url)
.data("__LASTFOCUS", "")
.data("__EVENTTARGET", "")
.data("__EVENTARGUMENT", "")
.data("__VIEWSTATE", viewstate)
.data("__VIEWSTATEGENERATOR", stategenerator)
.data("__EVENTVALIDATION", Eventvalidation)
.data("ctl00$Body$ENROLLMENTTextBox$tb", enrol)
.data("ctl00$Body$ENROLLMENTTextBox$cv_vce_ClientState", "")
.data("ctl00$Body$PasswordTextBox$tb", pass)
.data("ctl00$Body$PasswordTextBox$cv_vce_ClientState", "")
.data("ctl00$Body$LoginButton", "Login")
.cookies(loginForm.cookies())
.post();
logingcookies = loginForm.cookies();
title = doc.select("div[id=ctl00_Accounts]").html();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
/*Intent showadditionmenu = new Intent(MainActivity.this,Per.class);
//showadditionmenu.putStringArrayListExtra("logingcookies", (ArrayList<String>) logingcookies);
showadditionmenu.putExtra("logingcookies", String.valueOf(logingcookies));
MainActivity.this.startActivity(showadditionmenu);*/
/* Intent i = new Intent(MainActivity.this,Per.class);
i.putExtra("hashMap",hashMap );
startActivity(i);
*/
hashMap = new HashMap<String,String>(logingcookies);
Intent i = new Intent(MainActivity.this,wee.class);
i.putExtra("hashMap",hashMap );
startActivity(i);
/* E = (TextView) findViewById(R.id.message);
E.setText(title);
progressDialog.dismiss();*/
}
}
}
I have passed the saved cookie to the activity that load the webpage in webivew.. Here is the other activity;
Wee.java
package com.example.ebad.bu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Ebad on 11/8/2015.
*/
public class wee extends Activity {
String url= "http://111.68.99.8/StudentProfile/PersonalInfo.aspx";
HashMap<String ,String> hashMap;
Map<String,String> map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
Intent intent = getIntent();
hashMap = (HashMap<String,String>) intent.getSerializableExtra("hashMap");
WebView webView = (WebView) findViewById(R.id.webviewe);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url,hashMap);
}
}
Is there any way that I can view that webpage without logging in again to the webview?
Haven't tested it, but using CookieManager ahould work.
Usage should be something like this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie(); //optional
cookieManager.setAcceptCookie(true);
Then loop over your cookies using the setCookie method.
Note: If useing lollipop and up you should also use setAcceptThirdPartyCookies.
Good luck.

Categories