I have two similar program. the First: Java for PC, the Second: Android. I have a MacOS Pro Server with ip 192.168.0.103 in my local network. MacOS Server has got MySQL-Server 5.0.1, with
CREATE DATABASE db_demo01;
CREATE USER 'user01'#'%' IDENTIFIED BY '1234567';
GRANT ALL ON db_demo01.* TO 'user01'#'%';
My PC App has following code:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.0.103:3306/";
String dbName = "db_demo01";
String userName = "user01";
String userPass = "1234567";
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url+dbName,userName,userPass);
System.out.println("Connected!");
conn.close();
}
catch(Exception ex)
{
System.out.println("Error:" + ex.getMessage());
}
It's work!But when I try to do this with my android app, I'v got connection fail. I don't know why... I posted the full code of my app below:
package com.navi.newser;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
/// VARIABLES
private TextView textWidget;
private TableLayout tableWidget;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CreateOnClickConnect();
}
private void CreateOnClickConnect()
{
textWidget = (TextView)findViewById(R.id.textView1);
tableWidget = (TableLayout)findViewById(R.id.table1);
Button cmd = (Button)this.findViewById(R.id.button3);
cmd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ConnectToMySQL();
}
});
}
private class Connect extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls)
{
String response = "";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.0.103:3306/";
String dbName = "db_demo01";
String userName = "user01";
String userPass = "1234567";
Connection conn = null;
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,userPass);
response += "Connected!";
Log.e("MySQL", response);
conn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
response += "Error:" + ex.getMessage();
Log.e("MySQL", response);
}
publishProgress("Almost...");
return response;
}
#Override
protected void onPostExecute(String result) {
textWidget.setText(result);
}
#Override
protected void onProgressUpdate(String... text) {
textWidget.setText(text[0]);
}
}
public void ConnectToMySQL()
{
new Connect().execute();
}
I use Eclipse Luna.
01-20 19:09:07.777: E/dalvikvm(1069): Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo
I don't have other errors.
The emulator is always isolated from your machine's network, take a look at this Network Address Space
Start your emulator with this
emulator -avd avdname -http-proxy http://192.168.0.1:8080
Here replace avdname to name of avd you want to run your program, and http:192.168.1.1 to your proxy server.
original answer
Well you have to make some settings; first of all with emulator isn't always a good idea to use it, while there is internet connection in the middle. Also the library (jar) for the connector should be in a folder called lib in Android project. For MySQL interaction, I use JSON with PHP. I hope this help you !
Related
I am trying to connect to an Infura node from Java Android application.
I was following these documents to connect to an infura node.
https://kauri.io/managing-storage-in-a-java-application-with-ipfs/3e8494f4f56f48c4bb77f1f925c6d926/a
https://github.com/ipfs-shipyard/java-ipfs-http-client/issues/115
Code:
package com.example.javahttp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import io.ipfs.api.IPFS;
public class MainActivity extends AppCompatActivity {
IPFS ipfs ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void , Void, Void > {
#Override
protected Void doInBackground(Void... voids) {
IPFS ipfs = new IPFS("/dnsaddr/ipfs.infura.io/tcp/5001/https");
try{
System.out.println("connected");
System.out.println("id: "+ ipfs.id());
}catch(Exception e){
System.out.println("not connected"+e);
}
return null;
}
}
}
I am getting this error.
java.lang.RuntimeException: IOException contacting IPFS daemon.
Trailer: null ipfs method not allowed
Any suggestions please.
I don't get why there is such an error but when I used a plain java class to connect with it. It was possible ,you may refer here to my repository blockchain with java to see if you have all the relevant dependencies and you have been doing it properly because I am not familiar with android but I am familiar with web3j.
You can use the below code to connect with an infura node and parse a file to it.
import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class App {
public static void main(String[] args) throws IOException {
IPFS ipfs = new IPFS("/dnsaddr/ipfs.infura.io/tcp/5001/https");
try {
NamedStreamable.InputStreamWrapper is = new NamedStreamable.InputStreamWrapper(new FileInputStream());
MerkleNode response = ipfs.add(is).get(0);
} catch (IOException ex) {
throw new RuntimeException("Error whilst communicating with the IPFS node", ex);
}
}
}
In case anyone has trouble with this nowadays, the fix to this issue was simply to upgrade to the newest version.
I upgraded from v1.2.3 to v1.3.3 and the issue disappeared.
For maven, pom.xml:
<dependency>
<groupId>com.github.ipfs</groupId>
<artifactId>java-ipfs-http-client</artifactId>
<version>v1.3.3</version>
</dependency>
I am currently working on a android app that needs to download everything from an online mySQL database, all of which will then be stored locally using the SQLite built into android.
The problem I am facing at the moment is making the connection from the android device to the server. I have not figured out how to pull information down yet.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.content.ContentValues.TAG;
public class LoginWorker {
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
private static String url_all_users = "http://localhost/get_user_login.php";
private static String TAG_SUCCESS = "success";
private static String TAG_USERS = "users";
private static String TAG_EMAIL = "email";
private static String TAG_PASSWORD = "password";
JSONArray users = null;
public void onCreate(){
System.out.print("Login worker onCreate started");
usersList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<>();
map.put("test","test");
usersList.add(map);
Log.d(TAG, "onCreate: LoadAllUsers Running now");
new LoadAllUsers().execute();
}
class LoadAllUsers extends AsyncTask<String, String, String>{
protected void onPreExecute(){
super.onPreExecute();
}
protected String doInBackground(String... args){
Log.d(TAG, "doInBackground: Start of method");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
users = json.getJSONArray(TAG_USERS);
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
String password = c.getString(TAG_PASSWORD);
String email = c.getString(TAG_EMAIL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EMAIL, email);
map.put(TAG_PASSWORD, password);
usersList.add(map);
}
} else {
Log.d("doInBackground : ", "No user found");
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecution(){}
}
This is an example of some of the code I have been working on (For the user login). Is there a simpler way to make this connection without having to use JSON and PHP? Any help will be greatly appreciated, even if it's just links to useful blogs or tutorials!
Follow these tutorials for connecting to mysql db and creating api which u can be used to retrieve data.
To Connect to db and create api:
https://www.simplifiedcoding.net/php-restful-api-framework-slim-tutorial-1/
https://www.simplifiedcoding.net/create-chat-app-for-android-using-gcm-1/
after creating api you can use retrofit to get data from api.
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
I try to create android login web service with java. I am using Axis2.
I am developing web service with Eclipse EE and android application with Eclipse Adt Bundle. I can access "http://localhost:8081/Login/services/Login?wsdl" page. When android application ran and clicked login button, i am not seeing any message (issued inside web services status="success" or status="login fail")on the screen.
I didn't solve this problem.Any help will be appreciated.
Web Service:
package com.userlogin.ws;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Login {
public String authentication(String userName, String password) {
String retrievedUserName = "";
String retrievedPassword = "";
String status = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/places", "root",
"");
PreparedStatement statement = con
.prepareStatement("SELECT * FROM user WHERE username = '"
+ userName + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
retrievedUserName = result.getString("username");
retrievedPassword = result.getString("password");
}
if (retrievedUserName.equals(userName)
&& retrievedPassword.equals(password)) {
status = "Success!";
}
else {
status = "Login fail!!!";
}
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
}
Android:
package com.androidlogin.ws;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidLoginExampleActivity extends Activity {
private final String NAMESPACE = "http://ws.userlogin.com";
private final String URL = "http://localhost:8081/Login/services/Login?wsdl";
private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
private final String METHOD_NAME = "authentication";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText userName = (EditText) findViewById(R.id.tf_userName);
String user_Name = userName.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
}
catch(Exception e){
}
}
}
You are squashing exceptions in the android code:
catch(Exception e){
}
There's a good chance that that is discarding the evidence that would tell you what the underlying problem is. Either way, squashing Exception like that is very bad practice.
In android code you trying to connect to localhost, but it should a host name where the java service running. In the android device you obviously don't have any service available on port 8081.
This is quite a common mistake. Usually you develop server side and android application on the same machine so when running a service on localhost you believe that the same service should be available in the android application. However, in the emulator, the localhost is the address of the android device. The easiest way to develop and test such applications is to use ip address of the host machine.
Yes, it's that newbie to Vaadin, again. This time, I'm trying to see if I can do one of the most basic of tasks: connect to a database.
We use MS SQL Server here (version 2012, I believe) and we've been able to connect to it fine in two other Java programs that I've written. When attempting to do the same thing using a newly-created Vaadin project, however, I am told that No suitable driver found for jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014. I have checked and made sure that all three .jars from Microsoft are in the build path: sqljdbc.jar, sqljdbc4.jar, and sqljdbc41.jar.
Here's the ConnectionManager class that I've written which only tests whether or not it can get a connection:
package info.chrismcgee.sky.vaadinsqltest.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
public class ConnectionManager {
Logger logger = Logger.getLogger(ConnectionManager.class.getName());
private static final String USERNAME = "web";
private static final String PASSWORD = "web";
private static final String CONN_STRING = "jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014";
public ConnectionManager() throws SQLException, ClassNotFoundException {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
}
}
The result is the SQLException message I mentioned earlier. I've tried it both with and without that Class.forName... line, which is apparently only necessary for Java versions below 7 (and we're using version 8). When that line is enabled, I get a ClassNotFoundException instead.
What gives?
EDIT 04/01/2015: To help clarify how this ConnectionManager class is called, I am simply creating an instance of it from the main class, thusly:
package info.chrismcgee.sky.vaadinsqltest;
import java.sql.SQLException;
import info.chrismcgee.sky.vaadinsqltest.dbutil.ConnectionManager;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("vaadinsqltest")
public class VaadinsqltestUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = VaadinsqltestUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
ConnectionManager connMan = new ConnectionManager();
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.addComponent(new Label("Thank you for clicking"));
}
});
layout.addComponent(button);
}
}
You need your dependencies in your runtime environment.
Please have a look at this answer here at stackoverflow:
https://stackoverflow.com/a/19630339
I've read lots of threads about this issue, and i couldnt see a 'real' solution for it.
I made a java project - which is a rmi server and i have an android application which suppose to be also a rmi client.
When i checked if the server works I wasn't wise enough to test the client on an android project and i made a test client on a simple java project.
Now when i'm trying to connect my android application to server i fail because the android project doesn't recognize the java rmi package.
Why that happen? what should I do?
You can also use the following library LipeRMI
Here is an example of a Android client interacting with Java Server via LipeRMI.
Create the Following 2 classes and a interface for Java application.
//TestService.java
package test.common;
public interface TestService {
public String getResponse(String data);
}
//TestServer.java
import java.io.IOException;
import java.net.Socket;
import test.common.TestService;
import lipermi.exception.LipeRMIException;
import lipermi.handler.CallHandler;
import lipermi.net.IServerListener;
import lipermi.net.Server;
public class TestServer implements TestService {
public TestServer() {
try {
CallHandler callHandler = new CallHandler();
callHandler.registerGlobal(TestService.class, this);
Server server = new Server();
server.bind(7777, callHandler);
server.addServerListener(new IServerListener() {
#Override
public void clientDisconnected(Socket socket) {
System.out.println("Client Disconnected: " + socket.getInetAddress());
}
#Override
public void clientConnected(Socket socket) {
System.out.println("Client Connected: " + socket.getInetAddress());
}
});
System.out.println("Server Listening");
} catch (LipeRMIException | IOException e) {
e.printStackTrace();
}
}
#Override
public String getResponse(String data) {
System.out.println("getResponse called");
return "Your data: " + data;
}
}
//TestMain.java
public class TestMain {
public static void main(String[] args) {
TestServer testServer = new TestServer();
}
}
Android client:
//MainActivity.java
package com.example.lipermidemoandroidclient;
import java.io.IOException;
import test.common.TestService;
import lipermi.handler.CallHandler;
import lipermi.net.Client;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private String serverIP = "192.168.1.231";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGet = (Button) findViewById(R.id.btnGet);
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new Conn().execute();
}
});
}
class Conn extends AsyncTask<Void, Void, MainActivity> {
#Override
protected MainActivity doInBackground(Void... params) {
Looper.prepare();
try {
CallHandler callHandler = new CallHandler();
Client client = new Client(serverIP, 7777, callHandler);
TestService testService = (TestService) client.getGlobal(TestService.class);
String msg = testService.getResponse("qwe");
//Toast.makeText(MainActivity.this, testService.getResponse("abc"), Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
Looper.loop();
return null;
}
}
}
//TestService.java
package test.common;
public interface TestService {
public String getResponse(String data);
}
Add the LipeRMI library to both the projects
Make sure you add INTERNET permission in Android project
Also make sure you have the TestService.java file placed in same package name at both places for eg. test.common package here
Also change value of serverIP variable in Android MainActivity.java to the IP of the machine running the Java code.
I had the same problem and changed my communication to socket communication!
As far as I could figure out Java.rmi unfortunately does not come with Android and therefore it's not possible to use it.
However there are some more disucssions in this post.
Android doesn't support RMI. You should change to socket or raw TCP communication.