Can not connect to "xampp server localhost" with android studio - android

I have tried to connect to my localhost xampp with android studio using AsyncTask class. Here is AsyncTask but it gives error saying Failed to connect
to /10.0.2.2:800
I tried my real ip address cmd --> ipconfig IPV4 and some other tricks but
they did not succeed
belwow is my app structure
AsyncTask using class
package app.buil.land.food.doymaj.doymaj;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by ProgrammingKnowledge on 1/5/2016.
*/
public class backGroundActivities extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
backGroundActivities (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.0.2.2:800/login.php";
if(type.equals("login")) {
try {
String phone_number = params[1];
// String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("phone_number","UTF-8")+"="+URLEncoder.encode(phone_number,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
Log.e("Line_from_php_server",result);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
here is my MainActivity
package app.buil.land.food.doymaj.doymaj;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText phone_Number;
EditText user_Name;
EditText pass_Word;
Button singButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// singButton = (Button)findViewById(R.id.sing_id);
// singButton.setOnClickListener(kyListener);
phone_Number =(EditText)findViewById(R.id.mobile_id);
user_Name =(EditText)findViewById(R.id.name_id);
pass_Word =(EditText)findViewById(R.id.p_id);
}
// Push_Identity db = new Push_Identity(this,"CustomerDatabas.db",null,1);
public boolean validate(EditText[] fields){
for(int i = 0; i < fields.length; i++){
EditText currentField = fields[i];
if(currentField.getText().toString().length() <= 0){
switch (i){
case 0:
Toast.makeText(getApplicationContext(),"شماره تلفن وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
case 1:
Toast.makeText(getApplicationContext(),"نام کاربری وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
case 2:
Toast.makeText(getApplicationContext(),"رمز وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
}
return false;
}
}
return true;
}
//private View.OnClickListener kyListener = new View.OnClickListener() {
public void send_number(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
boolean fieldsOK = validate(new EditText[] { phone_Number, user_Name, pass_Word });
if (fieldsOK ==true){
String Phon = phone_Number.getText().toString();
Toast.makeText(getApplicationContext(),Phon,Toast.LENGTH_LONG);
// the Tooast dose not display anything
// it seems that the EditText is empty buy i enter the value in
// in it.
String type ="login";
backGroundActivities back = new backGroundActivities(this);
back.execute(type,Phon);
//
}
}
// };
}
XML
<EditText
android:id="#+id/mobile_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:background="#drawable/customized_edtitext"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="#drawable/ic_smartphone"
android:elevation="2dp"
android:textStyle="bold"
android:hint="#string/register_phone_commnet"
android:fontFamily="#font/iransansmedium"
android:textSize="12sp"
/>
<EditText
android:id="#+id/name_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_below="#id/mobile_id"
android:background="#drawable/customized_edtitext1"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="#mipmap/ic_user"
android:elevation="2dp"
android:textStyle="bold"
android:hint="#string/register_user_commnet"
android:fontFamily="#font/iransansmedium"
android:textSize="12dp" />
<EditText
android:id="#+id/p_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_below="#+id/name_id"
android:background="#drawable/customized_edtitext2"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="#mipmap/ic_unlocked"
android:elevation="2dp"
android:textStyle="bold"
android:hint="#string/register_pass_commnet"
android:fontFamily="#font/iransansmedium"
android:textSize="12sp"
android:paddingEnd="10dp" />
here is the url of my php page
enter image description here
And some more information: I have Genymotion installed and also bluestack, and VirtaulBox. Do they confilct about port? I mean could these softwares cause conflicting ports Apache xampp and their ports?

My Xampp was working with Port: 80 as shown in below image. So writing below ip address as http://10.0.2.2:80/ worked for me.

If you have wifi and your computer and real device (mobile) is connected to the same wifi you can use NGROK software tool to run and debug your app in your real device.
Run the ngrok.exe and type ngrok http 80, it will give you an address like the below image.
Just use the url in your app where you use your ip address.
It is best to use.

This answer assumes, that the browser screenshot shows a successful page load. I believe, the error page is a bit more gray.
There might be a firewall issue at hand. Since you are using a non-standard port, the firewall exceptions that are installed with XAMPP might not cover that.
Go to the Windows Firewall Advanced settings -> inbound rules. Now add a rule that allows for traffic on the TCP port 800. Make sure, that you uncheck the public profile so that if you are on a public wifi, nobody will be able to connect to this application.
Now check with a browser from the smartphone, if your PHP Application is accessible.

Related

how can i print persian with bixolon printers

I create an app for android in this app i connect to a bixolon(350plusll) printer and i print a tiket when my String is in english it is ok and my tiket print good but when my String is in persian my result print is not ok and my characters is revers and not correct
i use screenshot it was ok but it was very slow and not logiacal
please help me for resolve this problem
thanks alot
this is my code
package com.example.bahram.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import com.bixolon.printer.BixolonPrinter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class PrintTicketActivity extends Activity {
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print_tiket);
btn= findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//I set code page of the printer here because i want the printer print persian so i set that on Farsi
MainActivity.mBixolonPrinter.setSingleByteFont(BixolonPrinter.CODE_PAGE_FARSI);
//i have a file it's name is new2.txt and readContentOfFile is a method which read all of text in new2.txt and at last print data on the paper
MainActivity.mBixolonPrinter.printText(readContentOfFile(),BixolonPrinter.ALIGNMENT_CENTER,BixolonPrinter.TEXT_ATTRIBUTE_FONT_A,BixolonPrinter.TEXT_SIZE_HORIZONTAL1,true);
}
});
}
//read all of the text in new2.txt and return text
String readContentOfFile() {
StringBuilder text = new StringBuilder();
InputStream inputStream = getResources().openRawResource(R.raw.new2);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}
}
content of new2.txt is bottom text
اما جدیدترین شاهکار سازمان لیگ و هیات فوتبال استان تهران که از سوی همین سازمان لیگ به عنوان برترین هیات ایران انتخاب شد، جانمایی توپ شروع مسابقه روی قیف(یا کنز) بود که در دیدار سایپا و پیکان صورت گرفت.
You can use one of the Farsi options available for the Bixolon printer, for example one of the following:
// Farsi option : Mixed
MainActivity.mBixolonPrinter.setFarsiOption(BixolonPrinter.OPT_REORDER_FARSI_MIXED);
// Farsi option : Right to Left
MainActivity.mBixolonPrinter.setFarsiOption(BixolonPrinter.OPT_REORDER_FARSI_RTL);

Accessing database on server using android studio

I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.
Here is my code, any help would be appreciated.
`package com.example.vishal.connectiontest;
import java.sql.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button B1 = (Button)findViewById(R.id.button);
final TextView e1 = (TextView) findViewById(R.id.HelloWorld);
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String result = main();
e1.setText(result.toString());
}
catch(java.lang.Exception e){
System.out.println("Exception");
}
}
});
}
}
class DemoClass
{
public static String main()throws Exception
{
String url = "jdbc:mysql://125.10.10.214/demo" ;
String uname = "root";
String pass = "";
String ip = "";
String query = "Select UserName from user_info where Id = '90000515'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String name = rs.getString("UserName");
return (name);
}
}`
Easiest way of integrating Database to your Android Application is using Firebase.
It's really easy to use and other than Database, it has File Storage Services, Cloud Messaging, Analytics and many more.
I would recommend use of firebase database.
Here have a look at it's Documentation:
https://firebase.google.com/docs/database/

How to connect my Android emulator to my local web server

I've set up a web server on my own computer using xampp and I am trying to access the server in my App like this:
package com.example.connect2php;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
static String yahooStackInfo = "http://localhost/21/test03.php";
static String stockSymbol = "";
static String stockDaysLow = "";
static String stockDaysHigh = "";
static String stockChange = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... parms) {
// TODO Auto-generated method stub
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(yahooStackInfo);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
theStringBuilder.append(line + "\n");
}
result = theStringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (inputStream != null)
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
JSONObject jsonObject;
try {
result = result.substring(7);
result = result.substring(0, result.length() - 2);
// Log.v("JSONParser RESULT " , result);
jsonObject = new JSONObject(result);
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
JSONObject resultsJSONObject = queryJSONObject
.getJSONObject("results");
JSONObject quoteJSONObject = resultsJSONObject
.getJSONObject("quote");
stockSymbol = quoteJSONObject.getString("symbol");
stockSymbol = quoteJSONObject.getString("DaysLow");
stockSymbol = quoteJSONObject.getString("DaysHigh");
stockSymbol = quoteJSONObject.getString("Change");
}
catch (JSONException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
TextView line1 = (TextView) findViewById(R.id.line1);
TextView line2 = (TextView) findViewById(R.id.line2);
TextView line3 = (TextView) findViewById(R.id.line3);
line1.setText("Stack: " + stockSymbol + " : " + stockChange);
line2.setText("Days Low " + stockDaysLow);
line3.setText("Days High " + stockDaysHigh);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
But it didn't work. The server code is just:
echo 'cbfunc({"query":{"count":1,"created":"2013-08-24T13:38:58Z","lang":"en-US","results": {"quote":{"symbol":"MSFT","AverageDailyVolume":"47950000","Change":"+2.36","DaysLow":"34.00","DaysHigh":"35.20","YearLow":"26.26","YearHigh":"36.43","MarketCapitalization":"289.5B","LastTradePriceOnly":"34.75","DaysRange":"34.00 - 35.20","Name":"Microsoft Corpora","Symbol":"MSFT","Volume":"225493744","StockExchange":"NasdaqNM"}}}})';
Here is the ip detail:
#ppeterka
Microsoft Windows [版本 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\hcleeab>ipconfig / all
錯誤: 無法辨識或不完整的命令列。
使用方式:
ipconfig [/allcompartments] [/? | /all |
/renew [adapter] | /release [adapter] |
/renew6 [adapter] | /release6 [adapter] |
/flushdns | /displaydns | /registerdns |
/showclassid adapter |
/setclassid adapter [classid] |
/showclassid6 adapter |
/setclassid6 adapter [classid] ]
其中
adapter 連線名稱
(允許使用萬用字元 * 與 ?,請見範例)
選項:
/? 顯示此說明訊息。
/all 顯示完整設定資訊。
/release 釋放指定介面卡的 IPv4 位址。
/release6 釋放指定介面卡的 IPv6 位址。
/renew 更新指定介面卡的 IPv4 位址。
/renew6 更新指定介面卡的 IPv6 位址。
/flushdns 清除 DNS 解析快取。
/registerdns 重新整理所有 DHCP 租用並重新登錄 DNS 名稱。
/displaydns 顯示 DNS 解析快取的內容。
/showclassid 顯示介面卡所有允許的 DHCP 類別識別碼。
/setclassid 修改 DHCP 類別識別碼。
/showclassid6 顯示介面卡允許的所有 IPv6 DHCP 類別識別碼。
/setclassid6 修改 IPv6 DHCP 類別識別碼。
預設是僅顯示每個繫結到 TCP/IP 之介面卡的 IP 位址、子網路遮罩及預設閘道。
對於 Release 與 Renew,如果沒有指定介面卡名稱,則會釋放或更新所有繫結到
TCP/IP 介面卡的 IP 位址租用。
對於 Setclassid 與 Setclassid6,如果沒有指定 ClassId,則將移除 ClassId。
範例:
ipconfig ... 顯示資訊
ipconfig /all ... 顯示詳細資訊
ipconfig /renew ... 更新所有介面卡
ipconfig /renew EL* ... 更新所有名稱開頭為 EL 的連線
ipconfig /release Con ... 釋放所有符合的連線,
例如 "Local Area Connection 1" 或
"Local Area Connection 2"
ipconfig /allcompartments ... 顯示所有區間的相關資訊
ipconfig /allcompartments /all ... 顯示所有區間的詳細資訊
C:\Users\hcleeab>ipconfig
Windows IP 設定
無線區域網路介面卡 無線網路連線:
媒體狀態 . . . . . . . . . . . . .: 媒體已中斷連線
連線特定 DNS 尾碼 . . . . . . . . : hgcbroadband.com
通道介面卡 isatap.hgcbroadband.com:
媒體狀態 . . . . . . . . . . . . .: 媒體已中斷連線
連線特定 DNS 尾碼 . . . . . . . . : hgcbroadband.com
通道介面卡 6TO4 Adapter:
通道介面卡 Teredo Tunneling Pseudo-Interface:
預設閘道 . . . . . . . . . . . . .:
C:\Users\hcleeab>
You should use:
http://10.0.2.2/21/test03.php
10.0.2.2 is the special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
See: Emulator Network Address Space in the official docs
Though you could have added a logcat, this is most likely why your app fails to obtain the content:
static String yahooStackInfo = "http://localhost/21/test03.php";
This tells your android device to try and access itself. Localhost is the device itself. substitute that with the hostname or IP address of your host.
You might need to check firewall settings too...
Update
Updated with the IP in the comment:
static String yahooStackInfo = "http://223.18.60.177/21/test03.php";

Reading file from AVD sd card and displaying text view

I have a text file that has this information
Casino Canberra;21 Binara Street, Canberra ACT, 2601;Canberra Casino is a casino located in Civic in the central part of the Australian capital city of Canberra. The Casino is relatively small compared with other casinos in Australia.;(02) 6257 7074;www.canberracasino.com.au
National Museum of Canberra;Parkes Place, Canberra ACT, 2601;The National Museum of Australia explores the land, nation and people of Australia. Open 9am - 5pm every day except Christmas Day. General admission free.;(02) 6240 6411;www.nga.gov.au
which is stored in the sdcard
after this i retrieve the values using this method
package au.edu.canberra.g30813706;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Environment;
public class FileReader extends Activity{{
ArrayList<read> sInfo = new ArrayList<read>();
ArrayList<String> sLines = new ArrayList<String>();
String line;
String[] saLineElements;
String txtName = "AccomodationTxt.txt";
File root = Environment.getExternalStorageDirectory();
File path = new File(root, "CanberraTourism/" + txtName);
try {
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream(path)));
while ((line = br.readLine()) != null)
{
sLines.add(line);
//The information is split into segments and stored into the array
saLineElements = line.split(";");
//for (int i = 0; i < saLineElements.length; i++)
// sInfo.add(new read(saLineElements[i]));
sInfo.add(new read(saLineElements[0], saLineElements[1], saLineElements[3], saLineElements[4], saLineElements[5]));
}
br.close();
}
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
But i also have and object class to store each individual item into
package au.edu.canberra.g30813706;
public class read {
public String name;
public String address;
public String info;
public String phone;
public String www;
public read (String name, String address, String info, String phone, String www)
{
this.name = name;
this.address = address;
this.info = info;
this.phone = phone;
this.www = www;
}
}
The only issue im having is trying to display the information in a text view which i have no idea how to call the values i need
This is where im trying to insert it
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
}}
You should probably look into using the Application class. You can think of Application as a GUI-less activity which works like the model in a program following the MVC pattern. You can put all of your read objects into a data structure in your Application and then access them with accessors and mutators of your own design.
Take a look at this official doc.
As your code stands, you can only access your instances of read by obtaining a reference to your FileReader class, but your two activities are separate entities. You'd have to do something like this:
// This is the main activity and should be launched first
// Check your manifest to make sure it launches with this activity
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity
{
// Declare the file reader so you'll have a reference
FileReader reader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
// Instantiate the file reader
reader = new FileReader();
// Now you can access the array inside FileReader
// obviously, you need to have a text view called my_textView defined in the
// layout file associated with this activity
TextView myTextView = (TextView)findViewById(R.id.my_textView);
// displays the first element in FileReader's array list
myTextView.setText((String)reader.get(0));
}}
At the moment, you might be in a bit deep for your current understanding of Android and/or Java. I would encourage you to follow as many code examples as possible, get comfortable with Android and then go back to your project when you have a little more experience.

is there any way to make a webview running android 4.0 perform at an acceptable level?

On both the emulator and on my galaxy nexus device, this simple demo app takes an entire 1000 milliseconds or longer to select or deselect a checkbox. I wanted to write the majority of my app in javascript so I could reuse the code across ios / android / web, but this is a deal breaker.
Here is my code:
(The Activity)
package com.mycompanyname;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.mycompanyname.R;
public class JavascriptListViewTestActivity extends Activity {
private JavascriptListViewTestActivity parent = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebChromeClient chrome = new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
parent.showDialog(consoleMessage.message() + "\n" + consoleMessage.lineNumber());
return true;
}
};
WebViewClient client = new WebViewClient() {
};
WebView webView = (WebView)findViewById(R.id.webView1);
webView.setWebChromeClient(chrome);
webView.setWebViewClient(client);
webView.getSettings().setJavaScriptEnabled(false);
webView.getSettings().setAllowFileAccess(false);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setDatabaseEnabled(false);
webView.getSettings().setDomStorageEnabled(false);
webView.getSettings().setGeolocationEnabled(false);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.getSettings().setLightTouchEnabled(false);
webView.getSettings().setLoadWithOverviewMode(false);
webView.getSettings().setNavDump(false);
webView.getSettings().setNeedInitialFocus(false);
webView.getSettings().setPluginsEnabled(false);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.getSettings().setSaveFormData(false);
webView.getSettings().setSavePassword(false);
webView.getSettings().setSupportMultipleWindows(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setUseDoubleTree(false);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String html = readText(R.raw.listview);
webView.loadData(html, "text/html", "UTF-8");
}
private void showDialog(String message)
{
AlertDialog alert = new AlertDialog.Builder(parent).create();
alert.setMessage(message);
alert.show();
}
private String readText(int resourceId)
{
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
StringBuffer outputBuffer = new StringBuffer();
try
{
while ((readLine = br.readLine()) != null)
{
outputBuffer.append(readLine);
}
return outputBuffer.toString();
}
catch (Exception e) {
e.printStackTrace();
return "";
}
finally
{
// TODO: might throw - use IOUtils.close()
try
{
is.close();
br.close();
}
catch (IOException ex)
{
showDialog(ex.toString());
}
}
}
}
(The xml layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
(The html loaded in the webview)
<html>
<body>
<input type="checkbox" />
</body>
</html>
I realize this is over a year old, but you could try implementing fastclick.js: https://github.com/ftlabs/fastclick
I've used it successfully on quite a few projects. As the page explains:
...mobile browsers will wait approximately 300ms from the time that
you tap the button to fire the click event. The reason for this is
that the browser is waiting to see if you are actually performing a
double tap.
Same goes for interactions within a webview (as far as I know).

Categories

Resources