android studio webview to use javascript for the link - javascript

this question is how to apply java script by link to webview https://dl.dropboxusercontent.com/s/lmibwymtkebspij/background.js after the page is fully loaded the background should turn green here is a sample code for loading the page
webView = findViewById(R.id.Web);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyWebChromeClient());
thank you in advance

maybe someone will come in handy load the text of the script into the script variable using get request to link the address of the script like this:
#SuppressLint("StaticFieldLeak")
class ProgressTask extends AsyncTask<String, Void, String> {
#Override
public String doInBackground(String... path) {
try {
content = getContent(path[0]);
} catch (IOException ex) {
content = ex.getMessage();
}
return content;
}
#Override
public void onPostExecute(String content) {
scriptbg = content;
Log.d("debug", scriptbg);
}
public String getContent(String path) throws IOException {
BufferedReader reader = null;
try {
URL url = new URL(path);
HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(10000);
c.connect();
reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder buf = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
}
return (buf.toString());
} finally {
if (reader != null) {
reader.close();
}
}
}
then we apply the script to our webView when the page is fully loaded like this:
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:" + Script);
Log.d("debug", "finish");
}

Related

Can't fetch dynamically changed HTML content(by JavaScript) in android using AsyncTask.

I'm using python script to dynamically change the content of my web-page. The link of the web page is: [HERE]
The web page contains table which has two columns:
1) Values between 1 to 5.
2) And the time when it is uploaded on the page.
It is displayed dynamically by the JavaScript on the page. See the source of the page opening the link above.
Now I'm creating a android application which displays the values in the text view by fetching that page and parsing the HTML. But the page source only contains JavaScript code. So whenever I fetch the HTML, it only displays the JavaScript even if it contains more than one rows with values.
My question is how to fetch those values dynamically?
I'm using AsyncTask and scheduling it every 10 seconds. My code is:
public class MainActivity extends AppCompatActivity {
TextView et ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (TextView) findViewById(R.id.editText);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[]{"https://rasppiclient.herokuapp.com/"});
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
DownloadWebPageTask performBackgroundTask = new DownloadWebPageTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute(new String[]{"https://rasppiclient.herokuapp.com/"});
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 50000 ms
}
public 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;
}
} catch (Exception e) {
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
}
}}
This does not work with DefaultHttpClient. What you could to is the evaluate the javascript and then get the content with AndroidJSCore.
JSContext context = new JSContext();
context.evaluateScript(yourJsString);
context.property("getWhatYouWantHere");
An example from the github looks like this
JSContext context = new JSContext();
context.evaluateScript("a = 10");
JSValue newAValue = context.property("a");
System.out.println(df.format(newAValue.toNumber())); // 10.0
String script =
"function factorial(x) { var f = 1; for(; x > 1; x--) f *= x; return f; }\n" +
"var fact_a = factorial(a);\n";
context.evaluateScript(script);
JSValue fact_a = context.property("fact_a");
System.out.println(df.format(fact_a.toNumber())); // 3628800.0

How to send data to server javascript using get request

I'm new to Java and Android development and try to create a simple app which should contact a web server A and send,add some data to text using a http get.
I have simple HTML code with some javascript (server A)
<html>
<head>
<title>This is my Webpage</title>`enter code here`
<h1>My Example</h1>
<script>
function myFunction(){
document.getElementById("myid").value=$ab;
}
</script
</head>
<body onload="myFunction()">
<input id="myid" type="text" />
</body>
</html>
and i have Android code to send http request to a local (server A)
public class MainActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.localhost/tuan/example.html";
MyCommandTask task = new MyCommandTask();
task.execute(url);
}
});
}
public class MyCommandTask extends AsyncTask<String,Void,Document>
{
#Override
protected Document doInBackground(String... params) {
String url=params[0];
try {
HttpGet httpGet = new HttpGet(url);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
}
}
}``
Now i want send text data and show result in text on (server A).
Please anyone help me.
Check this out dude. http://developer.android.com/training/basics/network-ops/connecting.html#download . Since you already got url string in doInBackground() method , use below code
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
Don't forget to change return type of doInBackground() to String as well. If you wanna go further , try grab volley which is one of the awesome network library https://developer.android.com/training/volley/index.html
Here is how you can post data to server. Put these line inside doInBackground()
private static final String POST_PARAMS = "userName=Pankaj";
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
Here is the source

loading an image file hosted in assets folder exposed with web server in the app

In my app, I have created web server which is hosting a web app. All the files of web app are placed in assets folder.
Now, i start the web server by running my application and then from crome brower, I try to run my web app by calling index.html file. The html, css part of the page is getting loaded properly but the images are not getting loaded in the page:
Here is my HttpRequestHandlerCode:
public class HomePageHandler implements HttpRequestHandler {
private Context context = null;
private static final Map<String, String> mimeTypes = new HashMap<String, String>() {
{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xhtml", "text/xhtml");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("svg", "image/svg+xml");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
put("m3u8", "application/vnd.apple.mpegurl");
put("ts", " video/mp2t");
}
};
public HomePageHandler(Context context){
this.context = context;
}
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
//String contentType = "text/html";
//Log.i("Sushill", "..request : " + request.getRequestLine().getUri().toString());
final String requestUri = request.getRequestLine().getUri().toString();
final String contentType = contentType(requestUri);
String resp = Utility.openHTMLStringFromAssets(context, "html" + requestUri);
writer.write(resp);
writer.flush();
// }
}
});
((EntityTemplate) entity).setContentType(contentType);
response.setEntity(entity);
}
}
/**
* Get content type
*
* #param fileName
* The file
* #return Content type
*/
private String contentType(String fileName) {
String ext = "";
int idx = fileName.lastIndexOf(".");
if (idx >= 0) {
ext = fileName.substring(idx + 1);
}
if (mimeTypes.containsKey(ext)) {
//Log.i("Sushill", "...ext : " + ext);
return mimeTypes.get(ext);
}
else
return "application/octet-stream";
}
To handle image, I tried this but it did not work :
if(contentType.contains("image")) {
InputStream is = Utility.openImageFromAssets(context, "html" + requestUri);
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can someone please help me in figuring out how to load the images also in my browser.
Thanks for any help
Do away with BufferedReader(new InputStreamReader' so you do away with UTF-8 too. Use only InputStream 'is'. Do away with writer. You are not showing what 'writer' is but do away with it. Use the OutputStream of the http connection. Keep the buffer and the loop where you read in the buffer and write from the buffer.

Get content string (not source code) of webPage on Android

I made a Javascript page to generate a JSON object for read it then from Android device.
I read it with the following code
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null){
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to donwload file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is that this code returns the source code of the webpage, and the source code is the script in Javascript, not the JSON string generated after execute it.
I need the JSON string and I need use Javascript to generate the JSON string because I access to an external service.
I haven't find any solution for this. I don't care if the possible solution involves the server or the Android terminal.
Thanks.
String myresponse=Html.escapeHtml(YourStringHere);
Try this.
private class MyJavaScriptInterface {
private MyJavaScriptInterface () {
}
public void setHtml(String contentHtml) {
//here you get the content html
}
}
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.ResponseChecker.setHtml"
+ "(document.body.innerHTML);");
}
}

Android to Javascript Calling issue

I have a android method which one is called from Javascript for getting the selected filepath info from phone gallery. Now i want to send the filepath name to the javascript method but if i return the filepath name from the android function then it will always return the last filepath info not the current one (May be its for callback!) or if i call any javascript method to send the file info after getting the file path then its show on debug console
like that:
05-04 22:07:50.274: ERROR/Web Console(331): ReferenceError: Can't find variable: SetImageFileName at undefined:1
And here is my Code what i have done...
public class Hello extends Activity {
/** Called when the activity is first created. */
WebView webview;
private ProgressDialog progressBar;
private static final int SELECT_PICTURE = 1;
private static final int PICK_IMAGE = 1;
private String selectedImagePath;
private String filemanagerstring;
private long siteId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setWebViewClient(new HelloWebViewClient());
WebSettings webSettings = webview.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webview.loadUrl(getString(R.string.ApplicationWebURL));
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
selectedFileName=getFileName(selectedImagePath);
if (selectedImagePath != null) {
filePath = selectedImagePath;
}
else if (filemanagerstring != null) {
filePath = filemanagerstring;
}
else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
}
final class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public String ShowPhoneGallery(long sId) {
try {
siteId=sId;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
//Calling Javascript to return the value
webview.loadUrl("javascript:SetImageFileName('"+ selectedImagePath +"')");
return selectedImagePath;
}
}
}
I
s there anybody who can help me on this issue ...
Looks to me like you need to put this line
webview.loadUrl("javascript:SetImageFileName('"+ selectedImagePath +"')");
in a different method which is then called from onActivityResult once your user has selected the picture

Categories

Resources