Android WebView Compile a Form and submit with Javascript - javascript

I'm trying to complete this form :
http://www.lbalberti.it/whatsup.asp?codist=57247
I was able to insert value to the two textbox but the button doesn't work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
final String user = getIntent().getStringExtra("username");
final String psw = getIntent().getStringExtra("password");
MyWebView view = new MyWebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setDomStorageEnabled(true);
view.loadUrl("http://www.lbalberti.it/whatsup.asp?codist=57247");
view.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
v.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView v, String url) {
v.loadUrl("javascript:" +
"var y = document.getElementsByName('login')[0].value='"+user+"';" +
"var x = document.getElementsByName('password')[0].value='"+psw+"';");
}
});
setContentView(view);
}
class MyWebView extends WebView {
Context context;
public MyWebView(Context context) {
super(context);
this.context = context;
}
}
The following code doesn't work :
"var k = document.getElementByTagName('form')[0].submit();"
or
"var k = document.getElementByName('newlogin')[0].submit();"

#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
view.evaluateJavascript("javascript:document.getElementById('username').value ='" + strUsername + "';javascript:document.getElementById('password').value = '" + strPassword + "';javascript:document.getElementById('loginButton').click();", null);
} else {
view.loadUrl("javascript:document.getElementById('username').value = '" + strUsername + "';javascript:document.getElementById('password').value = '" + strPassword + "';javascript:document.getElementById('loginButton').click();");
}
}

Related

Download file via BLOB link in Android webview

I have a website that is navigated from within a webview. One of the pages generates a ZIP file that is downloaded via a BLOB URL. I discovered that this is not supported by webview, so I have tried implementing this solution:
Download Blob file from Website inside Android WebViewClient
However, it is not working for me. Breakpoints in convertBase64StringToZipAndStoreIt are never hit.
UPDATE: I've found that I'm getting an HTTP 404. I've tried using blobUrl and blobUrl.substring(5) and the result is the same either way. The BLOBs are downloading fine in Chrome, though.
Webview setup:
private void launchWV() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
setContentView(R.layout.activity_self_service_launcher);
mWebView = (WebView) findViewById(R.id.activity_launcher_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setUserAgentString("Mozilla/5.0 (Android; X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24" + getClientVersionInfo());
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.setWebViewClient(new MyWebViewClient(this));
mWebView.setWebChromeClient(new MyWebChromeClient(this));
mWebView.addJavascriptInterface(new JavaScriptInterface(getApplicationContext()), "Android");
}
Function called from shouldOverrideUrlLoading() (only the else condition for BLOB URLs is of concern):
private boolean handleRequest(WebView view, String url) {
String filename;
if (!checkInternetConnection()) {
ShowNetworkUnavailableDialog(false);
return true;
}
else {
if (url.contains("view/mys") || url.contains("view/myy") || url.contains("blob") || url.contains("view/mye")) {
if (url.contains("view/mys")) {
filename = getResources().getString(R.string.mys_file_name).concat(".pdf");
} else if (url.contains("view/myy")) {
filename = getResources().getString(R.string.form_file_name).concat(".pdf");
} else if (url.contains("blob")) {
filename = getResources().getString(R.string.mys_file_name).concat(".zip");
} else {
filename = getResources().getString(R.string.mye_file_name).concat(".pdf");
}
if (!url.contains("blob")) {
String cookies = CookieManager.getInstance().getCookie(url);
DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(url));
downloadRequest.addRequestHeader("cookie", cookies);
downloadRequest.allowScanningByMediaScanner();
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
try {
dm.enqueue(downloadRequest);
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.connection_unavailable), Toast.LENGTH_LONG).show();
return false;
}
} else {
String blobURL = JavaScriptInterface.getBase64StringFromBlobUrl(url);
mWebView.loadUrl(blobURL);
}
Toast.makeText(getApplicationContext(), getResources().getString(R.string.download_message), Toast.LENGTH_LONG).show();
return true;
} else if (!url.contains(getMetadata(getApplicationContext(), HOSTNAME))) {
//Navigate to external site outside of webview e.g. Help site
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
} else if(url.contains(getResources().getString(R.string.about_url))) {
mWebView.loadUrl(url);
return false;
} else {
if (savedInstanceState == null) {
mWebView.loadUrl(url);
}
return false;
}
}
}
JavaScriptInterface class:
public class JavaScriptInterface {
private Context context;
private NotificationManager nm;
public JavaScriptInterface(Context context) {
this.context = context;
}
#JavascriptInterface
public void getBase64FromBlobData(String base64Data) throws IOException {
convertBase64StringToZipAndStoreIt(base64Data);
}
public static String getBase64StringFromBlobUrl(String blobUrl){
if(blobUrl.startsWith("blob")){
return "javascript: var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + blobUrl.substring(5) + "', true);" +
"xhr.setRequestHeader('Content-type','application/zip');" +
"xhr.responseType = 'blob';" +
"xhr.onload = function(e) {" +
" if (this.status == 200) {" +
" var blobZip = this.response;" +
" var reader = new FileReader();" +
" reader.readAsDataURL(blobZip);" +
" reader.onloadend = function() {" +
" base64data = reader.result;" +
" Android.getBase64FromBlobData(base64data);" +
" }" +
" }" +
"};" +
"xhr.send();";
}
return "javascript: console.log('It is not a Blob URL');";
}
private void convertBase64StringToZipAndStoreIt(String base64Zip) throws IOException {
final int notificationId = 1;
String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/YourFileName_" + currentDateTime + "_.zip");
byte[] zipAsBytes = Base64.decode(base64Zip.replaceFirst("^data:application/zip;base64,", ""), 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(zipAsBytes);
os.flush();
if(dwldsPath.exists()) {
NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MY_DL")
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("MY TITLE")
.setContentText("MY TEXT CONTENT");
nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
if(nm != null) {
nm.notify(notificationId, b.build());
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
nm.cancel(notificationId);
}
}, delayInMilliseconds);
}
}
}
}
One thing I know I am unclear on is what URL should be going into the call to xhr.open in the class.
I also tried using onDownloadStart with the same result.
Any insight is greatly appreciated!

javascript function can't find the element

I need to call some file uploader JavaScript from code behind. The JavaScript is basically customizing the style of the file uploader control. However, the JavaScript function can't find the element. I get this from the inspector:
*o = {element: null,
action: "/Web/UploadHandler.axd?UploadID=55f3930c-6aa9-4201…ccfdfae6c6&ObjectID=145649&RelationshipTypeID=223",
sizeLimit: 209715
when it should look like this:
o = {element: div#uploadContent, action: "/Web/UploadHandler.axd?UploadID=c1829b40-7869-4f19…411e7a542c&ObjectID=151808&RelationshipTypeID=223", sizeLimit: 20971520, acceptTypes: "image/*", onSubmit: ƒ, …}
qq.extend
This is the code:
div = new HtmlGenericControl("div") { ID = ("dlWrapper") };
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
var imageUploader = (ImageUpload)CreateImageUploader(ActiveObject, p, litScript);
div.Controls.Add(imageUploader);
controls.Add(div);
private static Control CreateImageUploader(ObjectInstance objectInstance, PropertyType propertyType, Literal litScript)
{
ImageUpload imageUpload = new ImageUpload (objectInstance, litScript) { ID = ControlFactory.GetControlId(ControlFactory.IMAGE_PREFIX, ControlFactory.PROPERTY_TYPE_PREFIX, objectInstance.Id, propertyType.Id), Width = Unit.Pixel(80), Height = Unit.Pixel(30) };
PropertyInstanceValue piv = objectInstance.GetPropertyInstanceValue(propertyType.Id);
return imageUpload;
}
public class ImageUpload : FileUpload
{
public ObjectInstance ActiveObject {get; set; }
public Literal litScript { get; set; }
private string uploadID;
private string accept = "image/*";
public string UploadID
{
get
{
if (string.IsNullOrEmpty(uploadID))
{
uploadID = GetUploadID();
}
return uploadID;
}
set { uploadID = value; }
}
public ImageUpload(ObjectInstance activeObject, Literal literal)
{
ActiveObject = activeObject;
litScript = literal;
}
public string GetUploadID()
{
string uploadID;
if (HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] != null)
{
uploadID = (string)HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID];
HttpContext.Current.Cache.Remove("cacheFlashSessionID_" + uploadID);
HttpContext.Current.Cache.Remove("cacheFlashAuth_" + uploadID);
}
uploadID = Guid.NewGuid().ToString();
HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] = uploadID;
HttpContext.Current.Cache.Insert("cacheFlashSessionID_" + uploadID, HttpContext.Current.Session.SessionID, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
// ReSharper disable PossibleNullReferenceException
HttpContext.Current.Cache.Insert("cacheFlashAuth_" + uploadID, HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
// ReSharper restore PossibleNullReferenceException
}
return uploadID;
}
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
sb.Remove(0, sb.Length);
sb.Append("<script type=\"text/javascript\">");
int maxBytes = ProcessUnity.Common.Utility.GetMaxRequestLength() * 1024;
sb.Append("var uploader = new qq.FileUploader({ element: document.getElementById('uploadContent'), action: '" + Context.Request.ApplicationPath + "/UploadHandler.axd?UploadID=" + UploadID + "&ObjectID=" + ActiveObject.Id + "&RelationshipTypeID=" + EDM.Common.Definitions.RelationshipTypeId.IMAGE_FILE + "', sizeLimit: " + maxBytes + ", acceptTypes:'" + accept + "', onSubmit: uploadStart, onComplete: uploadComplete, onError: uploadError, multiple: false });");
sb.Append("</script>");
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, typeof(ImageUpload), Guid.NewGuid().ToString(), sb.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), sb.ToString());
}
base.OnLoad(e);
}
private object GetScriptManager()
{
foreach (DictionaryEntry entry in Page.Items)
{
if (entry.Key.ToString().IndexOf("System.Web.UI.ScriptManager") >= 0)
{
return entry.Value;
}
}
return null;
}
}
It looks like you're expecting litScript here:
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
To be modified by the OnLoad event:
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
// ...
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
// ...
base.OnLoad(e);
}
But your OnLoad is constructing its own local Literal. Just because it has the same litScript name as the outer Literal doesn't mean that the two are related. In short, nothing is writing that div to the page.

Java Program TextFile Issue

I have a program where a text file is read in and then each word in the file is outputted, followed by the # of times it is repeated throughout the file.
Use the following code.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Desktop\\formate.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try this code:
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
HashMap<String, Integer> count = new HashMap<String, Integer>();
while (scanner.hasNext())
{
String word = scanner.next();
if (count.containsKey(word))
{
count.put(word, count.get(word) + 1);
}
else
{
count.put(word, 1);
}
}
scanner.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Entry<String, Integer> entry : count.entrySet())
{
writer.write("#" + entry.getKey() + " " + entry.getValue()+"\r\n");
}
writer.close();
}
This also, it is a lot simpler if You can't use HashMap or BufferedReader:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class WordCounter
{
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
LinkedList<Word> words = new LinkedList<Word>();
while (scanner.hasNext())
{
String word = scanner.next();
addWord(words, word);
}
scanner.close();
WriteToFile(outputFile, words);
}
private static void WriteToFile(File outputFile, LinkedList<Word> words) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Word word : words)
{
writer.write("#" + word.getWord() + " " + word.getCount() + "\r\n");
}
writer.close();
}
private static void addWord(LinkedList<Word> words, String word)
{
for (Word aWord : words)
{
if (aWord.getWord().equals(word))
{
aWord.incrementCount();
return;
}
}
words.add(new Word(word, 1));
}
}
class Word
{
private String word;
private int count;
public Word(String word, int count)
{
this.word = word;
this.count = count;
}
public String getWord()
{
return word;
}
public void setWord(String word)
{
this.word = word;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public void incrementCount()
{
count++;
}
#Override
public String toString()
{
return "Word: " + word + " Count: " + count;
}
}

Marker.remove() is not working in Google map?

In my application I have two set of marker when I click a marker another marker should be removed.But marker.remove() is not working, have checked whether the marker!=null then am removing the marker but the marker is not removed please help me.
public class MapFragment extends Fragment implements LocationListener
{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.187.247.199/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONObject jsonobject = null;
JSONObject jsonobject1 =null;
JSONObject jsonobject2 =null;
JSONObject ja = null;
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
JSONArray jsonarray2 = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
ArrayList<HashMap<String, String>> arraylist11;
ArrayList<HashMap<String, String>> arraylist12;
ArrayList<HashMap<String, String>> arraylist;
List<Marker> markerList = new ArrayList<Marker>();
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
public Marker marker;
Marker stop;
String RegistrationNo="";
LatLng destination,source,destination2,center;
Polyline polylin;
String ime1,destname,routeid;
GMapV2GetRouteDirection md;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude,destlat,destlong,sourcelat,sourcelong,destlat2,destlong2;
String ime,reg,regi;
Geocoder geocoder;
List<Address> addresses;
CircleOptions circleOptions;
Circle circle;
// LatLng val;
float[] distance = new float[2];
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
ImageView imageView1;
TextView Address;
public MapFragment() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
Address=(TextView)rootView.findViewById(R.id.adressText);
//imageView1=(ImageView) rootView.findViewById(R.id.imageView1);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
new DestinationJSON().execute();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView markerLabel = (TextView)v.findViewById(R.id.ime);
TextView destiname=(TextView)v.findViewById(R.id.destname);
TextView route=(TextView)v.findViewById(R.id.routeid);
markerLabel.setText(regi);
destiname.setText(destname);
route.setText(routeid);
Log.e("imeid", ""+ime1);
return v;
}
});
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
//Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition arg0) {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng= mMap.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
Log.e("lati",""+lat);
Log.e("longi",""+lng);
Log.d("TAG", latLng.toString());
//mMap.clear();
if(circle!=null){
circle.remove();
//mMap.clear();
}
circleOptions = new CircleOptions();
circleOptions.center(latLng);
//circleOptions.fillColor(Color.TRANSPARENT);
circleOptions.radius(10000);
circleOptions.strokeColor(Color.TRANSPARENT);
circle = mMap.addCircle(circleOptions);
Log.e("",""+circle);
center = mMap.getCameraPosition().target;
new GetLocationAsync(center.latitude, center.longitude).execute();
/* geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
Log.e("address",""+address);
String city = addresses.get(0).getLocality();
Log.e("city",""+city);
String state = addresses.get(0).getAdminArea();
Log.e("state",""+state);
String country = addresses.get(0).getCountryName();
Log.e("contry",""+country);
String postalCode = addresses.get(0).getPostalCode();
Log.e("postalcode",""+postalCode);
String knownName = addresses.get(0).getFeatureName();
Log.e("knownName",""+knownName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Here 1 represent max location result to returned, by documents it recommended 1 to 5
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}*/
}
});
}
});
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
if(stop!=null){
stop.remove();
}
arg0.showInfoWindow();
regi=arg0.getTitle().toString();
Log.e("aaa", ""+regi);
JSONPost jsonpost= new JSONPost();
ja=jsonpost.datewise(regi);
Log.e("Home_details..", "" + ja);
// new DownloadJSON2().execute();
try
{
arraylist11 = new ArrayList<HashMap<String, String>>();
arraylist12 = new ArrayList<HashMap<String, String>>();
jsonarray = ja.getJSONArray("Routeinbus");
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
Log.e("G>>>>>>>>>>>", "" + json);
// Retrive JSON Objects
// map.put("flatID", jsonobject.getString("flatID"));
map.put("FromLat", json.getString("FromLat"));
map.put("FromLong", json.getString("FromLong"));
sourcelat = json.getDouble("FromLat");
sourcelong=json.getDouble("FromLong");
source=new LatLng(sourcelat, sourcelong);
map.put("Fromaddress", json.getString("Fromaddress"));
map.put("ToLat", json.getString("ToLat"));
map.put("ToLong", json.getString("ToLong"));
routeid=json.getString("RouteID");
destname=json.getString("Toaddress");
destlat2=json.getDouble("ToLat");
destlong2=json.getDouble("ToLong");
destination2=new LatLng(destlat2, destlong2);
jsonarray1 = json.getJSONArray("Routes");
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonarray1);
for (int j = 0; j <jsonarray1.length(); j++) {
jsonobject1 = jsonarray1.getJSONObject(j);
jsonarray2=jsonobject1.getJSONArray("stages");
Log.d("jsonarray2", "" + jsonarray2);
for(int k=0;k<jsonarray2.length();k++)
{
jsonobject2 =jsonarray2.getJSONObject(k);
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Lat",jsonobject2.getString("Lat"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Lat"));
map1.put("Long",jsonobject2.getString("Long"));
map1.put("StopName", jsonobject2.getString("StopName"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Long"));
// map1.put("LiveLongitude",jsonobject1.getString("LiveLongitude"));
// Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject1.getString("LiveLongitude"));
arraylist12.add(map1);
Log.e("arraylist12", ""+arraylist12);
//marker=mMap.addMarker(new MarkerOptions().position(destination2).icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)));
for (int m = 0; m < arraylist12.size(); m++)
{
final LatLng stopposition = new LatLng(Double .parseDouble(arraylist12.get(m).get("Lat")),Double.parseDouble(arraylist12.get(m).get("Long")));
Log.e("position", ""+stopposition);
String stopname = arraylist12.get(m).get("StopName");
Log.e("markcheck",""+stopname);
final MarkerOptions options = new MarkerOptions().position(stopposition);
//mMap.addMarker(options);
stop=mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)).title(stopname));
}
}
}
arraylist11.add(map);
Log.e("arraylist11",""+arraylist11);
}
}catch (Exception e) {
String result = "Error";
}
return false;
}
});

Passing array from js to android

Hi I have this activity code:
public class WebActivity extends ActionBarActivity {
TextView number;
WebView mWebView;
CountDownTimer mTimer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
number = (TextView) findViewById(R.id.number);
mTimer=new CountDownTimer(10000, 1000) {
String[] myArray={"javascript:document.getElementById(\"utente\").value=\""+LoginActivity.username+"\"; document.getElementById(\"j_password\").value=\""+LoginActivity.password+"\"; document.querySelector(\"input[type=submit]\").click();","javascript:document.getElementById(\"menu-servizialunno:_idJsp14\").click();"};
int currentIndex=0;
public void onTick(long millisUntilFinished) {
number.setText("seconds remaining: " + millisUntilFinished / 1000 + " " + (currentIndex + 1) + "/" + (myArray.length + 1));
}
//code comment start
// i think this part could be written better
// but it works!!
public void onFinish() {
if (currentIndex<myArray.length) {
number.setText("done!");
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
mTimer.start();
} else{
mTimer.cancel();
}
}
//code comment end
};
mTimer.start();
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebSliderWebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(mWebView, url);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
mWebView.loadUrl("http://www.ss16374.scuolanext.info");
}
and this js function:
function voti( showSubject, showData, showVote ){
var votitotali = []
document.getElementById("menu-servizialunno:_idJsp14").click();
setTimeout(function(){
elems = document.querySelectorAll("td, legend");
for(var i = 0; i < elems.length; i++){
curText = elems[i].innerHTML;
if( elems[i].tagName == "LEGEND" && showSubject ){
votitotali += [curText]
//console.log( curText );
}else if( elems[i].innerHTML.indexOf("Voto") != -1 && showVote ){
votitotali += [curText.replace(/.*\(([0-9\.]+)\)/,"$1")]
//console.log( curText.replace(/.*\(([0-9\.]+)\)/,"$1") );
}else if( /\d{2}\/\d{2}\/\d{4}/.test(elems[i].innerHTML) && showData ){
votitotali += [curText.replace(/.*(\d{2}\/\d{2}\/\d{4}).*/,"$1")]
//console.log( curText.replace(/.*(\d{2}\/\d{2}\/\d{4}).*/,"$1") );
}
}
document.getElementsByClassName("btl-modal-closeButton")[0].click()
},3000);
return votitotali
}
Can I store the votitotali array in my android app? Because I need to get some informations from a site and I have to print them on a textView in the app, but I really do not know how to do this using webview...
That's actually easy. You need to inject a Java object which has a method receiving an array:
class MyReceiver {
#JavascriptInterface
public void receive(String[] input) {
// input is your data!
}
}
// At the very beginning
mWebView.addJavascriptInterface(new MyReceiver(), "receiver");
// ...
Then if you call it like that in your JavaScript code:
receiver.receive(voti( ... ));
You will get the array inside MyReceiver.receive.
Note that non-string array elements (e.g. numbers) will not be converted into strings, and will be replaced by nulls instead.

Categories

Resources