How to connect and access SQL Database server from Android app??

Recently I have tried to connect to SQL Database server which is in my local network machine. I can connect and access SQL server from my Android app. I did it in the following way….

1. First of all you need a JDBC driver library for SQL Server. As we know android library has only SQLite database driver. So first download an open source JDBC driver from this http://jtds.sourceforge.net/ site (I downloaded the Linux version).

2. Then import the jar file into your Android app.(jtds-1.2.5.jar).

3. Now just try this code by modifying according to your context

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import net.sourceforge.jtds.jdbc.*;

public void query2()
{
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
String connString = "jdbc:jtds:sqlserver://server_ip_address :1433/DBNAME;encrypt=fasle;user=xxxxxxxxx;password=xxxxxxxx;instance=SQLEXPRESS;";
String username = "xxxxxx";
String password = "xxxxxxxxxx";
conn = DriverManager.getConnection(connString,username,password);
Log.w("Connection","open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from TableName");

//Print the data to the console
while(reset.next()){
Log.w("Data:",reset.getString(3));
//              Log.w("Data",reset.getString(2));
}
conn.close();

} catch (Exception e)
{
Log.w("Error connection","" + e.getMessage());
}
}

4. You will find more about parameter passing here in connection string  http://jtds.sourceforge.net/doc.html .

Android begining: Some problems those I faced when I started to develop android !!!

I have been developing android application since last 8 months. During that time I faced a lot of weird problems which wasted a lot of time and created a lot mental pressure on me. No I always try to keep in mind on those things before coding for android application. Let’s discuss some of those things…..

1. First of all I faced problem when I tried to work with functionality which takes a lot of time to finish execution( i.e  parsing a web url response content). It caused ANR (application not responding). Android recommendation was to use asynchronus task for heavy process (http://developer.android.com/reference/android/os/AsyncTask.html) . It is really simple to understand. But as beginner I wasted time to figure out it.

2. Second problem was to update the UI from background function/thread. There is a nice technique for this, use runOnUiThread() method for updating the UI instead from background thread.

3. Most time wasting issue was working with networking on android device specially with WIFI. If you use wifi for net connection or communicate through wifi wireless device/router don’t forget to wait until there is valid DHCP is assigned to your android phone/device. I was tried to do stuff as soon as wifi is enabled checking the network is available. Though there is a method for checking network availablity that made me a real fool for a long period of time. It shows that network is available but still the valid DHCP is not assigned.

4. The most dangerous issue I faced was “Virtual machine memory budget issue”. I worked on multiple IP camera streaming. First stage of development memory budget issue was occurring frequently and the app was crashing unexpectedly. There were so many threads and about 4 input streaming is closed at the same time and I found that if the heap memory size exceeds more than 10 MB (Android 1.6) then memory issue occurs. So when working with stream and graphics care should be taken that the app doesn’t hold up much heap memory.

Necessary gem lists

You are an experienced Ruby developer then you know most of the gems I have listed here.  But there are some gems which are awesome for scaling your Rails application in a better way – necessary to be an rails project leader.

Lets take a look at some of them…..

  • hoptoad_notifier             # Exception notification
  • jammit                       # Asset bundler
  • bullet                       # Find n+1 eager loading issues in development
  • yajl-ruby               # Faster JSON parsing, utilized in Rails 2.3.6+ if available
  • paperclip                   # Image attachments (Note anything after v2.3.1 requires Ruby 1.8.7+)
  • mysql2                       # Woot! Much faster replacement for aging mysql adapter
  • resque                       # Redis-based background worker queue
  • resque_mailer                # Email sending from resque
  • delayed_paperclip            # Paperclip processing in the background

# Interface with the sphinx search daemon

  • thinking-sphinx
  • ts-resque-delta
Posted in Uncategorized. Tags: . Leave a Comment »

How to add bookmarklet??

The following code help you to add bookmarklet to other site……………….

javascript:(function(){
if(document.getElementById) 
{var x=document.getElementsByTagName(‘head’).item(0);
 var o=document.createElement(‘script’); 
if(typeof(o)!=’object’) o=document.standardCreateElement(‘script’); 
o.setAttribute(‘src’,'http://………………………./javascripts/mr.js’);   
o.setAttribute(‘type’,'text/javascript’)
if (document.getElementById(“divAddToMyregistry_Panel_Container”)) {
CreateDiv_AddToMyregistry();
}
else {
var documentBody = document.getElementsByTagName(“body”)[0];
var Divform = document.createElement(‘div’)
Divform.id = “popup_name”
Divform.className =”bookmark_popup_block”
documentBody.appendChild(Divform)
var Div_own = document.getElementById(‘popup_name’)
var Divform2 = document.createElement(‘div’)
Divform2.id = “bookmark_content”
Div_own.appendChild(Divform2)
var MrOtherStores1 = document.createElement(‘link’);
MrOtherStores1.rel = “stylesheet”;
MrOtherStores1.type = ‘text/css’;
MrOtherStores1.href = “http://………………./stylesheets/bookmark.css”;
documentBody.appendChild(MrOtherStores1);
// Check Price
var MrOtherStoresPrice = document.createElement(‘script’);
MrOtherStoresPrice.id = “mr_scriptGetPrice”;
MrOtherStoresPrice.type = ‘text/javascript’;
MrOtherStoresPrice.src = “http://……………/javascripts/jquery.js”;
documentBody.appendChild(MrOtherStoresPrice);
var newScript1 = document.createElement(‘script’);
newScript1.id = “pt_scriptAuthentication”;
newScript1.type = ‘text/javascript’;
newScript1.src = “http://………………………………/javascripts/jquery.xdomainajax.js”;
documentBody.appendChild(newScript1);
var drag_script = document.createElement(‘script’);
drag_script.id = “drag_script”;
drag_script.type = ‘text/javascript’;
drag_script.src =”http://…………………./javascripts/event_drag.js”;
documentBody.appendChild(drag_script);
// Check Cookie
var newScript = document.createElement(‘script’);
newScript.id = “mr_scriptAuthentication”;
newScript.type = ‘text/javascript’;
newScript.src = “http://…………………../javascripts/bookmark.js”;
documentBody.appendChild(newScript);

jQuery(document).ready(function() {
var popID = “popup_name” //jQuery(this).attr(‘rel’); //Get Popup Name
var popURL = “#?w=685″ //jQuery(this).attr(‘href’); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split(‘?’);
var dim= query[1].split(‘&’);
var popWidth = dim[0].split(‘=’)[1]; //Gets the first query string value
//Fade in the Popup and add close button
jQuery(‘#’ + popID).fadeIn().css({
‘width’: Number( popWidth )
}).prepend(‘<img src=”http://………………………./images/lightview/close_small.png” alt=”Close” />’);
jQuery(‘#popup_name’).bind(‘drag’, function(event){
jQuery(this).css({
top: event.offsetY,
left: event.offsetX
});
});
////Close Popups and Fade Layer
jQuery(‘.book_close, #fade’).live(‘click’, function() { //When clicking on the close or fade layer…
jQuery(‘#fade, .bookmark_popup_block’).fadeOut(function() {
jQuery(‘#fade, .book_close’).remove();  //fade them both out
});
return false;
});
var d = document
var w = window
var e = w.getSelection
var k = d.getSelection
var x = d.selection
var s = (e?e():(k)?k():(x?x.createRange().text:0));
var f = “http://……………………/item_from_bookmarklet”;
var l = d.location
e = encodeURIComponent
var p= ‘?v=1&u=’+ e(l.href)%20 + ‘&t=’ + e(d.title.replace(/^\s*|\s*$/g,”))%20 + ‘&s=’+ e(s);
var loadUrl=f;
jQuery.ajaxSetup({
cache: false
});
var ajax_load = “<img src=’img/load.gif’ alt=’Loading…’ />”;
jQuery(“#bookmark_content”).html(ajax_load).load(“http://…………………………/item_from_bookmarklet?” + “u=”+ encodeURIComponent(l.href) +”&”+”s=”+ s + “&t=” + encodeURIComponent(d.title), null, function(responseText){
jQuery(‘#bookmark_content’).prepend(responseText);
});
});

How to solve delayed_job running problem in server machine?

If there is problem of running delayed job in your server machine then install “daemon-spawn” plugin and change the delayedjob script file as following…………..

require 'rubygems'

require 'daemon-spawn'

RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
class DelayedJobWorker < DaemonSpawn::Base
def start(args)
ENV['RAILS_ENV'] ||= args.first || 'development'
Dir.chdir RAILS_ROOT
require File.join('config', 'environment')
Delayed::Worker.new.start
end
def stop
system("kill `cat #{RAILS_ROOT}/tmp/pids/delayed_job.pid`")
end
end
DelayedJobWorker.spawn!(:log_file => File.join(RAILS_ROOT, "log", "delayed_job.log"),
:pid_file => File.join(RAILS_ROOT, 'tmp', 'pids', 'delayed_job.pid'),
:sync_log => true,
:working_dir => RAILS_ROOT)

The RAKE task for this is bellow……………………………………….


desc "Start delayed_job process"

task :start_job, :roles => :app do

run "cd #{current_path}; chmod 755 script/delayed_job; RAILS_ENV=#{env} script/delayed_job start"

end

desc "Stop delayed_job process"

task :stop_job, :roles => :app do

run "cd #{current_path}; chmod 755 script/delayed_job; RAILS_ENV=#{env} script/delayed_job stop"

end

Some important things while developing android application

To make your application more efficient remember the following things…………..

  • Accessing a local variable than a member field is more efficient in DVM (Dalvik Virtual Machine). So try to use local variable as you can .

Using re-captcha in Rails application

Captcha validation is implemented in rails app using “ambethia-recaptcha” gem. After installing the gem you need to do the following…..

You need to register in google recaptcha group which provides you 2 keys and put these 2 keys in your environment.rb file as follows

ENV['RECAPTCHA_PUBLIC_KEY']  = '6LffcrsSA...................................''
ENV['RECAPTCHA_PRIVATE_KEY'] = '6LffcrsSA.................................'

You just need to do the following code in your view if you want to show the default recaptcha…

=recaptcha_tags( )

If you want to customize it then write the following code in your view…

=recaptcha_tags( :display => {:theme => 'custom', :custom_theme_widget => 'recaptcha_container'})

#recaptcha_container

#recaptcha_image

%input#recaptcha_response_field.text{ :name => "recaptcha_response_field", :type => "text" }

%label{ :for => "recaptcha_response_field" }

(Enter the two words above)

%p

Choose captcha format:

%a.btn_img{ :href => "javascript:Recaptcha.switch_type('image');",:title => 'Image' }

or

%a.btn_audio{ :href => "javascript:Recaptcha.switch_type('audio');",:title => 'Audio' }

/%input#recaptcha_reload_btn{ :type => 'image', :src => '/images/home/refresh.gif', :style=>'width: 18px; height:15px',:value => 'New', :onclick => "Recaptcha.reload();" }

%script{ :src => "http://api.recaptcha.net/challenge?k=#{ENV['RECAPTCHA_PUBLIC_KEY']}", :type => "text/javascript" }

%noscript

%iframe{ :src => "http://api.recaptcha.net/noscript?k=#{ENV['RECAPTCHA_PUBLIC_KEY']}" }

/height="300" width="500" frameborder="0">

%textarea{ :name => "recaptcha_challenge_field", :rows => "3", :cols => "40" }

Then for validation you have to write code in your controller..........
if verify_recaptcha(:model => @user, :message => "Oh! It's error with reCAPTCHA!")
//
end
Follow

Get every new post delivered to your Inbox.