I'm trying to read a line of text from a URL and display the result in a Textview.
ISSUE/ERROR:
At present there is no error, the textview is not populated after I execute DownloadWebPage Async task.
INVESTIGATIONS
I believe I may not be calling this correctly, as I can't find any results from my debug calls, in DownloadWebPage. Also my URL has one line of code with two strings, if that makes any difference.
UPDATE:
In DownloadWebPage my logs commands are not showing in the log files - weird
CODE: ON CREATE:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox_list);
textView = (TextView) findViewById(R.id.textView6);
// Hashmap for ListView
inboxList = new ArrayList<HashMap<String, String>>();
//ASYNC TASK I CREATED
new DownloadWebPageTask().execute();
// Another Async Task in my code
new LoadInbox().execute();
}
CODE: AsyncTask for Parsing Data from URL & Setting Data to Textview
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(Html.fromHtml(result));
}
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.url.com/blah.php" });
}
Related
I am using JaxRS jersey for server and I have deployed it on aws. Http post request to server is working with postman but not with Http post apache client.
Following is my Java for Rest service
#Path("/data")
public class MyResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<trackerdetails> getIt() {
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
trackerdetails user = new trackerdetails();
List<trackerdetails> sendlist = (List<trackerdetails>) session.createQuery("from trackerdetails").list();
session.getTransaction().commit();
session.close();
return sendlist;
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public trackerdetails putit(trackerdetails track) {
track.setDate(new Date());
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(track);
session.getTransaction().commit();
session.close();
return track;
}
Following is my trackerdetails class
#Entity
#XmlRootElement
public class trackerdetails {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private int autoid;
private String latitude;
private String longitude;
private String devicename;
private Date date;
public trackerdetails(){
}
public int getAutoid() {
return autoid;
}
public void setAutoid(int autoid) {
this.autoid = autoid;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getDevicename() {
return devicename;
}
public void setDevicename(String devicename) {
this.devicename = devicename;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
Following is my Client side http post request
HttpPost httpPost = new HttpPost("myurl");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("devicename", "vip"));
nvps.add(new BasicNameValuePair("date", "hjksvn"));
nvps.add(new BasicNameValuePair("latitude", "hello"));
nvps.add(new BasicNameValuePair("longitude","hi"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
httpPost.setHeader("Cache-Control", "no-cache");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Host", "trackertest.herokuapp.com");
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
System.out.println(response2.toString());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
BufferedReader rd = new BufferedReader(
new InputStreamReader(response2.getEntity().getContent()));
StringBuffer result1 = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result1.append(line);
System.out.println(line);
System.out.println("");
}
System.out.println(result1);
EntityUtils.consume(entity2);
} finally {
response2.close();
}
Following is my error status is 400
Bad Requestdescription The request sent by the client was syntactically incorrect.
Your REST API expects request in JSON format but the way you are constructing request body using NameValuePair will not result in JSON format.
You should make a valid JSON request body either by using some libraries which can convert object into JSON like Jackson or you can manually construct JSON request body and then call your API.
Below is one way of manually constructing JSON request body -
HttpPost httpPost = new HttpPost("myurl");
StringBuilder jsonBody = new StringBuilder();
jsonBody.append("{");
jsonBody.append("\"devicename\" : ").append("\"vip\"").append(",");
// Pass a valid date because on server side, you are using Date object for accepting it
jsonBody.append("\"date\" : ").append("\"2017-09-23\"").append(",");
jsonBody.append("\"latitude\" : ").append("\"vip\"").append(",");
jsonBody.append("\"longitude\" : ").append("\"vip\"");
jsonBody.append("}");
StringRequestEntity requestEntity = new StringRequestEntity(jsonBody.toString(),"application/json","UTF-8");
httpPost.setRequestEntity(requestEntity);
httpPost.setHeader("Cache-Control", "no-cache");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Host", "trackertest.herokuapp.com");
// Rest code should remain same
I'm loading data from website to a webview in my application.And i need to make the video plays inside the webview.my problem is when i don't use setJavaScriptAsEnable the images and the video loads just fine but i can't play the video inside the webview it gives me the following error
An error occurred. try watching this video on youtube or enabe JavaScript.
however when i use setJavaScriptAsEnable(true) all the images and videos inside the webview disappears like the following image.
here's my code for the webview
void setupWebView(final WebView webView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
} else {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// add padding to the html page
webView.loadUrl("javascript:(function(){ document.body.style.paddingBottom = '30px'})();");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request) {
if (request.contains("http")) {// TODO: 14/08/2017 use regs
Log.d("url", request);
new CheckIfImageAsyncTask().execute(request);
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains("http")) {
new CheckIfImageAsyncTask().execute(url);
return true;
}
return false;
}
});
// settings
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
String data = "<div>" + post.getContent() + " </div>";
webView.loadDataWithBaseURL("file:///android_asset/", getHtmlData(data), "text/html", "utf-8", null);
}
private class CheckIfImageAsyncTask extends AsyncTask<String, Void, Boolean> {
private String url;
#Override
protected Boolean doInBackground(String... strings) {
url = strings[0];
URLConnection connection = null;
boolean isImage = false;
try {
connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
isImage = contentType.startsWith("image/");
} catch (IOException e) {
e.printStackTrace();
}
return isImage;
}
#Override
protected void onPostExecute(Boolean isImage) {
try {
if (isImage) {
Intent intent = new Intent(PostDetailsActivity.this, FullScreenImageActivity.class);
intent.putExtra("coverImage", url);
startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
FirebaseCrash.report(new Exception(e.getMessage()));
}
}
}
i searched a lot and i can't figure it out. any help will be appreciated. thanks in advance.
I am calling this method from JavaScript.
For the first time, it is giving null. But from the second time onwards, the data is coming.
Please help me.
#SuppressLint("JavascriptInterface")
public String loadClickedData() {
pDialog = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new HttpAsyncTaskClickedData()
.execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
return bdb.getmPosIdData();
}
Here we are getting data through AsyncTask in Android:
private class HttpAsyncTaskClickedData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag", "get_pos_details"));
nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
return GET(urls[0], nameValuePairs);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getApplicationContext(), result+" in post ",
// Toast.LENGTH_LONG).show();
pDialog.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
bdb.setmPosIdData(result);
}
}
This method is for getting data from the server:
public static String GET(String url, List<NameValuePair> pair) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
is = inputStream;
// convert inputstream to string
if (inputStream != null) {
// jObj = convertIsToJson(inputStream);
result = convertIsToJson(inputStream) + " ";
// jSonStr = result;
} else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
I am getting data from the server in json string format.
It is displaying attributes with null value like {pos["posid":null, "storeName":null]} etc..
In the following function
public String loadClickedData() {
pDialog = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new HttpAsyncTaskClickedData()
.execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
return bdb.getmPosIdData();
}
You execute your HttpAsyncTaskClickedData(), and return bdb.getmPosIdData() immediately. (Which will always be an issue for the 1st time)
The result of the AsyncTask is only available in onPostExecute, where you call bdb.setmPosIdData(result);.
#Override
protected void onPostExecute(String result) {
// ...
bdb.setmPosIdData(result); // result is only stored in bdb here!
}
The HttpAsyncTaskClickedData runs in the background, and possibly takes some time.
That is why your first call is always unable to get data, as you returned bdb.getmPosIdData() immediately after executing your AsyncTask.
private class HttpAsyncTaskClickedData extends
AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("tag", "get_pos_details"));
nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
return GET(urls[0], nameValuePairs);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getApplicationContext(), result+" in post ",
// Toast.LENGTH_LONG).show();
data = result;
pDialog.dismiss();
bdb.setmPosIdData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(MainActivity.this, "dialog title",
"dialog message", true);
}
#SuppressLint("JavascriptInterface")
public String loadData() {
Toast.makeText(getApplicationContext(), data+ " hi ",
Toast.LENGTH_LONG).show();
return data;
}
}
and calling loadData() method from javascript.
This function is for get data by using post url in javascript
function jsonPost(){
var http = new XMLHttpRequest();
var url = "http://192.168.0.9/btrepo/btrepo/android_api.php";
var params = "tag=fav_stores&mobile=984989874";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
alert("hello "+http.send(params));
}
I have a Webpage loading into my WebView. This webpage loads a login page for the website. As the user enters his credentials he gets redirected to a certain page. I want to stop the loading of the webpage after user enters his credentials and get redirected to another activity instead of the default redirected page.
My idea of doing this is to catch the redirected url and compare it with the url created by me, if both match it should stop loading the default webpage and load another activity. However, Iam able to catch the redirected Urls and show them in a AlertDialog, but cannot stop the loading of the default web page.
Can anyone help me on this?
This is what I have tried:-
myWebView.loadUrl(url);
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
String absoluteUrl = view.getUrl();
absoluteUrl = Uri.decode(absoluteUrl);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"Authorize/index"+myId;
//int redirectedCount = redirectedUrl.length();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(absoluteUrl);
alert.show();
if(absoluteUrl!=null && absoluteUrl.contains(redirectedUrl))
{
view.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
HttpClient httpClient = new DefaultHttpClient();
URL myUrl;
URLConnection connection;
try
{
myUrl = new URL(url);
connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
int size = connection.getContentLength();
}
catch (Exception e) {}
String htmlContent = "";
HttpPost httpGet = new HttpPost(url);
HttpResponse response;
HttpContext httpContext = new BasicHttpContext();
try
{
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
}
catch (Exception e) {}
return true;
}
EDIT:- Suggested by #SimplePlan
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
}
private void showAlert2(String Url)
{
// TODO Auto-generated method stub
Url = Uri.decode(Url);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"/AuthorizeDevice/index"+deviceId;
//int redirectedCount = redirectedUrl.length();
if(Url!=null && Url.contains("redirect_uri"+redirectedUrl+"?{StandardTokens}"))
{
myWebView.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(Url);
alert.show();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
showAlert2(url);
return true;
}
Try to implement like:
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(progressBar.isShowing())
{
progressBar.dismiss();
}
showAlert2(url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
view.loadUrl(url);
HttpClient httpClient = new DefaultHttpClient();
URL myUrl;
URLConnection connection;
try
{
myUrl = new URL(url);
connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
int size = connection.getContentLength();
}
catch (Exception e) {}
String htmlContent = "";
HttpPost httpGet = new HttpPost(url);
HttpResponse response;
HttpContext httpContext = new BasicHttpContext();
try
{
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
htmlContent = convertToString(inputStream);
}
}
}
catch (Exception e) {}
return true;
}
And showAlert2(url) method:
public void showAlert2(String Url) {
//String absoluteUrl = view.getUrl();
Url = Uri.decode(Url);
//int absoulteCount = absoluteUrl.length();
String redirectedUrl = endpointHost+"Authorize/index"+myId;
//int redirectedCount = redirectedUrl.length();
if(Url!=null && Url.contains(redirectedUrl))
{
myWebView.stopLoading();
Intent myIntent = new Intent(Details.this, Home.class);
startActivity(myIntent);
}else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Details.this);
alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.setMessage(Url);
alert.show();
}
}
Try as per my answer and give me feedback on this
could someone please help me. I'm having difficulty with LoadUrl and javascript.
The code below seems to work sorta ok (killing the app then trying again makes it work) on my old HTC running 2.3 however, my Xperia Z which runs the latest Android gets stuck on "Attempting to get Comments".
The section of code it is sticking on is InjectJavaScript() wherein this fails to LoadUrl (I know this as onPageFinished is never called). The strange thing is statistics part of the code works fine and its identical.
Sorry its pretty messy code...
#SuppressLint("SetJavaScriptEnabled")
public class MyIceland extends SherlockActivity {
private static class FetchMyIceland extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
setDialog("Checking Farera for WoW Data....",2);
switch(FETCHFROMMYICELAND){
case 0: //contact Farera for information.
Log.i("IcePlan","Farera Check/Empathica Front Page Retrieval...");
MyIceland.url = MainActivity.BASE_URL+"android_get.php?action=myiceland&store="+MainActivity.STORE;
try {
String Result = HTTPGET();
if(Result.startsWith("no")){ //content for today?
setDialog("No WoW Data Available for Today\nAbout to contact Empathica.com....",2);
activity.runOnUiThread(new Runnable(){#Override public void run() {MyIceland.FetchFromEmpathica("http://www.iceland.empathica.com/LogonIceland.aspx");;}}); }
else{FETCHFROMMYICELAND = 100;} //we do have content...
} catch (IOException e1) {Log.i("IcePlan",e1.toString());} catch (Exception e1) {Log.i("IcePlan",e1.toString());
} //we have data for today, so download and sort it.
break;
case 1: //get comments
setDialog("About to Contact Empathica.com for Comments....",2);
try {Thread.sleep(1000);} catch (InterruptedException e) {Log.i("IcePlan",e.toString());}
activity.runOnUiThread(new Runnable(){#Override public void run() {MyIceland.FetchFromEmpathica("http://v2.empathica.com/Reporting1/ClientReporting/LiveDataReporting.aspx?RID=1&PID=Comments&TID=1a");}});
break;
case 2: //POST data
setDialog("Posting all data to Farera.com \n So we don't have to do this again today....",2);
List<NameValuePair> params = new ArrayList<NameValuePair>();
try {params.add(new BasicNameValuePair("frontpage", URLEncoder.encode(FRONTPAGE, "utf-8")));} catch (UnsupportedEncodingException e) {Log.e("IcePlan",e.toString());}
try {params.add(new BasicNameValuePair("comments", URLEncoder.encode(COMMENTS, "utf-8")));} catch (UnsupportedEncodingException e) {Log.e("IcePlan",e.toString());}
MyIceland.url = MainActivity.BASE_URL+"android_get.php?action=store_myiceland&store="+MainActivity.STORE;
String POST = HTTPPOST(params);
if(POST != null){FETCHFROMMYICELAND = 100; }
break;
}
return null;
}
#Override
protected void onPreExecute(){super.onPreExecute();}
#Override
protected void onPostExecute(Void arg0){
if(FETCHFROMMYICELAND == 100) new MyIceland.DisplayMyIceland().execute();
}
}
//------------------------------------------------------
//-----------------------------------------------------
//-----------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_iceland);
ctx = getApplicationContext();
activity = this;
//webView2 = (WebView) findViewById(R.id.myIwebview2_widget);
/********************************************************/
/****************** ABS ********************************/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().show();
// This is a workaround for http://b.android.com/15340 from
// http://stackoverflow.com/a/5852198/132047
BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(
R.drawable.bg_striped);
bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setBackgroundDrawable(bg);
BitmapDrawable bgSplit = (BitmapDrawable) getResources().getDrawable(
R.drawable.bg_striped);
bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
/************************************************************/
try {
ov_e = (TextView) findViewById(R.id.overall_exp_tx);
ov_r= (TextView) findViewById(R.id.overall_rank_tx);
s_e= (TextView) findViewById(R.id.storeexp_tx);
st_e= (TextView) findViewById(R.id.staffexp_tx);
t_e= (TextView) findViewById(R.id.tillexp_tx);
res= (TextView) findViewById(R.id.responses_tx);
res_r= (TextView) findViewById(R.id.resp_rank_tx);
MyIceland.list = (ListView) findViewById(R.id.wow_lv); // set list
MyIceland.adapter = new SeparatedListAdapter(ctx, false); // initialise adapter
//authenticate
CookieSyncManager.createInstance(this);
SetUp(); //Set up webView
setDialog("Loading MyIceland data...\n Please be Patient...",0);
new FetchMyIceland().execute(); //get data
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("IcePlan",e.toString());
}
}
private static String HTTPPOST(List<NameValuePair> params){
String Resp = null;
try {
HttpClient client = new DefaultHttpClient();
String postURL = MyIceland.url;
HttpPost post = new HttpPost(postURL);
//List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("user", "kris"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Resp = "not null";
}
} catch (Exception e) {
Log.e("IcePlan HTTPPOST",e.toString());
}
return Resp;
}
private static String HTTPGET() throws Exception, IOException{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
Log.i("IcePlan",str.toString());
return str.toString();
}
private void SetUp(){
webView = (WebView) findViewById(R.id.myIwebview_widget); //load custom webview
webView.clearView(); //clear view of browser
webView.clearFormData(); //clear form data
webView.setNetworkAvailable(MainActivity.isOnline(ctx)); //set network state
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setPluginsEnabled(false); //no flash
webView.getSettings().setJavaScriptEnabled(true); // enable javascript
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webView.getSettings().setSavePassword(false); //don't show password dialog
webView.setVerticalScrollBarEnabled(false); //no scrolling!
webView.setHorizontalScrollBarEnabled(false); //no scrolling!
webView.getSettings().setLoadsImagesAutomatically(false); // NO Images
webView.getSettings().setSaveFormData(false); //Don't save form data
//webView.setVisibility(View.VISIBLE);
return;
}
private static void FetchFromEmpathica(String EmpathURL){
/*****************************************************
* setWebViewClient to load pages
*****************************************************
*****************************************************
*/
webView.loadUrl(EmpathURL);
MyIceland.page = 0;
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Log.i("IcePlan",url);
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("IcePlan","Starting...");
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.i("IcePlan","Loaded...");
switch(FETCHFROMMYICELAND){
case 0:
if(MyIceland.page == 0){
MyIceland.page=1;
try {Thread.sleep(500);}catch (InterruptedException e) {Log.e("IcePlan",e.toString());}
view.loadUrl("javascript: {" +
"document.forms[0].elements['userNameBox'].value = 'xxx.xxxxx';" +
"setTimeout(function(){document.forms[0].elements['passwordBox'].value = 'xxxxxxx';},300);" +
"setTimeout(function(){document.forms[0].elements['loginButton'].click();},300); };");
}else if(MyIceland.page == 1){
MyIceland.page=2;
try {Thread.sleep(1000);}catch (InterruptedException e) {Log.e("IcePlan",e.toString());}
String oAuthUrl=("v2.empathica.com");
if(url.indexOf(oAuthUrl) > -1)
{
Log.i("Contains","Auth URL");
InjectJavaScript(view);
}else{view.loadUrl("javascript:{};");}
}else if (MyIceland.page ==2){
if(MyIceland.FRONTPAGE == null){
Log.i("IcePlan","Inject");
InjectJavaScript(view);
}else{MyIceland.page=3;}
}
break;
case 1:
if(MyIceland.COMMENTS == null){
Log.i("IcePlan","Inject Comments");
InjectJavaScript(view);
}else{MyIceland.page=100;} //else end
break;
}
super.onPageFinished(view, url);
}
});
return;
}
}
private static void setDialog(final String msg, final int dothis){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
switch(dothis){
case 0: //set up and show
if (dlg == null) {
dlg = new ProgressDialog(activity);
dlg.setTitle("Loading...");
dlg.setMessage(msg);
dlg.setCancelable(activity.isFinishing());
dlg.show();
}
break;
case 1: //remove and reset to null
if (dlg.isShowing() || dlg!=null) {
dlg.hide();
dlg = null;
}
break;
case 2:
if (dlg.isShowing() || dlg!=null) {
dlg.setMessage(msg);
}
}
}});
return;
}
/*********************************************************
* HACK - Inject Javascript to get the HTML we want!
*********************************************************/
private static void InjectJavaScript(WebView view){
switch(FETCHFROMMYICELAND){
case 0: //get front page
setDialog("Attempting to get Statistics...",2);
view.loadUrl("javascript:{" +
"var element = document.getElementById('ReportDivFPRank');"+
"if (typeof(element) != 'undefined' && element != null)"+
"{" +
"var e=document.getElementById(\"ReportDivFPCR\");"+
"var content=e.innerHTML;"+
"window.HTMLOUT.processHTML(content);"+// exists.
"}" +
"};");
break;
case 1: //get comments
setDialog("Attempting to get Comments....",2);
view.loadUrl("javascript:{" +
"var element = document.getElementById('AddNPSDetails');"+
"if (typeof(element) != 'undefined' && element != null)"+
"{" +
"var e=document.getElementById(\"_ctl1_ReportDiv\");"+
"var content=e.innerHTML;"+
"window.HTMLOUT.processHTML(content);"+// exists.
"}" +
"};");
break;
}
return;
}
/*********************************************************
* Class injected into Empathica website to get HTML
* Continues onto our controlling AsyncTask
* #author Vince
*
********************************************************/
public static class MyJavaScriptInterface
{
public void processHTML(final String html)
{
setDialog("Caught RAW data....",2);
if(html != ""){
//MyIceland.webView2.loadDataWithBaseURL("notreal/", html, "text/htm", "utf-8",null);
if(FETCHFROMMYICELAND == 0){ setDialog("Retrieved Area Statistics....",2); MyIceland.FRONTPAGE = html;}
else if(FETCHFROMMYICELAND == 1){ setDialog("Retrieved Area Comments....",2); MyIceland.COMMENTS = html;}
FETCHFROMMYICELAND++;
new MyIceland.FetchMyIceland().execute();
}
return;
}
}
}
I see that FetchFromEmpathica is going to be called again when you load the second page, and you set again a new WebViewClient() to the webview, put it on the setup() method so it is going to be called once.
Make sure that your Xperia is 4.1.2, nonetheless look what is mentioned on
Reference: JavascriptInterface methods in WebViews must now be annotated
Beginning in Android 4.2, you will now have to explicitly annotate public methods with #JavascriptInterface in order to make them accessible from hosted JavaScript. Note that this also only takes effect only if you have set your app's minSdkVersion or targetSdkVersion to 17 or higher.
Add it and import android.webkit.JavascriptInterface
So the code will be up-to-date to last versions.
#JavascriptInterface
public void processHTML(final String html)
{
//code
}