Android App unable to access Azure database - android

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

Related

mysql driver class not found exception

I'm trying to use MySQL while learning Android, but this class not found exception occurs. I have imported the MySQL connecter jar file into my project, and I have set it up. I googled about the problem but only got a tomcat solution of the same problem but I still don't know how to solve this in Android.
private class GetData extends AsyncTask<String,String,String> {
String msg = "";
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://"+
DBStrings.DATABASE_URL +"/"+
DBStrings.DATABASE_NAME;
#Override
protected void onPreExecute(){
progressTextView.setText("Connecting to database");
}
#Override
protected String doInBackground(String... strings) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,DBStrings.USERNAME,DBStrings.PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT * FROM medicine";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
Integer ID = rs.getInt("ID");
String name = rs.getString("Name");
Integer date = rs.getInt("Date");
medID.add(ID);
names.add(name);
medDate.add(date);
}
msg = "complete!";
rs.close();
stmt.close();
conn.close();
}catch (SQLException connERROR)
{
msg = "An exception was thrown for JDBC";
connERROR.printStackTrace();
}catch (ClassNotFoundException classERROR)
{
msg = "Class not found exception";
classERROR.printStackTrace();
}finally {
}
return null;
}
}
Don't use JDBC from an android device, just use J2EE servlets (simplest solution if you want to code in JAVA), and call these servlet from android through HTTP (you can use Retrofit Library to make these calls https://square.github.io/retrofit).

Android storing data locally for offline access

In my project, there is a scenario where i am getting Json data as response when the device is in online. I need the same data when the device is offline.
I have tried saving the data into Default SharedPreference file using
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("contactobject", result.toString()).apply();
And retrieving the data from SharedPreference file like using
String result = PreferenceManager.getDefaultSharedPreferences(context).getString("contactobject", "");
The thing is, by using SharedPreference, the usage of memory is high.
Question : Is there any other better way to save the data in Cache memory as like WebView for better performance.
Just write the JSON to your cache dir. Read it from your cache file if you're offline and update your cache when you're online. You don't need a database for simple JSON. Seriously.
The Sharedpreferences use key values.That might be create a problem some time. So store the data in database and retrieve it when user is offline.
UPDATE
you can use database for retrieving records like this
aQuery.progress(progressDialog).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
if (object != null) {
//delete old records
db.execSQL("delete from entrys");
String quotos = object.optString("quote_data");
String msg = object.optString("msg");
// Toast.makeText(getApplicationContext(),msg+" and "+quotos,Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = new JSONArray(quotos);
al = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String str = jsonObject.getString("quote");
al.add(str);
//add the data in database
ContentValues cv = new ContentValues();
cv.put("name",str);
db.insert("entrys",null,cv);
Log.d("STR,","Created"+str);
}
ArrayAdapter<String> adpt = new ArrayAdapter<String>(Wishes.this, R.layout.single_row, R.id.tv_wishdata, al);
lv.setAdapter(adpt);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Server is busy Reciving data..", Toast.LENGTH_LONG).show();
}
} else {
//show the data when user is offline
SimpleCursorAdapter sd = new SimpleCursorAdapter(getApplicationContext(), R.layout.single_row,c, new String[]{"name"}, new int[]{R.id.tv_wishdata});
lv.setAdapter(sd);
Toast.makeText(getApplicationContext(), "Please Check Internet connection", Toast.LENGTH_LONG).show();
}
}
});
Option 2 You can also use cache files for retrieve data.
First of all create a function for save data in cachefile.
public void saveMyData()
{
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+"cachefile.txt"));
out.writeObject(al.toString());
Toast.makeText(getApplicationContext(), "Data Saved..",Toast.LENGTH_LONG).show();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then after retrieve data whenever you what to show data from file.
private String retriveMyData()
{
String fileContent = "";
try {
String currentLine;
BufferedReader bufferedReader;
FileInputStream fileInputStream = new FileInputStream(getFilesDir()+"cachefile.txt");
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream,"UTF-8"));
while ((currentLine = bufferedReader.readLine()) != null) {
fileContent += currentLine + '\n';
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("FAILED","THOS IS NULL");
fileContent = null;
}
Log.d("SUCESS","SUCESS BUDDYY"+fileContent);
Toast.makeText(getApplicationContext(),fileContent+"",Toast.LENGTH_SHORT).show();
return fileContent;
}

how to insert dynamic values in sql server via android

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 can not get nickName from users that currently added

i am new in asmack. i am writing a chat application and when i add a user by send him/her a subscription packet an he accept, i check openFire server nikename and other properties is ok for new user and mode is both.
but when i try to get friends data nickname is empty.
if i debug the code nickname receive correctly but in run mode can not?
code to receive friends :
public static void getContacts(final Context ctx)
{
try
{
try
{
Thread.sleep(1000);
}
catch(Exception ex)
{
}
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
if(globalVars.friends == null)
globalVars.friends = new ArrayList<globalVars.UserList>();
globalVars.friends.clear();
for(RosterEntry entry: entries)
{
String user = entry.getUser();
String username = user.split("#")[0];
Presence presence = roster.getPresence(entry.getUser());
int status = R.drawable.offline;
if(presence.getType().equals(Presence.Type.available))
status = R.drawable.online;
//String fromto = presence.getFrom() + " "+presence.getTo();
globalVars.UserList ul = new UserList(username, status, globalVars.smallImageAddress(ctx, username));
String wathsUp = "";
try
{
if(presence.getStatus() != null)
wathsUp = presence.getStatus();
}
catch(Exception ex)
{
}
ul.setComment(wathsUp);
ul.setFriend(true);
ul.setNikName(entry.getName());
globalVars.friends.add(ul);
}
can anyone help me?
Use vCard for setting nickname or other details of a user.
Use this code for getting Vcard information from a jid
VCard mVCard = new VCard();
mVCard.load(your xmppconnection,user jid);
String name = mVCard.getNickName();
Just an update on this matter: VCard load() method is now deprecated.
Instead you can use this method:
/**
* retrieves an user VCard
*
* #param userJid the user jid
* #return the VCard object
*/
public VCard getVCard(String userJid) {
VCard vCard = null;
VCardManager vCardManager = VCardManager.getInstanceFor(connection);
boolean isSupported;
try {
//remove resource name if necessary
if (!TextUtils.isEmpty(userJid) && userJid.contains("/")) {
userJid = userJid.split("/")[0];
}
isSupported = vCardManager.isSupported(userJid);
if (isSupported) // return true
vCard = vCardManager.loadVCard(userJid);
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (IllegalArgumentException iAE) {
iAE.printStackTrace();
}
return vCard;
}
As you can see, the method checks if the user understands the vCard-XML format and exchange. If it does, it returns the VCard.
Then just retrieve the user nickname from VCard.

Connecting to MySQL from Android with JDBC

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

Categories

Resources