Gridview ,open new activity on item click - javascript

Clicking on the items here is supposed to go to the specific activity, but as I have given the if else statement, instead of going to the specific activity, the homework-2 activity goes as soon as the apps run. And after pressing back three times the main activity comes again. When I press on specific item on menu, supposed to go to the next activity, but nothing happens.
public class MainActivity extends AppCompatActivity {
GridView grid_view;
ArrayList <HashMap<String,String>>arrayList = new ArrayList<>();
HashMap<String,String>hashMap = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid_view = findViewById(R.id.grid_view);
creatTable ();
myAdapter myAdapter = new myAdapter();
grid_view.setAdapter(myAdapter);
}
private class myAdapter extends BaseAdapter {
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = layoutInflater.inflate(R.layout.item_lay,parent,false);
TextView item_cat = myView.findViewById(R.id.item_cat);
TextView item_title = myView.findViewById(R.id.item_title);
HashMap<String,String>hashMap = arrayList.get(position);
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
item_cat.setBackgroundColor(color);
Random rnd1 = new Random();
int color1 = Color.argb(255, rnd1.nextInt(256), rnd1.nextInt(256), rnd1.nextInt(256));
item_title.setBackgroundColor(color1);
String cat = hashMap.get("CAt");
String title = hashMap.get("Title");
item_cat.setText(cat);
item_title.setText(title);
if (cat.contains("HomeWork_207")){
startActivity(new Intent(MainActivity.this,HomeWork_One.class));
}else if (cat.contains("HomeWork_214.1")){
startActivity(new Intent(MainActivity.this,HomeWork_Two.class));
}
return myView;
}
}
private void creatTable() {
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork_207");
hashMap.put("Title","bmi cal");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork_214.1");
hashMap.put("Title","Divisible");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.2");
hashMap.put("Title","Leap year");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.3");
hashMap.put("Title","Week");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.4");
hashMap.put("Title","Exam Grade");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.5");
hashMap.put("Title","Bill");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.1");
hashMap.put("Title","নামতা");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.2");
hashMap.put("Title","E.No & sum");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.3");
hashMap.put("Title","E.No & sum");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.3");
hashMap.put("Title","N.terms");
arrayList.add(hashMap);
}
}
I am trying this , way but problem is not solved yet.

Related

TextView with a specific item from a array using Day of the Month

I'm new with this things, I need to do a app that show the user a unique phrase each day of the month, like today is 25, the textView should show "A potato." Tomorrow the textView should show "A carrot." and the next month, day 25, show the same potato one, and day 26 show the same carrot one.
This is my code:
When I start it on my phone, it does nothing.
public class MainActivity extends AppCompatActivity {
String q;
Resources con;
TextView frase1;
TextView frase2;
TextView frase3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frase1 = (TextView)findViewById(R.id.textView1);
frase2 = (TextView)findViewById(R.id.textView2);
frase3 = (TextView)findViewById(R.id.TextView3);
con = getResources();
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
if (Calendar.DAY_OF_MONTH == 1){
q = con.getStringArray(R.array.dia)[1];
frase1.setText(q);
}
if (Calendar.DAY_OF_MONTH == 2){
q = con.getStringArray(R.array.dia)[2];
frase1.setText(q);
}
if (Calendar.DAY_OF_MONTH == 3){
q = con.getStringArray(R.array.dia)[3];
frase1.setText(q);
}
}
}
I think that you are entering none of the if statement and thus nothing is being set to TextView. Try using an else statement like below. Try this -
public class MainActivity extends AppCompatActivity {
String q;
Resources con;
TextView frase1;
TextView frase2;
TextView frase3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frase1 = (TextView)findViewById(R.id.textView1);
frase2 = (TextView)findViewById(R.id.textView2);
frase3 = (TextView)findViewById(R.id.TextView3);
con = getResources();
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
if (day == 1){
q = getResources().getStringArray(R.array.dia)[1];
frase1.setText(q);
}
else if (day == 2){
q = getResources().getStringArray(R.array.dia)[2];
frase1.setText(q);
}
else if (day == 3){
q = getResources().getStringArray(R.array.dia)[3];
frase1.setText(q);
} else {
q = getResources().getStringArray(R.array.dia)[3];
frase1.setText(q);
}
}
this doesnt answser your question, but you can replace all ifs with frase1.setText(con.getStringArray(R.array.dia)[day]);
Also, try using logs to find which value creates the problem (for example, Log.i(TAG,day);)

file download angularjs and servlets

I have an image stored in a database table, with primary key for a particular number. That image below the database to a folder of the java project by means of a servlet.
So far, so good.
My problem is that I need to download that image to the user and I can not do it.
My steps are as follows:
JSP:
$scope.downloadFile = function(){
var tkAct = $scope.ticketActual.tknum;
var param = {
nroTk: tkAct
};
var res = $http.post($scope.testHost +"/downloadAttachment",JSON.stringify(param));
});
res.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
}
SERVLET:
#WebServlet("/downloadAttachment")
public class downloadAttachment extends HttpServlet {
// size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
private final int BYTES_DOWNLOAD=1024;
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sess = request.getSession();
Controller ctrl = Controller.get();
ServletContext sc = getServletContext();
//int nroTicket=-1;
//nroTicket = 104;
System.out.println(request.getParameter("NroTk"));
System.out.println(request.getAttribute("NroTk"));
JSONObject joParam = getParametrosJo(request);
Long lNroTk = (Long) joParam.get("nroTk");
int nroTicket = lNroTk.intValue();
Vector<String> vNamesFile = ctrl.getFile(nroTicket,sc.getRealPath("/downloads"));
if(vNamesFile.size()==1){
String archivo = vNamesFile.get(0);
File downloadFile = new File(archivo);
String nombreFile = getNombreFileEnvio(nroTicket,downloadFile.getName());
// if you want to use a relative path to context root:
String relativePath = getServletContext().getRealPath("/downloads/");
System.out.println("relativePath = " + relativePath);
// obtains ServletContext
ServletContext context = getServletContext();
String mimeType = context.getMimeType(nombreFile);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition","attachment;filename="+nombreFile);
System.out.println("Obteniendo el Stream...");
System.out.println("nombre del file es: "+nombreFile);
InputStream is = sc.getResourceAsStream("/downloads/" + downloadFile.getName());
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream(relativePath+downloadFile.getName());
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}else{
byte[] zip = zipFiles(getServletContext().getRealPath("/downloads/"),vNamesFile, 95);
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=AdjuntosTicket95" + ".ZIP");
sos.write(zip);
sos.flush();
}
}
private JSONObject getParametrosJo(HttpServletRequest request) throws IOException{
StringBuilder buffer = new StringBuilder();
BufferedReader joParam = request.getReader();
String texto="";
String str = null;
while ((str = joParam.readLine()) != null) {
buffer.append(str);
//texto+=str;
}
texto = buffer.toString();
System.out.println(texto);
if(!texto.equalsIgnoreCase("")){
JSONObject obj = JSONObject.parse(texto);
return obj;
}else{
return null;
}
}
private byte[] zipFiles(String path, Vector<String> vNamesFile, int nroTk) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : vNamesFile) {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(getNombreFileEnvio(nroTk,fileName)));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
bis.close();
fis.close();
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
private String getNombreFileEnvio(int nroTk, String nombreEnFS){
String[] aNombreFile = nombreEnFS.split("%");
String nombreFile = aNombreFile[1];
return nombreFile;
}
}
How do I recover that image from the database to the folder / downloads / and deliver it to the user?
Thank you

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

Android WebView Compile a Form and submit with 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();");
}
}

Categories

Resources