Monday, 30 July 2012

Google map example in android

Android Google map and Google api key example
Hello Friends ,Here I am sharing the full tutorial of How to implements Google map
in your android application:

Step 1: Creating Key Store 


Open the command prompt and follow the steps

C:\Mukesh\Android-Sdk\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your 
organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

Is CN=mukesh, OU=zss, O=zss, L=delhi, ST=delhi, C=dl correct?

[no]: yes

Generating 2,048 bit RSA key pair and self-signed certificate 

(SHA1withRSA) with a validity of 15,000 days

        for: CN=CN, OU=OU, O=O, L=L, ST=ST, C=C

Enter key password for <aliasname>

        (RETURN if same as keystore password): ------------

Re-enter new password: ------------

[Storing projectkey.keystore]
C:\Mukesh\Android-Sdk\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Jul 22, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5):
A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0



Step 2: Obtaining Google API key for Google Map:
                                            Using Certificate fingerprint(MD5) you can get your get your google 
API Key from this link:
                         http://code.google.com/android/maps-api-signup.html 


Finally you get this:
Your key is: 
0NmasjBqpEvFTVP4IugZrbssdsIKnwPH2qSpd8g

This key is good for all apps signed with your certificate whose fingerprint is:

A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0

Here is an example xml layout to get you started on your way to mapping glory:
              <com.google.android.maps.MapView
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:apiKey="0NmasjBqpEvFTVP4IugZrbssdsIKnwPH2qSpd8g"
                 />


Use the above xml code and Enjoy...:)
Please Comment me or Ask if you face any problem.

Thursday, 26 July 2012

Phonegap get Latitude and Longitude / PhoneGap Geolocation Sample Application

Hello Friends,

With the help Phone Gap Api, You can easily get current position using GPS .
To start playing with it, Please have a look at this simple function or Code:

// Check if geolocation is available
if(navigator.geolocation) {
    // This is the specific PhoneGap API call
    navigator.geolocation.getCurrentPosition(function(p) {
        // p is the object returned
        alert('Latitude '+p.coords.latitude);
        alert('Longitude '+p.coords.longitude);
    }, function(error){
        alert("Failed to get GPS location");
    });
} else {
    alert("Failed to get GPS working");
}


Also Please add permission in your plugin.xml file
1.<plugin name="Geolocation" value="com.phonegap.GeoBroker"/>
2. <plugin name="Notification" value="com.phonegap.Notification"/>



Enjoy Coding.... :)
Please, write questions in comments.
Don’t forget share this post....... :) 

Monday, 23 July 2012

Android Send and Receive Sms


Hello Friends ,
Today ,I am sharing a sample application in which we can send and received
the sms.

1. SmsActivity.java



package com.app;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SmsActivity extends  Activity 
{
 Button btnSendSMS;
 EditText txtPhoneNo;
 EditText txtMessage;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
        
        /*
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);
        */
                
        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {             
             String phoneNo = txtPhoneNo.getText().toString();
             String message = txtMessage.getText().toString();              
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                 Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }
    
    //---sends a SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {      
     /*
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, test.class), 0);                
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, pi, null);        
        */
     
     String SENT = "SMS_SENT";
     String DELIVERED = "SMS_DELIVERED";
     
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
        
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
     
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
   @Override
   public void onReceive(Context arg0, Intent arg1) {
    switch (getResultCode())
    {
        case Activity.RESULT_OK:
         Toast.makeText(getBaseContext(), "SMS sent", 
           Toast.LENGTH_SHORT).show();
         break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
         Toast.makeText(getBaseContext(), "Generic failure", 
           Toast.LENGTH_SHORT).show();
         break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
         Toast.makeText(getBaseContext(), "No service", 
           Toast.LENGTH_SHORT).show();
         break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
         Toast.makeText(getBaseContext(), "Null PDU", 
           Toast.LENGTH_SHORT).show();
         break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
         Toast.makeText(getBaseContext(), "Radio off", 
           Toast.LENGTH_SHORT).show();
         break;
    }
   }
        }, new IntentFilter(SENT));
        
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
   @Override
   public void onReceive(Context arg0, Intent arg1) {
    switch (getResultCode())
    {
        case Activity.RESULT_OK:
         Toast.makeText(getBaseContext(), "SMS delivered", 
           Toast.LENGTH_SHORT).show();
         break;
        case Activity.RESULT_CANCELED:
         Toast.makeText(getBaseContext(), "SMS not delivered", 
           Toast.LENGTH_SHORT).show();
         break;         
    }
   }
        }, new IntentFilter(DELIVERED));        
     
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);               
    }    
}

2.SmsReceiver.Java



package com.app;



import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.gsm.SmsMessage;

import android.widget.Toast;



public class SmsReceiver extends BroadcastReceiver

{

 @Override

 public void onReceive(Context context, Intent intent)

 {

        //---get the SMS message passed in---

        Bundle bundle = intent.getExtras();       

        SmsMessage[] msgs = null;

        String str = "";           

        if (bundle != null)

        {

            //---retrieve the SMS message received---

            Object[] pdus = (Object[]) bundle.get("pdus");

            msgs = new SmsMessage[pdus.length];           

            for (int i=0; i<msgs.length; i++){

                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);               

                str += "SMS from " + msgs[i].getOriginatingAddress();                    

                str += " :";

                str += msgs[i].getMessageBody().toString();

                str += "\n";       

            }

            //---display the new SMS message---

            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

        }                   

 }

}


Download The Source Code:
Sms.zip



Sunday, 22 July 2012

Creating keystore and google api key for google maps-Android



Open the command prompt and follow the steps

C:\Mukesh\Android-Sdk\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your 
organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

Is CN=mukesh, OU=zss, O=zss, L=delhi, ST=delhi, C=dl correct?

[no]: yes

Generating 2,048 bit RSA key pair and self-signed certificate 

(SHA1withRSA) with a validity of 15,000 days

        for: CN=CN, OU=OU, O=O, L=L, ST=ST, C=C

Enter key password for <aliasname>

        (RETURN if same as keystore password): ------------

Re-enter new password: ------------

[Storing projectkey.keystore]
C:\Mukesh\Android-Sdk\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Jul 22, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5):
A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0

Using your Certificate fingerprint (MD5) get google api key from this site

http://code.google.com/android/maps-api-signup.html

Tuesday, 10 July 2012

Sending Sms in JAVA


Hello friends have you searching of sending mobile alert or mobile
Notification from your Java web Application ?

If, Yes then this blog Helps you a lot.

While lot of searches I came across to Red Oxygen SMS gateway.
It provide a few free messages on the daily basis for your testing
Purpose.

For sending sms from your application first of all you have to sign
Up  your account in Red Oxygen .

Once you create your account in Red Oxygen you receive a mail
Which contains:

Account Name:
Mukesh Yadav
Account ID:
CI0007555890
Email Address:
Password:
************


Now  Place the following code in your web application and Enjoy the
Mobile alert facility.




/*
 *
 *  Java example code to send an SMS via the Red Oxygen SMS gateway over HTTP.
 *
 *  Mukesh Yadav   
 */

import java.io.*; 
import java.net.*; 
import java.lang.*; 



public class RedOxygenSMS
{ 

 public static int  SendSMS(String strAccountId,String strEmail,
        String strPassword,String strMSISDN,String strMessage,
        StringBuffer strResponse)
 {
  String  sRequestURL;
  String  sData;
  Integer nResult = -1;
 
  sRequestURL = "http://sms1.redoxygen.net/sms.dll?Action=SendSMS";

  try
  {  
  
   sData  = ("AccountId="  +       URLEncoder.encode(strAccountId,"UTF-8"));
   sData += ("&Email="     + URLEncoder.encode(strEmail,
                        "UTF-8"));
   sData += ("&Password="  + URLEncoder.encode(strPassword,
                        "UTF-8"));
   sData += ("&Recipient=" + URLEncoder.encode(strMSISDN,
                        "UTF-8"));
   sData += ("&Message="   + URLEncoder.encode(strMessage,
                        "UTF-8"));


  
   URL urlObject = new URL(sRequestURL); 
   
   HttpURLConnection con = (HttpURLConnection)  urlObject.openConnection();
   con.setRequestMethod("POST");
   con.setDoInput (true);
                        con.setDoOutput (true);


   DataOutputStream out;
              out = new DataOutputStream(con.getOutputStream());
              out.writeBytes (sData);
   out.flush();
   out.close();
      
   BufferedReader in = new BufferedReader
                          (new InputStreamReader(con.getInputStream())); 
     
   String inputLine; 
   StringBuffer responseBuffer = new StringBuffer(); 

   while ((inputLine = in.readLine()) != null)
   {
                              responseBuffer = responseBuffer.append(inputLine);
         responseBuffer = responseBuffer.append("\n\n\n");
   }
  
   strResponse.replace(0,0,responseBuffer.toString());

   String sResultCode = strResponse.substring(0,4);
   nResult = new Integer(sResultCode);
   
   in.close();
  }
  
  catch (Exception e)
  {
   System.out.println("Exception caught sending SMS\n"); 
   nResult = -2;
  }
  return nResult;
 }


 public static void main(String[] args) throws Exception 
 { 
  String strAccountId  = "CI00001234";  // Put your AccountId here
  String strEmail      = "youremal@company.com";  // Put your Email address here (Used for authentication and replies)
  String strPassword   = "yourpassword";  // Put your Password here
  String strMSISDN     = "61407000000";   // Put a recipient mobile number here
  String strMessage    = "Test SMS via Red Oxygen API";  // Put your SMS message text here
  Integer nResult;
  StringBuffer strResponse = new StringBuffer();

  nResult = SendSMS(strAccountId,strEmail,strPassword,strMSISDN,strMessage,strResponse);

                System.out.println("Result Code = " + nResult + "\n");
  System.out.println("Response Text = " + strResponse + "\n");

 } 
} 




Hope this will help you…
Enjoy Coding J

Tuesday, 3 July 2012

Database in HTML5

Hello Guys,

Have you thinking of Creating | Inserting | Fetching of data in HTML5. If yes then this
Blog will helps you a lot.
Yesterday I worked on a phonegap Application where my need is to provide offline
Access to my mobile Apps. Its very Simple using HTML5 offline access to local
Database .

Here , I am sharing with a sample code:

1. Creating Database and Table in HTML5:
         This is, just a simple form. Of course, when you have a form, you want to capture the form submission somehow. In our case, we’ll use the new HTML5 local SQL database. We don’t need any servers or HTTP requests or anything except a compatible browser .
Here’s how we initialize the database:

Below can see that all we did here was add an openDatabase call and some SQL statements to create tables. These are just standard SQL statements (the reference SQL is from SQLite). 

<!DOCTYPE html> 
<html>  
  <head>
    <title>Offline Storage</title>
    <script src="http://www.google.com/jsapi"></script>
    <script>
      google.load("jquery", "1.4.1");
    </script>
    <script>
      var db = window.openDatabase("Student", "", "Previous Course", 1024*1000);
      $(document).ready(function() {
        db.transaction(function(tx) {
          tx.executeSql('CREATE TABLE IF NOT EXISTS Course(id INTEGER PRIMARY KEY, course_id
              INTEGER, subject_one TEXT, subject_two TEXT, email TEXT)', []);
        });
      });
    </script>
  </head>
  <body>
    <form method="get" id="course_form">
      <div>
        <label for="1">Subject 1</label>
        <input type="text" value="" id="subject1" name="subject1" placeholder="subject"/>
      </div>
      <div>
        <label for="2">Subject 2</label>
        <input type="text"  value="" id="subject2" name="subject2" placeholder="subject" />
      </div>
      <div>
        <input type="email" id="email" placeholder="Enter your email address" size="40"/>
      </div>
      <div>
        <input type="submit" value="Upload Data" />
      </div>
    </form>
  </body>
</html> 


2. Inserting Data into the Table:
               Now we’ll write a couple functions to help us insert subject into this table:

<!DOCTYPE html>
<html>
<head>
<title>OffLine Storage</title>
<script src="http://www.google.com/jsapi"></script>
<script>
      google.load("jquery", "1.4.1");
</script>
<script>
      var db = window.openDatabase("Student", "", "Previous Course", 1024*1000);

      function insertSubject(subject_one, subject_two, course_id, email) {
       db.transaction(function(tx) {
          tx.executeSql('INSERT INTO Course (course_id, subject_one, subject_two, email)
            VALUES (?, ?, ?, ?)', [course_id, subject_one, subject_two, email]);
       });
      }

      $(document).ready(function() {
        db.transaction(function(tx) {
          tx.executeSql('CREATE TABLE IF NOT EXISTS Course(id INTEGER PRIMARY KEY, course_id
           INTEGER, subject_one TEXT, subject_two TEXT, email TEXT)', []);
        });

        $('#course_form').submit(function() {
         course = { 1: $('#subject1').val(), 2: $('#subject2').val() };
          
          insertSubject($('#subject1').val(), $('#subject2').val(), 1, $('#email').val());

          return false;
        });
      });
    </script>
</head>
<body>
<form method="get" id="course_form">
<div>
<label for="1">Subject 1</label> <input type="text" value=""
id="subject1" name="subject1" placeholder="subject" />
</div>
<div>
<label for="2">Subject 2</label> <input type="text" value=""
id="subject2" name="subject2" placeholder="subject" />
</div>
<div>
<input type="email" id="email" placeholder="Enter your email address"
size="40" />
</div>
<div>
<input type="submit" value="Upload Data" />
</div>
</form>
</body>
</html>

3. Displaying | Fetching of data from the table :
       Getting data inserted into our database was trivial, but now we want to show previously submitted data, right? This is easy, too. We’ll start with two changes: (1) show ALL previously submitted data upon loading the page, and (2) update this list whenever new data are submitted.




<!DOCTYPE html>
<html>
<head>
<title>OffLine Storage</title>
<script src="http://www.google.com/jsapi"></script>
<script>
      google.load("jquery", "1.4.1");
</script>
<script>
      var db = window.openDatabase("Student", "", "Previous Course", 1024*1000);

      function insertSubject(subject_one, subject_two, course_id, email) {

       db.transaction(function(tx) {
          tx.executeSql('INSERT INTO Course (course_id, subject_one, subject_two, email)
VALUES (?, ?, ?, ?)', [course_id, subject_one, subject_two, email]);
       });
      }

      function renderResults(tx, rs) {
          e = $('#previous_course');
          e.html("");
          for(var i=0; i < rs.rows.length; i++) {
            r = rs.rows.item(i);
            e.html(e.html() + 'id: ' + r['id'] + ', subject_one: ' + r['subject_one'] + ',
  subject_two: ' + r['subject_two'] + ', email: ' + r['email'] + '<br />');
          }
        }
        function displayData(email) {
          db.transaction(function(tx) {
            if (!(email === undefined)) {
              tx.executeSql('SELECT * FROM Course WHERE email = ?', [email], renderResults);
            } else {
              tx.executeSql('SELECT * FROM Course', [], renderResults);
            }
          });
        }
        $(document).ready(function() {

         db.transaction(function(tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS Course(id INTEGER PRIMARY KEY,
course_id INTEGER, subject_one TEXT, subject_two TEXT, email TEXT)', []);
               });
               $('#course_form').submit(function() {
                course = { 1: $('#subject1').val(), 2: $('#subject2').val() };
                insertSubject($('#subject1').val(), $('#subject2').val(), 1, $('#email').val());
                displayData();
            return false;
          });
               displayData();
        });
    </script>
</head>
<body>
<form method="get" id="course_form">
<div>
<label for="1">Subject 1</label> <input type="text" value=""
id="subject1" name="subject1" placeholder="subject" />
</div>
<div>
<label for="2">Subject 2</label> <input type="text" value=""
id="subject2" name="subject2" placeholder="subject" />
</div>
<div>
<input type="email" id="email" placeholder="Enter your email address"
size="40" />
</div>
<div>
<input type="submit" value="Upload Data" />
</div>
</form>
<div>
<h2>Previous Course</h2>
</div>
<div id="previous_course"></div>
</body>
</html>

Hope this will helps some one.....
Enjoy Coding  :)

 

Copyright @ 2013 Android Developer Blog.