i'm new on java and android ,I'm trying to connect an android application to a SQL Server database
i'm using this code:
package com.example.sqlconnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
Button exec;
EditText textbox;
ListView list;
Connection connect;
SimpleAdapter AD;
private void declarer(){
exec=(Button) findViewById(R.id.btn);
textbox=(EditText) findViewById(R.id.textbox);
list=(ListView) findViewById(R.id.list);
}
private void initialiser(){
declarer();
textbox.setText("SELECT * FROM TEST");
connect = CONN("sa", "123456", "android", "192.168.1.1:1433");
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB , String _server){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn=null;
String ConnURL=null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL="jdbc:jtds:sqlserver://"+_server+"/"+"databaseName="+_DB+";user="+_user+";password="+_pass+";";
conn=DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
// TODO: handle exception
Log.e("ERROE",se.getMessage());
}catch (ClassNotFoundException e) {
// TODO: handle exception
Log.e("ERROE",e.getMessage());
}catch (Exception e) {
// TODO: handle exception
Log.e("ERROE",e.getMessage());
}
return conn ;
}
public void QuerySQL(String COMMANDSQL){
ResultSet rs ;
try {
Statement statement=connect.createStatement();
rs=statement.executeQuery(COMMANDSQL);
List<Map<String,String>> data=null;
data=new ArrayList<Map<String,String>>();
while(rs.next()){
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("A", rs.getString("NAME"));
datanum.put("B", rs.getString("CITY"));
data.add(datanum);
}
String[] from={"A","B"};
int[] views={R.id.txt_2,R.id.txt_1};
AD=new SimpleAdapter(this, data, R.layout.modele, from, views);
list.setAdapter(AD);
} catch (Exception e) {
// TODO: handle exception
Log.e("ERROR",e.getMessage());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialiser();
exec.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
QuerySQL(textbox.getText().toString());
}
} );
}
}
i also added the autorisations :
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
but when running i have this error:
Network error IOException : failed to connect to/192.168.1.1(port 1433): connect failed: ETIMEDOUT Connection timed out)
Don't pass Port Name ... I think it till work
use
connect = CONN("sa", "123456", "android", "192.168.1.1");
instead of
connect = CONN("sa", "123456", "android", "192.168.1.1:1433");
Related
package com.example.workdb;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.Bundle;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.sourceforge.jtds.jdbc.*;
public class MainActivity extends AppCompatActivity {
public Button run;
public TextView message;
public TextView txtvw;
public Connection con;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
run= (Button) findViewById(R.id.button);
run.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
CheckLogin checkLogin= new CheckLogin();
checkLogin.execute("");
Log.d("CREATION","ON CREATE WORKS");
// Log.d("txtvw", connection);
//System.out.println("Yes");
// txtvw.setText("hello");
}
});
} public class CheckLogin extends AsyncTask<String,String,String>
{
String z="";
Boolean IsSuccess= false;
String name1="";
// Log.d("txtvw","step 1 done");
protected void onPostExecute(String r){
if (IsSuccess){
message=(TextView)findViewById(R.id.textView);
message.setText(name1);
Log.d("TAG", "STEP 1 DONE");
}
}
#Override
protected String doInBackground(String... strings) {
try
{
Connection con = connectionClass();
if(con==null){
z="Check interent";
//Log.d("txtvw", z);
}
else
{
String query= "select * from Value";
Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(query);
if (rs.next())
{
name1=rs.getString("KneeAngle");
Log.d("MYTAG", "name 1 works");
z="Query success";
IsSuccess=true;
con.close();
}
else{
z="Invalid query";
IsSuccess=false;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return z;
}
}
public Connection connectionClass(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL ;
try{
Class.forName("net.sourceforge.jtds.jdbs.Driver");
ConnectionURL="jdbc:jtds:sqlserver://havvasemserv3.database.windows.net:1433;DatbaseName=Newfin;user=;password=;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
connection= DriverManager.getConnection(ConnectionURL);
} catch(ClassNotFoundException e){
Log.e("Error here 2 ",e.getMessage());
}
catch (Exception e) {
Log.e("error here 3:",e.getMessage());
}
//Log.d("txtvw", connection);
return connection;
}
}
I am trying to connect azure sql database to android studio. I have added all the permissions in the manifest file and I have also added a jtds module 1.3.1 in the project and implemented it in the gradle module app. My code exits with 0 errors but data is not displayed on the emulator. Expected output is the first value from my database which is "8".
Thanks.,
Add this at the end of you current connection url after timeout=30
;ssl=request
Also make sure in your firewall settings of your azure server!/database your current device ip is allowed to access as by default all access is blocked,
To allow all devices to access server go to the firewall settings and in the insert ip section add this ip range
0,0,0,0 and 255,255,255,255
I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");
I'm trying to pull all the data from a table using SELECT * from book, but I'm getting:
Attempt to invoke interface method 'java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String)' on a null object reference
I got it working when triggering the SQL statement in Eclipse. I'm trying to recreate it in Android Studio, but seems to throw this issue. Any help is appreciated.
SQL.java
package com.example.andy.loginapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Created by Andy on 1/4/2017.
*/
public class SQL {
private Statement st;
private Connection con;
private ResultSet rs;
public SQL(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sqltest", "root", "");
st = con.createStatement();
}
catch(Exception e){
System.out.println(e);
}
}
public void getData(){
try{
String query = "SELECT * from book";
String queryInsert = "INSERT into Book " + "VALUE(authorField.getText(), titleField.getText(), yearField.getText())";
rs = st.executeQuery(query);
while(rs.next()){
String author = rs.getString("author");
String title = rs.getString("title");
System.out.println("Author: " + author + " " + "Title" + " " + title);
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("success");
}
}
MainActivity.java
package com.example.andy.loginapp;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private Statement st;
private Connection con;
private ResultSet rs;
TextView hi;
RelativeLayout background;
Button sqlButton;
SQL data = new SQL();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlButton = (Button) findViewById(R.id.sqlButton);
sqlButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
data.getData();
}
});
}
}
You would have to write a webservice to connect to any external databases such as MYSQL to connect android application to a database. It also involves writing a very basic PHP script.
See the following link for some examples.
https://www.b4x.com/android/forum/threads/connect-android-to-mysql-database-tutorial.8339/
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
So you're better off using SQLLite unless its absolutely necessary.
package com.efas.admin.efasrestaurant;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LoginPage extends AppCompatActivity {
EditText Username;
EditText Password;
Button button1;
Button button2;
Connection connect;
SimpleAdapter AD;
private Connection CONN(String _user , String _pass , String _DB , String _server){
StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection Conn=null;
String connString;
try{
connect = CONN("sa", "123456789", "EFAS", "192.168.0.101");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connString = "jdbc:jtds:sqlserver://server_ip_address :192.168.0.101/EFAS;encrypt=fasle;user=sa;password=123456789;instance=BLAZE;";
Conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
Statement stmt = connect.createStatement();
stmt.executeQuery("select * from UserName");
Statement stmt1 = Conn.createStatement();
stmt1.executeQuery("select * from UserPassword");
}catch (SQLException se){
Log.e("ERROR",se.getMessage());
}catch (ClassNotFoundException e){
Log.e("ERROR",e.getMessage());
}catch (Exception e){
Log.e("ERROR",e.getMessage());
}
return CONN(_user, _pass, _DB, _server);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
Username=(EditText)findViewById(R.id.edit_text1);
Password=(EditText)findViewById(R.id.edit_text2);
button1=(Button)findViewById(R.id.btn1);
button2=(Button)findViewById(R.id.btn2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Username.getText().toString().equals("stmt")&&
Password.getText().toString().equals("stmt1")) {
Toast.makeText(LoginPage.this, "Username and Password is correct", Toast.LENGTH_SHORT).show();
EditText editText = (EditText) findViewById(R.id.edit_text1);
Intent i = new Intent(getApplicationContext(), TableLists.class);
i.putExtra("text", editText.getText().toString());
startActivity(i);
} else
{Toast.makeText(LoginPage.this,"Please Enter a Valid Username and Password ",Toast.LENGTH_SHORT).show();
Toast.makeText(LoginPage.this,"And Try Again",Toast.LENGTH_SHORT).show();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),EFAS.class);
startActivity(i);
}
});
public String getMacAddress(Context context){
WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wifiManager.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Device don't have mac address or wi-fi is disabled";
}
return macAddress;
}
}
when i enter username as stmt and password as stmt1 then the next activity starts but it is supposed to take username and password input from the database
and it is not happining when i enter the username and password of the database it goes to else condition how can i fix this ???
try
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskWrites().penaltyLog().build());
i cant send data from andorid device to url
please help me !
this is my class
what is problem of my code ?
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.AsyncTask;
public class loginserver extends AsyncTask{
private String Link="";
private String User="";
private String Pass="";
public loginserver(String link,String user,String pass){
Link=link;
User=user;
Pass=pass;
}
#Override
protected String doInBackground(Object... arg0) {
try{
String data=URLEncoder.encode("username","UTF8")+"="+URLEncoder.encode(User,"UTF8");
data+="&"+URLEncoder.encode("password","UTF8")+"="+URLEncoder.encode(Pass,"UTF8");
URL mylink=new URL(Link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) !=null){
sb.append(line);
}
Main.res = sb.toString();
}catch(Exception e){
}
return "";
}
}
and this is my main code
problem in class code or main code?
package com.example.test;
import java.util.Timer;
import java.util.TimerTask;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebStorage.Origin;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
public static String res="";
private EditText usertext,passtext;
private Button login,register,exit;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
usertext =(EditText) findViewById(R.id.usertext);
passtext =(EditText) findViewById(R.id.passtext);
login =(Button) findViewById(R.id.login);
exit =(Button) findViewById(R.id.exit);
register =(Button) findViewById(R.id.register);
login.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
login(usertext.getText().toString(),passtext.getText().toString());
}
});
}
private void login (String user,String pass ){
new loginserver("my address",user,pass ).execute();
final ProgressDialog pd = new ProgressDialog(Main.this);
pd.setMessage("please wait");
pd.show();
final Timer tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask(){
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(res.equals("")){
pd.cancel();
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
tm.cancel();
}
}
});
}
},1, 1000);
}
}
the php code work true - but i cant send data from android device
is ther any body know my mistakes ?
at first you have to setup the internet permissions in the manifest.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
It would also be helpful if you check at first if the network is available.
private boolean networkIsAvailable(Context con) {
ConnectivityManager cm = (ConnectivityManager)
con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
After that, you have to work with the HttpClient.
Check this post how to do this:
Android HTTP-POST