Connecting to FTP server using AsyncTask - android

I am quite new to android developing
I have written the following code to connect my android to a ftp server
package com.example.test1;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.*;
public class MainActivity extends Activity {
public FTPClient mFTPClient = null;
Button but;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
CharSequence c = ""+e;
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),c,d);
toast.show();
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but=(Button)findViewById(R.id.button1);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ftpConnect("127.0.0.1","userName","Password",21);
}
});
}
}
But this gives a networkOnMainThread Exception so after searching i found out i have to use AsyncTask but i have no idea how to implement it!

public void onClick(View v) {
new AsyncTask() {
publc Object doInBackground(Object...) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
return e;
}
}
}
public void onPostExecute(Object res) {
if (res instanceof Exception) {
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),""+res,d);
toast.show();
}
}
}.execute();
Another temporary 'workaround' is to set your android:targetSdkVersion="9" or below in AndroidManifest.xml, as this exception was introduced in API level 10.

Documentation on Android Developers is pretty rich on such an important topic. You'll get it through with that.
http://developer.android.com/reference/android/os/AsyncTask.html

You may want to refer the NetworkConnect sample from the Android SDK.

Related

error: package net.sourceforge.jtds.jdbc does not exist

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

Access database from android phone through android app

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

Connection to MS SQL server using jTDS on android

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?

unable to run my android application

I am trying to establish a chatting application between a server and a client, but the application could not run because of this line of code : message = (String) input.readObject();
because at first, inputStream is null ! any one can help please ? here is my code
package com.example.test;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button send;
private Button connect;
private EditText userText;
private TextView chatWindow;
private String serverIP;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private Socket connection;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
serverIP = "192.168.1.4";
//userText.setEnabled(false);
send = (Button)findViewById(R.id.button1);
connect = (Button)findViewById(R.id.button2);
chatWindow =(TextView)findViewById(R.id.textView1);
userText = (EditText)findViewById(R.id.editText1);
userText.setHint("Enter your message here");
connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//connect to the server
try{
connectToServer();
setupStreams();
}catch(EOFException eofException){
showMessage("\n client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String message = userText.getText().toString();
sendMessage(message);
userText.setText("");
}
});
while(true){
try{
message = (String) input.readObject();
showMessage("\n" + message + " NULL ");
chatWindow.refreshDrawableState();
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n I don't know that object type");
}
catch(NullPointerException e){
e.printStackTrace();
}
catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // end of onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//connect to the server
private void connectToServer() throws IOException {
showMessage("Attempting connection... \n");
connection = new Socket( "192.168.1.4", 6789);
showMessage("Connected to " + connection.getInetAddress().getHostName() );
}
//setup streams to send and receive messages
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Your streams are now good to go! \n ");
}
//whileChatting with server
private void whileChatting() throws IOException{
try{
message = (String) input.readObject();
showMessage("\n" + message + " NULL ");
chatWindow.refreshDrawableState();
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n I don't know that object type");
}
}
//close the streams and sockets
private void closeCrap(){
showMessage("\n closing crap down");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
// gives user permission to type into the text box
private void ableToType(final boolean tof){
userText.setEnabled(tof);
}
// send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n somethine messed up sending message!");
}
}
//change/update chatWindow
private void showMessage(final String m){
chatWindow.append(m);
chatWindow.refreshDrawableState();
}
} // end of class MainActivity
Your code is definitely not following any good UI guidelines: You are doing network operations on the Main (UI) Thread, and you have an infinite loop in onCreate(). Android should actually offer to force close your app if nothing crashes. Now, a likely cause for the null problem you are facing:
setupStreams() is only called upon a button click. However, your while (true) loop is in the root of onCreate(). This means that as soon as the click listeners are made and set, the loop runs, attempts to read in from input and fails since setupStreams() hasn't been called.
So please don't do away with StrictMode - it's there to help, and thing about your code from an event driven standpoint ("Once X happens, then do Y"). And also get rid of loops in the Main (UI) Thread. Loops are fine for Console windows, but with UIs (which have their own complex lifecycle), you can't do this without freezing a lot of things.
Do all of your network tasks in doInBackground() ofAsyncTask then update your UI variables in onPostExecute(). Something like
public class TalkToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
//do your work here
return something;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// do something with data here-display it or send to mainactivity
}
Here is the documentation on AsyncTask
Another thing to consider is you are using the variable message in different places which may cause you problems. It looks like you have it defined as a member variable then as a local variable to other methods. You don't want to re-use the same variable name this way. Don't define String message multiple times in the same Activity

Android: Force close when reading from Socket

I'm trying to make a client in Android. This clients runs a thread that creates the client socket and launches another thread that is always listening to the socket to receive Strings. Everything is OK when I send a String from the client to a Java server running in a PC, but when I send a String from the server to the Android client the app finishes. Why do I get this error?
Here is the code of the main Activity of the client:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView chatHistorial;
EditText msg;
Socket client;
DataInputStream in;
DataOutputStream out;
Boolean cerrar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable(){
#Override
public void run() {
try{
client = new Socket("192.168.1.33", 4444);
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
cerrar = false;
chatHistorial = (TextView) findViewById(R.id.chatHistorial);
msg = (EditText) findViewById(R.id.msg);
ThreadLectura tl = new ThreadLectura(in, cerrar, chatHistorial);
tl.start();
}
catch(Exception e){
// ...
}
}
});
t.start();
findViewById(R.id.enviar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cadena = msg.getText().toString();
try {
out.writeUTF(cadena);
} catch (IOException e) {
// ...
}
if(cadena.equals("exit"))
cerrar = true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class ThreadLectura extends Thread{
DataInputStream in;
String cadena;
TextView chatHistorial;
Boolean cerrar;
public ThreadLectura(DataInputStream in, Boolean cerrar, TextView tv){
this.in = in;
this.cerrar = cerrar;
chatHistorial = tv;
}
#Override
public void run(){
try{
while(!cerrar){
cadena = in.readUTF();
chatHistorial.append("Has recibido: " + cadena);
}
}
catch(IOException ioe){
System.out.println("Error de entrada/salida: "+ioe.getMessage());
}
}
}
It's hard to say without seeing your logcat output, but I'm betting it's because you are attempting to modify the UI from within your background thread. This line within ThreadLectura:
chatHistorial.append("Has recibido: " + cadena);
is probably the issue, as chatHistorial is a TextView. You need to only modify the UI from within the main UI thread.

Categories

Resources