Connecting Android webservices to localhost - android

I am fighting with this particular thing but not able to resolve it.. Please help me...
I am trying to connect the android program to a local host which is running on apache server.
I found examples in internet which directly connect to their own websites. So, they are giving the name spaces(in the following program) with their name spaces.
But since I have my web application in my local host, what should I mention?
(I am pasting my code here)
MainActivity.java
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private String METHOD_NAME = "sum"; // our webservice method name
private String NAMESPACE = "http://calculator.backend.web.org&#8221"; //I have to give the name space here I guess
private String SOAP_ACTION = NAMESPACE + METHOD_NAME;
private static final String URL = "http://localhost:8081/Test/services/Caluclate?wsdl";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.txtAddition);
try
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("i", 5);
request.addProperty("j", 15);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION,envelope);
Object result = envelope.getResponse();
System.out.println(" Result : " + result.toString());
((TextView) findViewById (R.id.txtAddition)).setText("Addition : "+result.toString());
} catch (Exception E) {
E.printStackTrace();
((TextView) findViewById (R.id.txtAddition)).setText("Error: " + E.getClass().getName() + ":" + E.getMessage());
}
}
}
Calculate.java(program in the web app)
public class Caluclate {
public int sum() {
return (1);
}
public int subtract(int i, int j) {
return (i - j);
}
public int multiply(int i, int j) {
return (i * j);
}
public int divide(int i, int j) {
return (i / j);
}
}
Thank you for helping me...

I assume the service endpoint is running on a remote machine but not directly on the mobile device.
In this case localhost would not work because it is a local alias for 127.0.0.1 which resolves to itself.
In your code at the moment, every device will try to reach services hosted by itself. You have to replace localhost by the ip of the server hosting the endpoint

You can use :
private static final String URL = "http:// 10.0.2.2:8081/Test/services/Caluclate?wsdl";

hi friend find your PC allocated IP (Go to CMD and type ipconfig and find IP address) replace "Localhost" with that IP Address .this works for me.

Related

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/

Create a JSON file and send it to other device using wifi direct

I'm trying to create an application that allows two devices to connect using wifi direct and send a message from one device to another in a JSON file format and then parse that file into a text view. So far I'm not concern about the wifi part because I know it's very difficult and I want to start with the "easy" part of my project. I have this code so far.
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText edtx1;
TextView txvw1;
TextView txvw2;
TextView txvw3;
TextView txvw4;
TextView txvw5;
Button btn;
String Message;
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edtx1 = (EditText) findViewById(R.id.editText1);
txvw1 = (TextView) findViewById(R.id.textView1);
txvw2 = (TextView) findViewById(R.id.textView2);
txvw3 = (TextView) findViewById(R.id.textView3);
txvw4 = (TextView) findViewById(R.id.textView4);
txvw5 = (TextView) findViewById(R.id.textView5);
//txvw1.setText(edtx1.getText().toString());
makeJSON();
}
});
}
public JSONArray makeJSON() {
JSONArray jArr = new JSONArray();
JSONObject jObj = new JSONObject();
try {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
//Long tsLong = System.currentTimeMillis() / 1000;
//String ts = tsLong.toString();
jObj.put("Created_on:", currentDateTimeString);
jObj.put("Sent_by:", Build.MODEL);
jObj.put("MAC_Address:", macAddress);
jObj.put("Number_of_Hops:", 1);
jObj.put("Message:", edtx1.getText());
txvw1.setText(jObj.getString("Created_on:"));
txvw2.setText(jObj.getString("Sent_by:"));
txvw3.setText(jObj.getString("MAC_Address:"));
txvw4.setText(jObj.getString("Number_of_Hops:"));
txvw5.setText(jObj.getString("Message:"));
jArr.put(jObj);
} catch (Exception e) {
System.out.println("Error:" + e);
}
return jArr;
}
}
I want to have a button and when clicked just send the information on the edittext to the json object called message. So at the end i will have something like this
{
"Created on": Date,
"Sent By": "name",
"MAC Address": "FF:FF:FF:FF:FF:FF",
"Number of Hops": "This number I will figure it out later",
"Message": "Message"
}
And then send that file to the other device.
UPDATE:
I just edited the code above and now it's kind of working, at least I think is doing what i want. The problem here is with the device name and the MAC address. I know that now the MAC address cannot be taken within the app but I can just fill in that part and make it static. But how can i retrieve the name of the device for example my device is called "Daniel" how can i have that retrieved with a code?
I haven't tested this out, but this might help.
Here are the official docs for using wifi-direct in case you need them
android docs: wifi-direct
You can try to send your json object over as a string (its what i have to do when i POST to my server) and on the other side parse it like a standard json.
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("key_1", "value_1");
builder.appendQueryParameter("key_2", "value_2");
String json = builder.build().getEncodedQuery();
Once you have a class built you can get the data from it and then set with .setText()
let me know if you need an example on how to do that.
--- EDIT ---
as far was getting your device name, i found this snippet of code that should work for you, as long as you are ok with asking for bluetooth permission.
add this to your manifest
<uses-permission android:name="android.permission.BLUETOOTH" />
and in your code
public String getPhoneName(){
BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();
return deviceName;
}

How to properly install mysql connector in Eclipse?

First of all I'd like to say that it is a project for a course in my university and at the same time my first app for Android which is more complicated that a calculator, so I understand that I could have done some unforgivable mistakes, but my priority is that the code should work. It can be insecure and not considering some cases, but as long as those cases won't appear, it will do.
My app is intended to be running on Android and first of all there should appear login screen which takes login and password, makes the hash of the password and contacts a database on a web server to compare hashes. I was told to use a free database db4free.net.
I created a class Serwer, which would be responsible exclusively for contacting the database. As far as I understood from tutorials and stackoverflow questions and answers, the connection should consist of:
Loading the driver,
Registering it in the DriverManager class,
Using getConnection method to open the connection, passing the credentials,
Preparing and executing SQL query,
Fetching a result set.
I also learned that I should download a mysql-connector-java-5.1.38-bin.jar file. As some threads on stackoverflow suggested, I copied it into main directory of the project (I have to copy the workspace and take to professor's computer when I finish), added it to Libraries tab of properties as an external library. Now when I run the project on my smartphone, I get a java.lang.ClassNotFoundException: Didn't find class "com.mysql.jdbc.Driver" error. I also tried to check the library in Order and Export tab - then it even doesn't compile, returning Conversion to Dalvik format failed with error 1.
I've tried many scenarios in other stackoverflow threads, such as cleaning the project in many configurations, changing the order of build path, etc. I suspect that I've made a simple, stupid mistake that I do not see and I hope you will recognize it.
Here is my Serwer class:
package com.planer.serwer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Driver;
import com.planer.MainActivity;
import com.example.planer.R;
import com.planer.pracownik.Pracownik;
public class Serwer {
private Connection conn = null;
private static Driver driver;
private static int status;
private MainActivity parentActivity;
private final String user = parentActivity.getResources().getString(R.string.db_login);
private final String pass = parentActivity.getResources().getString(R.string.db_pass);
private final String url= "jdbc:mysql://db4free.net:3306/kalendarzplaner";
public static final int STATUS_GOOD = 0;
public static final int STATUS_NO_CONNECTION = 1;
public static final int STATUS_NOT_AUTHENTICATED = 2;
public static final int STATUS_SQL_EXCEPTION = 4;
public static final int STATUS_NO_DRIVER = 8;
public Serwer(MainActivity parentActivity){
status = STATUS_NO_CONNECTION;
try {
driver = new com.mysql.jdbc.Driver();
} catch (Exception ex) {
status |= STATUS_NO_DRIVER;
} catch (NoClassDefFoundError e){
status |= STATUS_NO_DRIVER;
}
this.parentActivity = parentActivity;
}
public Pracownik authorize(String login, String passhash){
Pracownik pracownik = new Pracownik("","",false,status);
status |= this.polacz();
if(status != Serwer.STATUS_GOOD) {
pracownik.status |= status;
return pracownik;
}
Statement statement = null;
ResultSet resultSet = null;
String query = "select passhash, imie_nazwisko, czy_kierownik from auth where login='" + login + "';";
try {
statement = conn.prepareStatement(query);
resultSet = statement.executeQuery(query);
resultSet.first();
if(resultSet.getString("passhash").toString().compareTo(passhash)!= 0){
status |= Serwer.STATUS_NOT_AUTHENTICATED;
pracownik.status |= status;
return pracownik;
}
pracownik.login = login;
pracownik.imie_nazwisko = resultSet.getString("imie_nazwisko");
pracownik.czy_kierownik = resultSet.getBoolean("czy_kierownik");
} catch (SQLException ex) {
pracownik.status |= Pracownik.STATUS_SQL_EXCEPTION;
}
return pracownik;
}
public int polacz() {
int done = STATUS_NO_CONNECTION;
if((status & STATUS_NO_DRIVER) != 0)
return done;
// Connection
try {
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection(url, user, pass);
done = Serwer.STATUS_GOOD;
} catch (java.sql.SQLException ex) {
done |= Serwer.STATUS_SQL_EXCEPTION;
System.out.println("SQLException: " + ex.getMessage());
}
return done;
}
}
As I said, the status of the result of authorise method is 9, which is expected when the driver is not loaded. I also append my workspace contents.
First, I want to start by suggesting that you tried out Android Studio. It's the new more modern IDE developed specifically for the purpose of Android Development.
Secondly, contacting a database on Android is a lot different than for example contacting a DB from Java/C# in an Desktop application.
To contact an online MySQL Database you need a RESTful service (written in PHP for example) that gets the data from the database and sends it over to the application. The service is like a communication point between the App and the Database. The service usually sends data to the application in a human-unfriendly format like JSON, so your app needs to parse that and then display it.

FTPS connection in android

I am new to android, i want to download the files from FTPs server, On emulater i am able to download files but when i try on target board it is giving error at ftp.auth(SSLFTPClient.AUTH_TLS);
Below is the my code, please suggest me where i am wrong.
package com.android.ftp;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import com.enterprisedt.net.ftp.FTPClientInterface;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.ssl.SSLFTPClient;
import com.enterprisedt.util.debug.Level;
import com.enterprisedt.util.debug.Logger;
public class Ftp_testActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String host = "ftp.xyz.com";
String username = "abcd";
String password = "pqr";
String filename = "/mnt/sdcard/video1/747.3gp";
// set up logger so that we get some output
Logger log = Logger.getLogger(Ftp_testActivity.class);
Logger.setLevel(Level.INFO);
SSLFTPClient ftp = null;
try {
// create client
log.info("Creating FTPS (explicit) client");
ftp = new SSLFTPClient();
// disable standard SSL closure
log.info("Setting configuration flags");
ftp.setConfigFlags(SSLFTPClient.ConfigFlags.DISABLE_SSL_CLOSURE);
// set remote host
log.info("Setting remote host");
ftp.setRemoteHost(host);
ftp.setRemotePort(21);
// turn off server validation
log.info("Turning off server validation");
ftp.setValidateServer(false);
// connect to the server
log.info("Connecting to server " + host);
ftp.connect();
// switch to SSL on control channel
log.info("Switching to FTPS (explicit mode)");
ftp.auth(SSLFTPClient.AUTH_TLS);
// log in
log.info("Logging in with username=" + username + " and password="
+ password);
ftp.login(username, password);
log.info("Logged in");
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
putGetDelete(filename, ftp);
log.info("Successfully transferred in ASCII mode");
// Shut down client
log.info("Quitting client");
ftp.quit();
log.info("Example complete");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void putGetDelete(String name, FTPClientInterface ftp)
throws Exception {
ftp.put(name, name);
ftp.get(name + ".copy", name);
ftp.delete(name);
File file = new File(name + ".copy");
file.delete();
}
}
You should try:
ftp.setRemotePort(990);
where 990 is port SSL default.

DNS problems on Android

I had gotten reports from a few users that they couldn't login to our app (which makes HTTP calls to our site) or visit our website in their browser, so I added some code to our latest build to check what IP our host name is resolving to. I've gotten reports from several different users now that they get 127.0.0.1 for our hostname when the app starts, which obviously isn't going to work.
They claim they aren't running any proxy software, and this happens on both 2.1 and 2.2. This also happens on both wifi & 3g, which makes me suspect it is some piece of software on their phone that is interfering with DNS resolution somehow. Does anyone know of any popular software that might do that? Or does anyone have any ideas about how to identify which software might be doing it?
Thanks,
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.TXTRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
public class DNSLookUpActivity extends Activity {
private String url = "https://spectracore.americanlogistics.com/rdac/AdmissionController/CheckMddAdmission";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
funDNS(url);
}
private static void funDNS(String url) {
try {
Lookup lookup = new Lookup(url, Type.ANY);
Record[] records = lookup.run();
if (lookup.getResult() == Lookup.SUCCESSFUL) {
String responseMessage = null;
String listingType = null;
for (int i = 0; i < records.length; i++) {
if (records[i] instanceof TXTRecord) {
TXTRecord txt = (TXTRecord) records[i];
for (Iterator j = txt.getStrings().iterator(); j
.hasNext();) {
responseMessage += (String) j.next();
}
Log.e("TXRecord ", "" + responseMessage);
} else if (records[i] instanceof ARecord) {
listingType = ((ARecord) records[i]).getAddress()
.getHostAddress();
Log.e("ARecord address : ", "" + listingType);
}
}
}
} catch (TextParseException e) {
e.printStackTrace();
}
}
}
Need android ask version 2.3.3 or above
Get their DNS config, and try their DNS servers directly with dig or nslookup. This is not perfect, but it has a good chance of showing you the problem.
dnsjava/org.xbill.DNS is too big for android app, Scott Means's DNSQuery is promiseful:
http://smeans.com/programming/dns-queries-in-java/

Categories

Resources