i'm trying to connect to SQL Server Database from android studio
i'm using jtds and already import "jtds-1.3.1.jar" module to android studio
in the import part below line i got error
import net.sourceforge.jtds.jdbc.*;
and the error is:
"error: package net.sourceforge.jtds.jdbc does not exist"
. i don't know what i miss.
package com.example.mycar4;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
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 net.sourceforge.jtds.jdbc.*;
public class database extends AppCompatActivity {
// Declaring layout button, edit texts
Button login;
EditText username,password;
ProgressBar progressBar;
// End Declaring layout button, edit texts
// Declaring connection variables
Connection con;
String un,pass,db,ip;
String usernam,passwordd;
//End Declaring connection variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
// Getting values from button, texts and progress bar
login = (Button) findViewById(R.id.btn_Login);
username = (EditText) findViewById(R.id.et_username);
password = (EditText) findViewById(R.id.et_password);
progressBar = (ProgressBar) findViewById(R.id.pbbar);
progressBar.setVisibility(View.GONE);
// End Getting values from button, texts and progress bar
// Declaring Server ip, username, database name and password
ip = "***";
db = "***";
un = "***";
pass = "***";
// Declaring Server ip, username, database name and password
// Setting up the function when button login is clicked
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
usernam = username.getText().toString();
passwordd = password.getText().toString();
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute("");
}
});
//End Setting up the function when button login is clicked
}
public class CheckLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
progressBar.setVisibility(View.GONE);
Toast.makeText(database.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(database.this , "Login Successfull" , Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... params)
{
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
String query = "select * from login where username= '" + usernam.toString() + "' and password = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
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").newInstance();
ConnectionURL = "jdbc:jtds:sqlserver://sql5009.mywindowshosting.com;database=DB_A2C00B_login;user=DB_A2C00B_login_admin;password=login#123";
// ConnectionURL =
"jdbc:jtds:sqlserver://192.168.1.9;database=msss;instance=SQLEXPRESS;Network
Protocol=NamedPipes" ;
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
To connect an Android App with a SQL server, you'll need to set up a web (Http) server in between the two. You can build this web server in any language you're familiar with be it java (J2EE) or php etc.
This web server will be hosted with your SQL server and will take Http requests from the Android app, process it, forward the request as queries to your SQL server and then return it back to your app as REST/JSON (the current format of sending data over the web) or SOAP/XML (the old way of sending data over the web).
App >> Web Server >> Database Server
The web server should be RESTful and the app can interact with it via Http requests via the library Retrofit2.
Here's some resources to get you started;
Retrofit by Square.
Retrofit Github repository.
Simple CRUD example with Java RESTful Web Service, a brief tutorial.
RESTful Web Services: A Tutorial Android + Java Web Services
if you are using android studio or eclipse you should put the jtds jar file in the correct location
it is in the libs (library) folder inside app n your project. Once you put it in the libs > right click then add library.
another note you should use 1.2.7 or lower which is much supported
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
When ever I click on the login button it always shows me check ur internet toast I don't know why I have also turned off my firewall also please help
I have also passed the internet permission also in the manifest .
Can someone also share the link from where I can learn how to pass values in android from sql server
thanks in advance !
MainActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity
{
// Declaring layout button, edit texts
Button login;
EditText username,password;
ProgressBar progressBar;
// End Declaring layout button, edit texts
// Declaring connection variables
Connection con;
String un,pass,db,ip;
//End Declaring connection variables
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting values from button, texts and progress bar
login = (Button) findViewById(R.id.button);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
// End Getting values from button, texts and progress bar
// Declaring Server ip, username, database name and password
ip = "LAPTOP-KOS272HK";
db = "fmv";
un = "username";
pass = "password";
// Declaring Server ip, username, database name and password
// Setting up the function when button login is clicked
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute("");
}
});
//End Setting up the function when button login is clicked
}
public class CheckLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... params)
{
String usernam = username.getText().toString();
String passwordd = password.getText().toString();
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
// Change below query according to your own database.
String query = "select * from login where user_name= '" + usernam.toString() + "' and pass_word = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
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://" + server + database + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tanis.logi">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
i am currently developping an application for my third year project, it's an android app (i used android studio) that will access a database that i created on my wamp server, the connection works perfectly from the application when i debug it on my android phone( i used in my code the "HttpURLConnection" with the url being my pc ip adress that i got from (cmd/ipconfig) ) .
The problem is that once i disconnect my phone from my pc and try to run the application from the phone, the connection with the database won't work, and also if i connect my pc to another modem, my pc ip changes, which is pretty much normal, but i don't think supposed to change the ip everytime the modem i connect to change ( although i'm not really sure, server connexions are clearly not something i'm an expert at ) , so i tried to use the ip of my pc on the internet that i got from "ipaddress.com" but it won't work, not even if i debug the application directly from android studio,
i don't have much time left to present the application , so i need a quick answer, thank you in advance
P.S : i guess i gotta mention that i need to acces the database to read AND write on it from the phone since it's an app that permits login/registration and will get the data that the user will enter and store it in the database .
I don't know wheter understanded, when you disconnect your phone from your pc, the app dead? or simplely it don't connect with db. Regard router, you need an account in "no-ip" and configure forguard's router on port 80 to redirect your computer's static IP. i need more details and information to help you. Regards
Try to connect the Phone and Mobile in same network.
your connection Url would be Like this 192.10.20.2 which is your ip or computer. as your get it form cmd using ipconfig command.
but whenever your networks changes your have to decompile to change the ip. or provide ip via textview.
take a Editview to take ip. and the concat it to your url. this will work. as it worked for me.
i'm working on an external server
The php code (for the connection to the db)
<?php
$db_name="pfe";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
?>
then i got another php file which handles the login part
<?php
require "connexion.php";
$user_email =$_POST["user-email"];
$user_pass =$_POST["password"];
$mysql_qry = "select id from donateur where email like '$user_email' and
password like '$user_pass'";
$result = mysqli_query($conn , $mysql_qry);
if(($row=mysqli_fetch_assoc($result))!=null){
$a = array('myarray' => array("donateur", $row["id"]));
echo json_encode($a);}
else {
$mysql_qry2 = "select id, username from association where email like
'$user_email' and password like '$user_pass'";
$result2 = mysqli_query($conn , $mysql_qry2);
if(($row=mysqli_fetch_assoc($result2))!=null) { $a = array('myarray' =>
array("association", $row["id"]));
echo json_encode($a);
}
else { echo "rien";}}
$conn->close();
the java code :
package applis.pfe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.Manifest.permission.READ_CONTACTS;
public class LoginActivity extends AppCompatActivity implements
LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
DonateurDAO donateurdao= new DonateurDAO(this);
AssociationDAO associationdao=new AssociationDAO(this);
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
String ip="http://105.101.179.155/";
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
public static String qui;
public static int id;
public static String username;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
///////////////////// POUR AFFICHER LE MESSAGE DIINSCRIPTION REUSSIE /////////////////////////////////////
if(getIntent().getStringExtra("inscription")!=null &&
getIntent().getStringExtra("inscription").equals("oui"))
{ AlertDialog a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Inscription réussie !");
a.setMessage("Votre inscription a été validé, veuillez vous connecter
pour pouvoir continuer");
a.show();}
session = new SessionManager(this);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
// populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new
TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent
keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
ImageButton btn;
btn =(ImageButton)findViewById(R.id.InscriptionDonateurButton);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {Intent in= new
Intent(LoginActivity.this,InscriptionDonateurActivity.class);
startActivity(in);
}
});
ImageButton btn1;
btn1 =(ImageButton)findViewById(R.id.InscriptionAssociationButton);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {Intent in= new
Intent(LoginActivity.this,InscriptionAssociationActivity.class);
startActivity(in);
}
});
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, String> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
String login_url= ip.concat("login.php");
try {
URL url= new URL(login_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream= httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String Post_data= URLEncoder.encode("user-email","UTF-8")+"="+URLEncoder.encode(mEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(mPassword,"UTF-8");
bufferedWriter.write(Post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
qui=null;
id=0;
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String resultat="";
String ligne="";
while((ligne=bufferedReader.readLine())!=null)
resultat += ligne;
if (resultat.equals("rien")) return resultat; else {
JSONObject jsonObject = new JSONObject(resultat);
JSONArray json_data = jsonObject.getJSONArray("myarray");
qui=json_data.getString(0);
id=json_data.getInt(1);
username= json_data.getString(2);}
/* for(int i=0;i<json_data.length();i++)
{
k++;
qui= json_data.getString(1);
id= json_data.getInt(2);
//r.add(json_data.getString("categorie"));
}*/
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return resultat;
} catch (MalformedURLException e) {
e.printStackTrace();return e.toString();
} catch (IOException e) {
e.printStackTrace();return e.toString();
} catch (JSONException e) {
e.printStackTrace(); return e.toString();
}
}
/* for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}*/
// TODO: register the new account here.
#Override
protected void onPostExecute(String resultat) {
mAuthTask = null;
showProgress(false);
/////////////////////////////////////////////////////////////////////////////////
Intent i;
AlertDialog a;
if (resultat.equals("rien")){i= new Intent(LoginActivity.this,LoginActivity.class);
a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Erreur");
a.setMessage(" Email et/ou mot de passe erroné(s)");
a.show();} else {
try {
session.createLoginSession(mEmail,username,qui,id);
session.checkLogin();
if (qui.equals("donateur")) {
i = new Intent(LoginActivity.this, Suite_Inscription_Donateur.class);
i.putExtra("id", id);
startActivity(i);
} else if (qui.equals("association")) {
session.createLoginSession(mEmail,username,qui,id);
i = new Intent(LoginActivity.this, Suite_Inscription_Association.class);
i.putExtra("id", id);
startActivity(i);
}
} catch (Exception e) {
e.printStackTrace();
a= new AlertDialog.Builder(LoginActivity.this).create();
a.setTitle("Erreur");
a.setMessage("Erreur :".concat(e.toString()));
a.show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
I want to make a simple login and register app, so the user can create an account. (name, username, password)
I use WAMP and a MYSQL database where I store the accounts.
When I fill in the user info on the registration form and click register I get the following error:
09-14 09:30:39.864 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7115e0
09-14 09:30:48.632 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7125a0
09-14 09:30:51.940 2624-2638/com.example.appname.appname E/Surface﹕ getSlotFromBufferLocked: unknown buffer: 0xab7125a0
When I go check the database it didn't store the account.
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void userReg(View v)
{
startActivity(new Intent(this, Register.class));
}
public void userLogin(View view)
{
}
}
Register.java
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class Register extends Activity {
EditText ET_NAME,ET_USER_NAME,ET_USER_PASS;
String name,user_name,user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText) findViewById(R.id.name);
ET_USER_NAME = (EditText) findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText) findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(Register.this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
}
Backgroundtask.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2.2/webapp/register.php";
String login_url = "http://10.0.2.2.2/webapp/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
register.php
<?php
require "init.php";
$name = $_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query))
{
//echo"<h3> Data insertion success...</h3>";
}
else{
//echo "Data insertion error..".mysqli_error($con);
}
?>
init.php
<?php
$db_name="myDBname";
$mysql_user = "root";
$mysql_pass = "root";
$server_name="localhost";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
if(!$con)
{
//echo"Connection Error".mysqli_connect_error();
}
else
{
//echo"<h3> Database connection success.....</h3>";
}
?>
Edit:
This was a bug in Android that was fixed in later versions of Marshmallow
Original:
I believe that this is Marshmallow specific. Are you using a Marshmallow device?
I've noticed this error is printed out every time I switch between applications (doesn't matter which) or exit out of them, and when activities are destroyed.
I've tried running the same apps on two Nexus 5s - one running Lollipop and the other Marshmallow, and these log prints only appeared on the Marshmallow version - with every app, not just the one I'm building.
Not sure why this happens, but I opened a report here.
I think you are finishing the context before backgrounTask finish, and Context you pass no longer exist.
You can try:
Use appContext : new BackgroundTask(Register.this.getApplicationContext());
Or, Wait for BackgroundTask finish : remove finish() after .execute(...) and add finish() onPostExecute
I don't have specific problem's solution. But I had similar problem.
Anyone who has problem like this please make sure you have below code.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<YOUR_XML_FILE_NAME>);
by using intelligence you might have choose below code:
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.<YOUR_XML_FILE_NAME>);
}
This worked for me
For more info on PersistentState
Happy coding :)
Update your android OS to 6.0.1.
This was an open issue found here. The issue is fixed in Android 6.0.1 which was publicly released recently.
It's quite strange but in my case i got this error when tried loading contacts without adding
<uses-permission android:name="android.permission.READ_CONTACTS" />
into manifest. And it disappeared just I've done it.
So my guess it's might be something with new permissions in Marshmallow.
Tested on my Nexus 5 with Android 6.0 and with targetSdkVersion 23 in build.gradle
Since that android changed permissions request (some permissions like android.permission.READ_PHONE_STATE or android.permission.READ_CONTACTS), when you ask for these permissions at runtime and dont add the permission tag (<uses-permission android:name="..." />) in manifest, you will get the error.
So just use tag permissions like old versions and add request permission at runtime in newer versions.
I'm trying to connect to a database on a sql server using jTDS-1.2.5. I know that this is dangerous and insecure, and I shouldn't be doing it this way, but I just want to try it, so humor me. To test jTDS I wrote this code in netbeans:
package dbconnecttest;
import java.sql.*;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.*;
public class DBConnectTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String connString = "jdbc:jtds:sqlserver://MY_SERVER_NAME:24923/Phone_Test;user=testLogin;password=xxxxxxxx;instance=MYINSTANCE";
con = DriverManager.getConnection(connString,"testLogin","xxxxxxxx");
try {
PreparedStatement stmt = con.prepareStatement("SELECT * FROM Product_Inventory_Test WHERE ProductTest = 'Car'");
stmt.execute();
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString("ProductTest").replace(" ", "") + " price: $" + rs.getString("PriceTest"));
}
stmt.close();
} catch (Exception e) {
System.out.println("Statement error: " + e.getMessage());
}
con.close();
}
catch (Exception e) {
System.out.println("Connection Error: " + e.getMessage());
}
}
}
Notice, I am connecting on a port other than 1433. I have enabled TCP/IP in the configuration manager, and set the TCP port for all the IP address to 24923. I also made sure it wasn't dynamically assigning TCP ports. This code works fine in netbeans, and it pulls the data from the database without any problems. I'm using similar code in eclipse on my android app:
package com.xxxxxx.xxxxxx;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.*;
public class LoginActivity extends Activity {
TextView labelLogin;
TextView labelError;
EditText txtUsername;
EditText txtPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Assign properties to login form views
labelLogin = (TextView)findViewById(R.id.labelLogin);
labelError = (TextView)findViewById(R.id.labelError);
txtUsername = (EditText)findViewById(R.id.txtUsername);
txtPassword = (EditText)findViewById(R.id.txtPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#SuppressWarnings("deprecation")
public void login_onClick(View view) {
Connection con = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String connString = "jdbc:jtds:sqlserver://MY_SERVER_NAME:24923/Phone_Test;user=testLogin;password=xxxxxxxx;instance=MYINSTANCE";
String username = "testLogin";
String password = "xxxxxxxx";
con = DriverManager.getConnection(connString,username,password);
PreparedStatement stmt = null;
try {
//Prepared statement
stmt = con.prepareStatement("SELECT * FROM Logins WHERE Username = ? AND Password = ?");
stmt.setString(1, txtUsername.toString());
stmt.setString(2, txtPassword.toString());
stmt.execute();
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
//Start new activity
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setTitle("Success!");
ad.setMessage("You have logged in successfully!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
stmt.close();
}
catch (Exception e) {
stmt.close();
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setTitle("Error");
ad.setMessage("Prepared statement error: " + e.getMessage());
ad.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
con.close();
}
catch (Exception e) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setTitle("Error");
ad.setMessage("Connection error: " + e.getMessage());
ad.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
}
}
I have added the jar file to the classpath, and everything seems to work fine. When I run the app on an emulator, though, it gives me the error:
Connection Error: Unable to get information from SQL Server: MY_SERVER_NAME.
I'm kinda stuck on what to do next. Everything seems to be working fine, it just won't connect. I've tried going to command prompt and trying sqlcmd -L, and it has my server in the list. I can also telnet into my server from there. netstat -an shows that it's listening on port 24923 with local ip address 0.0.0.0. I'm just not sure what the problem is, and I've checked the jTDS FAQ tips about resolving this error already. Any ideas/suggestions?