I used the following code to connect MySQL in localhost from Android. It only displays the actions given in catch section . I do not know whether it is a connection problem or not.
package com.test1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test1Activity extends Activity {
/** Called when the activity is first created. */
String str="new";
static ResultSet rs;
static PreparedStatement st;
static Connection con;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv=(TextView)findViewById(R.id.user);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://10.0.2.2:8080/example","root","");
st=con.prepareStatement("select * from country where id=1");
rs=st.executeQuery();
while(rs.next())
{
str=rs.getString(2);
}
tv.setText(str);
setContentView(tv);
}
catch(Exception e)
{
tv.setText(str);
}
}
}
When this code executes it displays "new" in the avd.
java.lang.management.ManagementFactory.getThreadMXBean, referenced from method com.mysql.jdbc.MysqlIO.appendDeadlockStatusInformation
Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo
Could not find method javax.naming.Reference.get, referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.initializeFrom
Can anyone suggest some solution? And thanks in advance
You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver
See
http://www.helloandroid.com/tutorials/connecting-mysql-database
http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html
Android cannot connect directly to the database server. Therefore we
need to create a simple web service that will pass the requests to the
database and will return the response.
http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html
For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.
this code runs permanently!!! created by diko(Turkey)
public void mysql() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
if (con == null) {
try {
con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();
}
}
}
});
if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();
thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
if (con != null) {
try {
// con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
Statement st = con.createStatement();
String ali = "'fff'";
st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
// ResultSet rs = st.executeQuery("select * from deneme");
// ResultSetMetaData rsmd = rs.getMetaData();
// String result = new String();
// while (rs.next()) {
// result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
// result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
// }
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ .Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.
Do you want to keep your database on mobile? Use sqlite instead of mysql.
If the idea is to keep database on server and access from mobile. Use a webservice to fetch/ modify data.
An other approach is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the MySql JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".
try changing in the gradle file the targetSdkVersion to 8
targetSdkVersion 8
public void testDB() {
TextView tv = (TextView) this.findViewById(R.id.tv_data);
try {
Class.forName("com.mysql.jdbc.Driver");
// perfect
// localhost
/*
* Connection con = DriverManager .getConnection(
* "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
* );
*/
// online testing
Connection con = DriverManager
.getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tablename ");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";
}
tv.setText(result);
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}
Related
My android application is supposed to get data from an Azure SQL database, but the queries keep responding with
Reference to database and/or server name is not supported in this
version of SQL Server
On the server side audit log it just states
Reference to database and/or server name in 'delivery.dbo.upload' is
not supported in this version of SQL Server
Code:
public class CheckDeliveries extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
private ArrayList<ModelU> arrayList;
//#Override
protected void onPostExecute(String r) {
if (z == "ok") {
GetDeliveries adapter = new GetDeliveries(ViewUpcoming.this, arrayList);
mRecyclerView.setAdapter(adapter);
}
Context context = getApplicationContext();
CharSequence text = "2 " + z;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
protected String doInBackground(String... strings)
{
try
{
con = connectionclass();
if (con == null)
{
z = "Internet Issue";
}
else
{
String query = "SELECT * FROM [delivery].[dbo].[upload]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
z = "ok";
if(rs.next()) {
do {
#SuppressLint("Range") ModelU modelu = new ModelU(
"" + rs.getInt(rs.getInt("ID")),
"" + rs.getString(rs.getInt("Name")),
"" + rs.getString(rs.getInt("Address")),
"" + rs.getString(rs.getInt("Status"))
);
arrayList.add(modelu);
}
while (rs.next());
}
else {
z = "Invalid Query";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://2033051.database.windows.net:1433;database=delivery;user=XXXXXXXX;password=XXXXXXXX;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;ssl=request;loginTimeout=30;";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error 1", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error 2", e.getMessage());
}
catch (Exception e)
{
Log.e("error 3", e.getMessage());
}
return connection;
}
}
Toastbox output
Azure database
Any help is greatly appreciated!
This error occurs because Azure does not allow to alter the master database. To resolve this, you need to connect directly to the Azure database you are going to use.
Delete the SQL Azure linked server that we created and create a new one.
Under the Server type section of the General tab, choose the Other data source radio button. The name for the linked server in the Linked server text box can be, this time, whatever you like (e.g. AZURE SQL DATABASE). Under the Provider drop down box, choose the Microsoft OLE DB Provider SQL Server item. In the Data source text box, enter the name of the SQL Azure (e.g. server.database.windows.net). The most important setting in order to correctly create a linked server to an Azure SQL database is to enter the name in the Catalog text box (e.g. TestDatabase) of an Azure SQL database for which you want to create a linked server to an Azure SQL database. Otherwise, if this field is left empty, we will encounter the same 40515 error when trying to get a list of the tables under the Catalogs folder.
Refer this article by Marko Zivkovic
This is more of an efficiency question: When performing JDBC in an Android application, should I use preparecall or createstatement with a stored procedure? Here is an example of a method in my code which calls a stored procedure and works:
public static ResultSet getUserNames (String userid) {
ResultSet rs = null;
try {
cstmt = con.prepareCall("{call dbo.StoredProcedure(?)}");
cstmt.setString("#ID", userid);
cstmt.setQueryTimeout(10);
rs = cstmt.executeQuery();
return rs;
} catch (Exception e) {
Log.e("DB Error:", e.getMessage());
return null;
}
}
Hi I'm new to Signalr and I want to develop android native client application for communicate with signalr server. So I follow "whathecode" article and still i'm not able to connect to server. Anyone can give me some sample project or example.Its big help for me. Thank you.
public void connect(){
HubConnection con = new HubConnection(Uri.parse("http://10.0.2.2:3227/").toString());
HubProxy hub = con.createHubProxy("MyHub1");
con.start();
try {
hub.invoke( "Send", "user", "Hello world!" ).get();
} catch (InterruptedException e) {
// Handle ...
} catch (ExecutionException e) {
// Handle ...
}
}
I face same issue like you but it resolved by adding 3227 part to allow all connection from it in my windows firewall settings .
I also suggest instead of creating localhost use some ip and create SignalR server, after that it should work fine.
private void createConnections() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "http://192.168.0.63/SignalRServerApp/signalr";
final HubConnection connection = new HubConnection(host, false);
final HubProxy hp = connection.createHubProxy("MyHubController");
Toast.makeText(getActivity(), SampleWork.getStringData(), Toast.LENGTH_LONG).show();
System.out.println(SampleWork.getStringData());
SignalRFuture<Void> awaitConnection = connection.start();
try {
EditText text = (EditText) getActivity()
.findViewById(R.id.text);
String data = text.getText().toString();
awaitConnection.get();
try {
hp.invoke("ReceiveData", data);
} catch (Exception e) {
System.out.println("Error");
}
//Calling a server method named "Acknowledge"
hp.on("Acknowledge", new SubscriptionHandler1<String>() {
#Override
public void run(final String p1) {
//Here u gets the response from server
}
}, String.class);
System.out.println("Test");
} catch (Exception e) {
e.printStackTrace();
}
}`enter code here`
public void query2(View V)
{
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://10.0.2.2:1433/demo;integratedSecurity=true;user=usd;password=dell#123;";
conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
// Statement stmt = conn.createStatement();
PreparedStatement ps;
ps=conn.prepareStatement("insert into UserMaster1 values(?,?)");
//int x=stmt.executeUpdate("insert into UserMaster1 values( 'usaid','mansoori')");
ps.setString(1,un);
ps.setString(2,pwd);
Log.d("exupdt","insertion done");
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
ps.executeUpdate();
Log.d("PreparedStmt","Success");
conn.close();
}
catch (Exception e)
{
Log.w("Error connection","" + e.getMessage()); }
}
}
i am inserting data in sql server by using the interface PreparedStatement by android to sql server but only a blank row inserted not the data how can i insert dynamic values
You cannot directly access your remote database.
You have to write web-service on server side and then send request from your android application to this service.
You can use this tutorial for example of implementing such program.
public class MainActivity extends Activity {
private TextView t1,t2,t3;
private Button b1;
private EditText e1,e2;
String un,pwd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.tv1);
t2=(TextView)findViewById(R.id.tv2);
t3=(TextView)findViewById(R.id.tv3);
b1=(Button)findViewById(R.id.btn);
e1=(EditText)findViewById(R.id.ed1);
e2=(EditText)findViewById(R.id.ed2);
if (android.os.Build.VERSION.SDK_INT> 9){
StrictMode.ThreadPolicy policy =new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public void query2(View V)
{
un =e1.getText().toString();
pwd =e2.getText().toString();
if(un.equals("")||pwd.equals(""))
Toast.makeText(this,"Above Fields cannot be left blank",Toast.LENGTH_LONG).show();
else
{
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://172.22.0.2:1433/Samay;integratedSecurity=true;user=DBSQL;password=samay#123;";
conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
PreparedStatement ps;
ps=conn.prepareStatement("insert into UserMaster1 values(?,?)");
ps.setString(1,un);
ps.setString(2,pwd);
int x;
x=ps.executeUpdate();
Log.d("exupdt",un);
Log.d("exupdt",pwd);
Toast.makeText(this, "Success"+x, Toast.LENGTH_LONG).show();
Log.d("PreparedStmt","Success");
conn.close();
}
catch (Exception e)
{
Log.w("Error connection","" + e.getMessage()); }
}
}
}
My best friend solve this typical problem very logically i don't understand why you people don't give the exact answer instead of successions
my best friend name is s.(java queen) she simply solve this problem by giving
un =e1.getText().toString();
pwd =e2.getText().toString();
this code after the method query2 and program gives the exact result what i wanted ..i got dynamic insertion android to sql server...
I am trying to call AsyncTask from a loop.It is working properly but the issue is it taking quite more time to execute all the request.Please suggest me how could i make it more fast .
for (int i = 0; i < 6; i++) {
response = requestWeatherUpdate(location);
}
requestWeatherUpdate
private WeatherResponse requestWeatherUpdate(String location) {
url = ""+ location;
Log.d("URL for Weather Upadate", url);
WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask();
String weatherRequestResponse = "";
try {
weatherRequestResponse = weatherReq.execute(url).get();
if (weatherRequestResponse != "") {
parsedWeatherResponse = ParseWeatherResponseXML
.parseMyTripXML(weatherRequestResponse);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return parsedWeatherResponse;
}
Used CallBack
public class WeatherUpdateAsyncTask extends AsyncTask<String, Void, String> {
Context context;
CallBack callBack;
public WeatherUpdateAsyncTask(CallBack callBack) {
this.callBack = callBack;
}
#Override
protected String doInBackground(String... arg0) {
String responseString = "";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(arg0[0]);
client.getParams().setParameter("http.socket.timeout", 6000);
client.getParams().setParameter("http.connection.timeout", 6000);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString.trim());
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
client.getConnectionManager().shutdown();
return responseString.trim();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
callBack.run(result);
}
}
requestWeatherUpdate
private WeatherResponse requestWeatherUpdate(String location) {
url = ""
+ location;
Log.d("URL for Weather Upadate", url);
WeatherUpdateAsyncTask weatherReq = new WeatherUpdateAsyncTask(new CallBack() {
#Override
public void run(Object result) {
try {
String AppResponse = (String) result;
response = ParseWeatherResponseXML
.parseMyTripXML(AppResponse);
} catch (Exception e) {
Log.e("TAG Exception Occured",
"Exception is " + e.getMessage());
}
}
});
weatherReq.execute(url);
return response;
}
Frm here i calling
for (int i = 0; i < 4; i++) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.sector_details, depart_arrivals_details, false);
depart_time = (TextView)layout.findViewById(R.id.depart_time);
depart_airport_city = (TextView)layout.findViewById(R.id.depart_airport_city);
temprature = (TextView)layout.findViewById(R.id.temprature);
humidity = (TextView)layout.findViewById(R.id.humidity);
flight_depart_image = (ImageView)layout.findViewById(R.id.flight_depart_image);
depart_time.setText("20:45");
depart_airport_city.setText("Mumbai");
/*
* This part will be updated when we will se the request and get the response
* then we have to set the temp and humidity for each city that we have recived
* */
temprature.setText("");//Here i have set the values from the response i recived from the AsynkTask
humidity.setText("");//Here i have set the values from the response i recived from the AsynkTask
flight_depart_image.setImageResource(R.drawable.f1);
depart_arrivals_details.addView(layout, i);
}
Calling get() on an AsyncTask blocks the calling thread. Don't do that. Instead pass the results to the caller in onPostExecute().
Starting with Honeycomb, the default implementation executes asynctasks sequentially on a serial executor. To run asynctasks parallely, use executeOnExecutor(THREAD_POOL_EXECUTOR, ...) instead of execute(...).
You should not use get() . Calling get() does not make the call asynchronous. Instead use execute
weatherRequestResponse = weatherReq.execute(url).get();
get()
public final Result get ()
Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.
Returns
The computed result.
Throws
CancellationException If the computation was cancelled.
ExecutionException If the computation threw an exception.
InterruptedException If the current thread was interrupted while waiting.
For parallel execution use executeOnExecutor
weatherReq.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
If your asynctask is an inner class of your activity class you can update ui in onPostExecute. If its not you can use a interface as a callback.
Retrieving a returned string from AsyncTask in Android
How do I return a boolean from AsyncTask?
From the discussion you get NUllPointerException # temprature.setText(parsedWeatherResponse.getTempInC()+(char) 0x00B0);
You have not initialized parsedWeatherResponse. You have only declared it
parsedWeatherResponse = new WeatherResponse();
use executeOnExecutor(THREAD_POOL_EXECUTOR, ...) to run asynctasks parallely. also you can use HttpURLConnection instead of DefaultHttpClient/HttpGet
If you want to connect with network from UI thread , it is quitly difficult. "The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness."
If you want to overcome this difficulty then following bellow instruction:
The solution is given below. I found it from another answer. It is working for me. And below import statement into your java file.
import android.os.StrictMode;
Write below code into onCreate
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}