Monday, April 6, 2015

GPS Application for Android..

In this example I will show you how to make an application which is use GPS.

First make an project and then create/ edit an xml file shown as below.

activity_my.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity"
    android:orientation="vertical">



    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Longtitude :-  "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <TextView
            android:text=" "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/label_long"/>
        </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="15px">
        <TextView
            android:text="Lattitude     :-"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/label_lat"/>
        <TextView
            android:text=" "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        </LinearLayout>
   

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="15px">
        <TextView
            android:text="Time           :-"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:text=" "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/label_time"/>
    </LinearLayout>




</LinearLayout>

First Look at the First <LinearLayout> block (blue colour)  It divides you screen vertically.
Like in the following image.
---------------------------------------------------------------------
When we add the first <LinearLayout>.......</LinearLayout> block first divided part will divide horzontally.

Now go to MyActivity.java file
And add 
public class MyActivity extends Activity implements LocationListener
for 
public class MyActivity extends

Then you will get red line in the edited line.
Right click on that and press Alt + Enter and click Implement methods.
Select all methods.



Saturday, March 28, 2015

Add a websocket Connection to android

In this post I will show how to integrate web socket server in to your android application.

This can be use to END-END communication between devices.

First you must download these 3 libraries from autobhan website.
AutobahnAndroid

Create a new project in android studio.





Then add a button in to the activity_my.xml file and edit the xml file.



Now you need to add the library.
go to lib folder in your project window(window in the left)

Copy the autobahn library you downloaded in to lib folder.



Go to android studio click synchronize lib folder

Then add autobahn as a library.



 Go to MyActivity.java file
and add the follwing code

USE ws://echo.websocket.org as websocket link..
Note:- this socket will reply the echo of our message.
       Thanks to:-http://www.websocket.org/echo.html
Keep the cursor in the try block and do the following
Then you will see the following methods are created

onOpen :- Calls when app connect to the web socket server.
onClose :- Calls when app/server close the connection.
onTextMessage :- Calls when you received a text message from the server.

The add the highlighted code
In button's code we call a send method with our message.

Then go to Androidmanifest.xml and add following codes.

Now run the the application.

Outputs


When app starting/Orientation is changing

Your app now connected with server..
Then Press Button you will see following screen.


Saturday, March 21, 2015

Use database in Android


Lets write a code for the Android application with Login function.
In here Most important thing we need is database.
In android we can use SQlite as our database provider.
Which is integrated in Android OS.

First we need to make a java class Which work as our database handler.
So every time we need to communicate with the database we must call a function in this java class.

When we create the java class   it must extends from SQLiteOpenHelper  Class.
It requires 2 methods to overide an one constructor.

    public DB(Context context) {
        super(context,"SMSDB.db",null,1);
    }

In constructor for super class we need pass 4 arguments.
One is the context
Second is Database name
Third column
Forth column

Methods to overide.
onCreate:- Execute when database create.
onUpgrade:- When SQLite version get update.


Normally Table create query , we write in the onCreate method.
In here I write code for create table which called login.
Columns:-
UserID int PrimaryKey,
createdate datetime default current_timestamp,
Username varchar(10),
Password varchar(255)

What happen when I say create datetime default current_timestamp
When user doesn't provide data while inserting a new row system will automatically inset the Current time when the row record.


How to get data from the database.
So we write anothe method

 public Cursor getAlllogin(){
        SQLiteDatabase database = this.getReadableDatabase();
        String selectquery="Select * from SMS";
        Cursor cursor = database.rawQuery(selectquery,null);
        return cursor;
    }

Cursor is the return type:
What is the Cusor?
  Cursor is an object which get the result of the database query.
 I will show how to get the cursor's data in below.



package com.example.nrv.msg;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


public class MyDB extends SQLiteOpenHelper {
    public DB(Context context) {
        super(context,"SMSDB.db",null,1);
    }

    @Override    public void onCreate(SQLiteDatabase database) {
        String create_login_query = "CREATE TABLE login(UserID int PrimaryKey,create datetime default current_timestamp,Username varchar(10),Password varchar(255))";
        database.execSQL(create_login_query);



    }

    @Override    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {

    }


    public Cursor getAlllogin(){
        SQLiteDatabase database = this.getReadableDatabase();
        String selectquery="Select * from SMS";
        Cursor cursor = database.rawQuery(selectquery,null);
        return cursor;
    }

    public void markSms(String id_no){//get the viewd sms ID as string and mark it as viewded        SQLiteDatabase database = this.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("Viewed", 1);
        database.update("SMS", values, "SmsID" + " = ?", new String[]{id_no});
    }

    public void addSms(String content,String send_by,boolean byme){
        SQLiteDatabase database = this.getReadableDatabase();
        ContentValues values = new ContentValues();
        if (byme){
            values.put("Viewed", 1);
            values.put("Content", content);
            values.put("Smsby", send_by);
            database.insert("SMS",null,values);
        }
        else{
            values.put("Content", content);
            values.put("Smsby", send_by);
            database.insert("SMS",null,values);
        }
    }

    public String getNumber(){
        SQLiteDatabase database = this.getReadableDatabase();
        String selectquery="Select * from maintable";
        Cursor cursor = database.rawQuery(selectquery,null);
        return cursor.getString(cursor.getColumnIndex("SPNumber"));

    }

    public void addNumber(String number){
        if (number.length()==10) {
            if (number.startsWith("0")) {
                number.replaceFirst("0", "+94");
            }
            SQLiteDatabase database = this.getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("SPNumber", number);
            database.update("maintable", values, "ID" + " = ?", new String[]{"1"});

        }
    }

}




Now You can use this DB interface anywhere in your code as follows.
Example.


package com.example.nrv.msg;

import android.app.ActionBar;
import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {
    MyDB db;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db=new MyDB(this);

        Button x=(Button)findViewById(R.id.button1);
        
        View.OnClickListener p=new View.OnClickListener() {
            @Override            public void onClick(View v) {
                db.addSms("Hello","0123456789",true);
            }
        };
        
        x.setOnClickListener(p);

    }



}


Hello world RPC

What is RPC?
         RPC stand for Remote procedure call.

We will see how to run an RPC program in Ubuntu.

Open the Terminal and type     rpcinfo
                      If you get error you must type the following command
                            Note:- You must connect to the internet before type he following command.
                     
                                      sudo apt-get install rpcbind
                                      To verify the installation retype rpcinfo
                       If you got the .following details.
                         
                           Now you can proceed.

What is our program do.

  •     Simply it is send the First and second initials in your name.
  •     Then server will print the both Initials.
  •     After that server replies how many messages server handle so far (with this message).
  •     Client will print it.


Now open text Editor and add the following code to a blank file.

struct messages{
char firstinitial;
char secondinitial;
};


program HELLO {
version HELLO_1{
int MY_FUNCTION(messages)=1;
}=1;
}=0x2fffffff;

We can use only one parameter for a function. So when we want to send 2 parameters simply we do is make structure (Class in java )which has number of parameters. So I need to send 2 parameters. Then I made a structure with 2 character parameters.

program HELLO 
this means the programs name. It must be capital.

version HELLO_1
This must be a capital.

int MY_FUNCTION(messages)=1;

This is the method we going to call remotely.
       int                             - return type
       MY_FUNCTION    - function name
       messages                  - type of the parameter
       1                               - number of the function. (I will give this as method number 1)

=1;
Version of the program

=0x2fffffff;
  Program number.


Then save it as hello.x

by using Terminal go to the folder where the hello.x is located.
Then type following command

            rpcgen -a -C hello.x

You can see some files were created in the folder where the hello.x is located.

Now open the hello_client.c file in that folder.
It must be something like this.

/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "hello.h"

void
hello_1(char *host)
{
CLIENT *clnt;
int  *result_1;
messages  my_function_1_arg;


#ifndef DEBUG
clnt = clnt_create (host, HELLO, HELLO_1, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */

result_1 = my_function_1(&my_function_1_arg, clnt);
if (result_1 == (int *) NULL) {
clnt_perror (clnt, "call failed");
}
#ifndef DEBUG
clnt_destroy (clnt);
#endif /* DEBUG */
}


int
main (int argc, char *argv[])
{
char *host;

if (argc < 2) {
printf ("usage: %s server_host\n", argv[0]);
exit (1);
}
host = argv[1];
hello_1 (host);
exit (0);
}


Explain:-
  my_function_1_arg -- Client must put data to here for send to server.
  *result_1  -- Servers reply will catch by this variable.
result_1 = my_function_1(&my_function_1_arg, clnt);   --- Where the function calls and get the reply


Now add the following sections.
        my_function_1_arg.firstinitial='L';
my_function_1_arg.secondinitial='J';
            This section must add before the  very first line of      #ifndef DEBUG line.    
                    Note:- you can add this line any where you want befor calling my_function1

       printf("You connect with server for %d time",result_1[0]);
             This section must add before the clnt_destroy (clnt); line.
                        Note:- you can add this line any where you want after calling my_function1


Now save the file.
AFTER EDIT CLIENT CODE LOOKS LIKE THIS

/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "hello.h"


void
hello_1(char *host)
{
CLIENT *clnt;
int  *result_1;
messages  my_function_1_arg;

my_function_1_arg.firstinitial='L';
my_function_1_arg.secondinitial='J';

#ifndef DEBUG
clnt = clnt_create (host, HELLO, HELLO_1, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */

result_1 = my_function_1(&my_function_1_arg, clnt);
if (result_1 == (int *) NULL) {
clnt_perror (clnt, "call failed");
}
#ifndef DEBUG
printf("You connect with server for %d time",result_1[0]);
clnt_destroy (clnt);
#endif /* DEBUG */
}


int
main (int argc, char *argv[])
{
char *host;

if (argc < 2) {
printf ("usage: %s server_host\n", argv[0]);
exit (1);
}
host = argv[1];
hello_1 (host);
exit (0);
}




Now open the hello_server.c file.
It must look like this.
/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "hello.h"
int calls=0;
int *
my_function_1_svc(messages *argp, struct svc_req *rqstp)
{
static int  result;
calls++;

/*
* insert server code here
*/
printf("Full initials are :- %c and %c \n",argp->firstinitial,argp->secondinitial);
result=calls;
return &result;
}


Edit it on following way.

/*
 * This is sample code generated by rpcgen.
 * These are only templates and you can use them
 * as a guideline for developing your own functions.
 */

#include "hello.h"


void
hello_1(char *host)
{
CLIENT *clnt;
int  *result_1;
messages  my_function_1_arg;

my_function_1_arg.firstinitial='L';
my_function_1_arg.secondinitial='J';

#ifndef DEBUG
clnt = clnt_create (host, HELLO, HELLO_1, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */

result_1 = my_function_1(&my_function_1_arg, clnt);
if (result_1 == (int *) NULL) {
clnt_perror (clnt, "call failed");
}
#ifndef DEBUG
printf("You connect with server for %d time",result_1[0]);
clnt_destroy (clnt);
#endif /* DEBUG */
}


int
main (int argc, char *argv[])
{
char *host;

if (argc < 2) {
printf ("usage: %s server_host\n", argv[0]);
exit (1);
}
host = argv[1];
hello_1 (host);
exit (0);
}

Now save it.

Then in terminal enter the following command.

             make -f Makefile.hello 

Then new files will create in the folder.
Then type sudo ./hello_server .

Now open a new terminal and go to the folder where the hello.x is located.
Now type sudo ./hello_client localhost .
local host means server's address.

You can see the following data in both terminals as a result

Do the sudo ./hello_client localhost      again and see the results.

Thursday, February 12, 2015

COM port in JAVA With Eclipse

In some cases we need to make programs which communicate with the COM port in the computer.
In here Com ports are normal USB ports.

So we have to add a library called RXTX.

To get that library you have to download the library from here.

And get the relevant library accrdoding to the your JDK.
Ex:- If your JDK is 64bit and Your OS is windows then download Windows-x64 library.



Open Eclipse and create a  new Project.

Create a new class called Test.

And add this code into it

import gnu.io.*;

import java.util.Enumeration;



public class Test {



public static void main(String[] args) {

   CommPortIdentifier serialPortId;
   Enumeration enumComm;

   enumComm = CommPortIdentifier.getPortIdentifiers();

   serialPortId = (CommPortIdentifier) enumComm.nextElement();
   System.out.println("Name "+serialPortId.getName()+" Type "+serialPortId.getPortType());
}
}


After You did that you can see error in import line.

 Open the zip file downloaded.

There is  3 files called
   RXTXcomm.jar
   rxtxParallel.dll
   rxtxSerial.dll

copy .dll files to your project's root folder.
             If you don't know where is the root folder then right click on the project name in left window.
             Select show in.
             Click system explorer.
             
             In here you can see the folder which named same as project name.
             Go in to it.
             Copy .dll files.

then create a folder in root folder called lib
Copy the  RXTXcomm.jar in to it.

Then in eclipse window right click in the project name click the refresh.

Right click in the project name and click properties.


In that window click the Libraries TAB.
Click add jars button.
Select the lib folder in it and select the RXTXcomm.jar
Press OK.



In Library window you can see the RXTXcomm.jar was added.
Click on its arrow.

Double Click native library location.
Now give the path to your root directory.

Errors will disappear.

Now we have to run our code.
Before that open device manager and click port section in the list.



It is for the verify program output.
Now run the code you will get the one of your COM port available.(Exactly the first port).


You can extend this code to get the all ports in the system.