how to enable Javascript in the HttpURLConnection - javascript

i am write a code for access the sever php file and to do find and sort data from the server.... the code works the is no error, when i am using the wamp server but i am change local host in to sever there show a message
"This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support"
this is code i am used for access the sever side php file...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timelist);
Intent datafmto = getIntent();
rsltlist =(ListView)findViewById(R.id.rsltlist);
frm = datafmto.getExtras().getString("from");
to = datafmto.getExtras().getString("to");
Toast.makeText(this, frm + to, Toast.LENGTH_LONG).show();
new asd().execute("http://www.some severname.com/test.php", frm, to);
}
public class asd extends AsyncTask<String,Void,List<models>> {
StringBuffer buffer= null;
BufferedReader red = null;
HttpURLConnection con = null;
#Override
protected List<models> doInBackground(String... params) {
frm= params[1];
to = params[2];
JSONObject json =new JSONObject();
try {
json.put("from",frm);
json.put("to",to);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(String.valueOf(json));
try {
URL url = new URL(params[0]);
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.connect();
DataOutputStream os = new DataOutputStream(con.getOutputStream());
os.writeBytes(String.valueOf(json));
System.out.println(String.valueOf(json));
os.flush();
os.close();
InputStream in = con.getInputStream();
red = new BufferedReader(new InputStreamReader(in));
String line = "";
buffer = new StringBuffer();
while ((line=red.readLine())!= null){
buffer.append(line);
}
String out = buffer.toString();
System.out.println(out);
JSONObject timing = new JSONObject(out);
JSONArray jarray = timing.getJSONArray("times");
List<models> timelist = new ArrayList<>();
for (int i = 0;i<jarray.length();i++){
JSONObject lastobj = jarray.getJSONObject(i);
models mod = new models();
mod.setRoute(lastobj.getString("route"));
mod.setStart(lastobj.getString("start"));
mod.setStop(lastobj.getString("stop"));
timelist.add(mod);
}
return timelist;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(con!=null){
con.disconnect(); }
try {
if (red!=null){
red.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

Related

Issue populating Textview with data from website via URL

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" });
}

Unable to get data at first click in android webview with server communication

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));
}

Stop loading a webpage on Url redirection android

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

LoadUrl Javascript not loading at all

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
}

How to Hide Android WebView Notifications?

I am using 8 - 10 different WebViews in one layout and loading different content in each WebView.
While loading Webview shows different messages like "Loading.." "Processing.." etc.
Is there any way to hide these notifications?
Try to use HttpClient to get the webpage's html code and then use WebView.loadData to load the entire page into WebView.
private class exampleHttpTask extends AsyncTask<Integer, Integer, String> {
public String convertStreamToString(InputStream is, String charset) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, charset));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
protected String doInBackground(Integer... params) {
String r = "";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://google.com"); // replace with the url
HttpResponse hr = hc.execute(get);
if(hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream is = hr.getEntity().getContent();
r = convertStreamToString(is, "UTF-8");
} else {
r = "Error";
}
} catch(Exception e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
WebView wv = (WebView) findViewById(R.id.web_view); // replace web_view with the webView id
wv.loadData(result, "text/html", "utf-8");
}
protected void onPreExecute() {
}
}
Then call new exampleHttpTask().exec() to load the webpage.

Categories