Friday, April 1, 2016

That Stye in Eye..




Past two days had been really bad..... It's just because of one stye in eye... It's totally annoying... Irritating to the core how much ever I try to get rid of it it's just getting worse.... I feel even medicine isn't working and I feel I have to wait for a day more (hopefully) and just to watch it grow until it finally burst! 

I have always been paranoid about eyes it is because my dad is blind, he lost his eyes at very young age and if anything happens to anyones eyes naturally get one panic attack. 

So coming back to stye... Ooouch it hurts! Day -1 it started with a small pin drop. Day - 2 it grew and started hurting, took medicine, rest , avoided working for half day Day - 3 morning was worst.. Felt like conjunctivitis.. It was so big that I could hardly open one of my eye... Rushed to doc he said it will grow a day more... Missed meeting up with my friends....Wait and watch... 

Now as I'm not working today and they say idle mind is devil's workshop...lol.. Thoughts are running marathon.... In all possible directions... In the middle of all the thoughts I just paused and started thinking in different direction... I started associating the stye with real life goals.... If we had planned a goal/target for a day and it happens that a stye (obstacle) comes in such a way that no matter hard we try to get rid of it or try to avoid it by all possible means but it will hinder out our way towards our target. At that particular time we get so much pissed off, annoyed but it hardly helps. All we can do is to wait and watch and look out for the phase to pass. No point in bending the rod with bare hands, it will only hurt us. 

So consider such situations as a break from routine and learn to dance in rain. I have decided until my stye gets fine will stay at home play with my daughter and spend time with her which I usually missed while I'm at work.

Tuesday, November 4, 2014

Getting Started With Phonegap / Cordova




Before you Start your New Phonegap / Apache Cordova Project!

After about one and half year here's my new Blog Post, I need to blogged this out as I faced some Issues while setting up a new Phonegap OOps I should say a New Apache Cordova Project, and I will also write the reasons of facing these issues and I spent couple of hours understanding them and solving them, I hope I will help someone who is going through the same and might save couple of hours :)

Okay, So here it goes... I "used" to be a phonegap developer in 2010-2011 and did couple of projects back then, Even you will find some of my blog posts of those times, What was the usual way to start off the Phonegap Project back then, as In what way I use to follow learning from various other blogs and its documentation was a pretty simple and involved few basic steps:  Create a new Android Project In Eclipse, add phonegap jar in the Build path, and add Phonegap js to index.html in assets/www folder and there you go! It was enough to start with. Even the Phonegap jar and js were easily available for download from there site.

And Then when Phonegap became Apache Cordova, We need to follow the specific "steps", You will not find the Cordova jar and Cordova js easily available to download on there site. Also after 2011, I have hardly got the chance to work with phonegap (I worked on various CMS platforms), And recently when I started working with the Phonegap Project, I was thrilled that so much can changed in sometime, I realized that how important is to have in touch with the technologies which we are working!   

So, Now going ahead, Its been wonderfully documented on there site, I will be summarize the basic steps, which will be required to install phonegap, (Yes you heard it right! you will need to install phonegap you will no longer served with the ready-made download! ),


1.Node.js
Yes! to install and use Phonegap / Cordova you will need to install Node.js, It is very easy to install,
Just go there site, http://nodejs.org/ Click on Install button, and it will do the rest for you.

2. To Install Phonegap on your system, Type in the following command In Terminal,

sudo npm install -g phonegap

(For windows, eliminate the sudo command).

For  Installing Cordova,

sudo npm install -g cordova
 
As you write sudo command in Linux and Mac System it will prompt you to enter root password before beginning the installation.

3. To create a new Cordova Project,

Now Navigate to the directory where you wish to create the new Cordova Project, and execute the following command in terminal,

$ cordova create hello com.example.hello HelloWorld

This will create the new Blank Cordova Project by the name 'HelloWorld' in Specified directory,  com.example.hello is the package name of the application and hello is the base directory name.

Following is the base directory structure,




4. Adding Platforms,

To Add Platform, we need to navigate inside the project directory, Type in the following command to do so,

$ cd hello 

In The above step, the blank project is being created, Now we need to add platforms which we intend to Target, As I was intending to target Android & iOS, I have added those two platforms, you can also add various platforms like windows, blackberry etc as per your requirements,

To Add iOS Platform, Type this command in terminal,

$ cordova platform add ios

Directory Structure of iOS Project will be as follows,



This will add the basic hello world iOS project inside platforms directory, The project created is XCode ready Project, you can directly import to Xcode and get started!

To Add Android Platform, Type this command in terminal,

$ cordova platform add android

Directory Structure of Android Project will be as follows,



This will be the basic Hello World Android Project inside platforms directory, The Project created is Eclipse Ready Project ready to be Imported to Eclipse, Remember after importing the project in Eclipse add the Reference of CordovaLib to the Project, This CordovaLib is present in the same directory.

Also one thing to be taken care of is to remember the ANDROID_HOME should be set to your path variable, If it is not set then above command will fail to execute, to set ANDROID_HOME in environment PATH, proceed with following commands,

export ANDROID_HOME = <Path to android sdk>

export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH


So Now You are done with the Creating Basic Cordova Development to get you started with your desired Platform.

Following this structure and steps will be very helpful in you wish to plan to add various basic plugins like InAppBrowser, AdMob etc to your Cordova Projects.

I hope this Article will be helpful to People who want to get started with Apache Cordova.

That is all for now.

Will be back again with some useful stuff soon!

Happy Blogging :)

-Mayuri


Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here








Tuesday, July 23, 2013

SQLite Android Example

Hello Friends,

Since Long time I was awaiting to write SQLite sample in my blogs, and finally here it is!

This is a simple example where in there are 2 screens, first one to add the entries of students name and subjects marks and then to view the entries in the next page.

There is a class 'DatabaseHandler' which extends 'SQLiteOpenHelper' where code to create database, tables, add new record, fetch records etc resides.

Data is displayed in ListView using ListView adapter.

Following code for the layout files and Java Files For App:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name" />
    <EditText
        android:id="@+id/etstdname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText>  
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Physic" />
    <EditText
        android:id="@+id/etphysics"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText> 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Biology" />
    <EditText
        android:id="@+id/etbiology"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText> 
    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chemistry" />
    <EditText
        android:id="@+id/etchemistry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
   </EditText>
    <Button
        android:id="@+id/btnsave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />
    <Button
        android:id="@+id/btncheckdata"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Data" />
</LinearLayout>


listview_row.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">  
    <TextView
        android:id="@+id/FirstText"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="First" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>
    <TextView
        android:id="@+id/SecondText"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Second" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>      
    <TextView
        android:id="@+id/ThirdText"
        android:layout_width="0dp"
        android:layout_height="match_parent"      
        android:text="Third" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>          
    <TextView
        android:id="@+id/FourthText"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Fourth" android:gravity="center"
        android:background="@drawable/shape"
        android:layout_weight="1">
    </TextView>
</LinearLayout>

activity_display_data.xml

 <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".DisplayData" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Student Info"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:background="@android:color/white" />
    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Back" />  
</RelativeLayout>

MainActivity.java

package com.example.sqlitedemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText etname, etchemistry, etbiology, etphysics;
    Button save, display;
    String name, biology, physic, chemistry;
    DatabaseHandler db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);       
        etname = (EditText)findViewById(R.id.etstdname);
        etchemistry = (EditText)findViewById(R.id.etchemistry);
        etbiology = (EditText)findViewById(R.id.etbiology);
        etphysics = (EditText)findViewById(R.id.etphysics);       
        save = (Button)findViewById(R.id.btnsave);
        display = (Button)findViewById(R.id.btncheckdata);   
       
        save.setOnClickListener(new View.OnClickListener() {           
            @Override
            public void onClick(View v) {               
                name = etname.getText().toString();
                biology = etbiology.getText().toString();
                chemistry = etchemistry.getText().toString();
                physic = etphysics.getText().toString();               
                db = new DatabaseHandler(getApplicationContext());               
                db.addContact(new Student(name, biology, chemistry, physic));
                Toast.makeText(getApplicationContext(), "Value Added", Toast.LENGTH_SHORT).show();
            }
        });       
            display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                       
                Intent i = new Intent(MainActivity.this, DisplayData.class);
                startActivity(i);
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {       
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Student.java

package com.example.sqlitedemo;

public class Student {
   
    int id;
    String name, biology, chemistry, phyics;
   
    public Student()
    {
       
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBiology() {
        return biology;
    }

    public void setBiology(String biology) {
        this.biology = biology;
    }

    public String getChemistry() {
        return chemistry;
    }

    public void setChemistry(String chemistry) {
        this.chemistry = chemistry;
    }

    public String getPhyics() {
        return phyics;
    }

    public void setPhyics(String phyics) {
        this.phyics = phyics;
    }

    public Student(String name, String biology, String chemistry,
            String phyics) {
        super();   
        this.name = name;
        this.biology = biology;
        this.chemistry = chemistry;
        this.phyics = phyics;
    }   

}

DatabaseHandler.java

package com.example.sqlitedemo;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "studentdetail";
    private static final String TABLE_STUDENTS = "students";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PHYSICS = "physics";
    private static final String KEY_CHEMISTRY = "chemistry";
    private static final String KEY_BIOLOGY = "biology";
           
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
  
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_STUDENTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT, "
                + KEY_BIOLOGY + " TEXT, " + KEY_CHEMISTRY + " TEXT, " +
                   KEY_PHYSICS + " TEXT" + ")";       
        db.execSQL(CREATE_CONTACTS_TABLE);
        }
  
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {      
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);      
        onCreate(db);
    }
    
    void addContact(Student student) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, student.getName());
        values.put(KEY_BIOLOGY, student.getBiology());
        values.put(KEY_CHEMISTRY, student.getChemistry());
        values.put(KEY_PHYSICS, student.getPhyics());       
        db.insert(TABLE_STUDENTS, null, values);
        db.close();
    }
     
    public List<Student> getAllDetails() {
        List<Student> studentList = new ArrayList<Student>();      
        String selectQuery = "SELECT  * FROM " + TABLE_STUDENTS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
       if (cursor.moveToFirst()) {
            do {
                Student student = new Student();
                student.setId(Integer.parseInt(cursor.getString(0)));
                student.setName(cursor.getString(1));
                student.setBiology(cursor.getString(2));
                student.setChemistry(cursor.getString(3));                        
                student.setPhyics(cursor.getString(4));              
                studentList.add(student);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return studentList;
    }

}
listviewAdapter.java

package com.example.sqlitedemo;

import static com.example.sqlitedemo.Constant.STUD_NAME;
import static com.example.sqlitedemo.Constant.BIOLOGY;
import static com.example.sqlitedemo.Constant.PHYSICS;
import static com.example.sqlitedemo.Constant.CHEMISTRY;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
       

public class listviewAdapter extends BaseAdapter
{
    public ArrayList<HashMap> list;
    Activity activity;

    public listviewAdapter(Activity activity, ArrayList<HashMap> list) {
        super();
        this.activity = activity;
        this.list = list;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }
    private class ViewHolder {
       TextView txtFirst;
       TextView txtSecond;
       TextView txtThird;
       TextView txtFourth;    
      }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                LayoutInflater inflater =  activity.getLayoutInflater();
                if (convertView == null){
                    convertView = inflater.inflate(R.layout.listview_row, null);
                    holder = new ViewHolder();
                    holder.txtFirst = (TextView) convertView.findViewById(R.id.FirstText);
                    holder.txtSecond = (TextView) convertView.findViewById(R.id.SecondText);
                    holder.txtThird = (TextView) convertView.findViewById(R.id.ThirdText);
                    holder.txtFourth = (TextView) convertView.findViewById(R.id.FourthText);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();       
                }           
                HashMap map = list.get(position);
                holder.txtFirst.setText(""+map.get(STUD_NAME));
                holder.txtSecond.setText(""+map.get(BIOLOGY));
                holder.txtThird.setText(""+map.get(PHYSICS));
                holder.txtFourth.setText(""+map.get(CHEMISTRY));
                return convertView;
    }
}
class Constant {
    public static final String STUD_NAME = "First";
    public static final String BIOLOGY = "Second";
    public static final String PHYSICS = "Third";
    public static final String CHEMISTRY = "Fourth";

}


DisplayData.java

package com.example.sqlitedemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.sqlitedemo.Constant.STUD_NAME;
import static com.example.sqlitedemo.Constant.BIOLOGY;
import static com.example.sqlitedemo.Constant.PHYSICS;
import static com.example.sqlitedemo.Constant.CHEMISTRY;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class DisplayData extends Activity {
    private ArrayList<HashMap> list;
    Button home;       
    String[] problemgrid = null;
    List<String>getnumbers =null;   
    ListView lview;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        setContentView(R.layout.activity_display_data);       
        lview = (ListView) findViewById(R.id.listview);
        populateList();
        listviewAdapter adapter = new listviewAdapter(this, list);   
        lview.setAdapter(adapter);       
        home = (Button)findViewById(R.id.button1);
        home.setOnClickListener(new View.OnClickListener() {           
            @Override   
            public void onClick(View v) {       
                Intent i = new Intent(DisplayData.this, MainActivity.class);                       
                finish();
                startActivity(i);
            }
        });     
   }       
    private void populateList() {
        list = new ArrayList<HashMap>();
        HashMap temp1 = new HashMap();
        temp1.put(STUD_NAME, "Stud Name");
        temp1.put(BIOLOGY, "Biology");
        temp1.put(PHYSICS, "Physics");
        temp1.put(CHEMISTRY, "Chemistry");
        list.add(temp1);       
     DatabaseHandler dbresult = new DatabaseHandler(getApplicationContext());       
     List<Student> recdata = dbresult.getAllDetails();   
         for (Student cn : recdata) {          
             String name = cn.getName();
            String biology = cn.getBiology();
            String physics = cn.getPhyics();
            String chemistry = cn.getChemistry();           
                HashMap temp = new HashMap();
                temp.put(STUD_NAME, name);
                temp.put(BIOLOGY, biology);
                temp.put(PHYSICS, physics);
                temp.put(CHEMISTRY, chemistry);       
                list.add(temp);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {   
        getMenuInflater().inflate(R.menu.display_data, menu);
        return true;
    }
}

The Screenshots of the Application is as Follows,






To Verify the Data in database, Go To File Explorer Window for Eumlator, In your IDE, browse to the data/data/<package name> /databases/ , here you will see the database file created as follows,


 Pull this file from the emulator and view the file in SQLite database browser you can fire the query and verify your table structure and data as follows,


 
That is all from my end from now.

Happy Coding!

~Mayuri


Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here



Friday, July 12, 2013

Android PhoneGap Login Example with JQuery-Ajax & Java/Servlet/JDBC

Hello Friends,

Following Example Illustrates the Login Functionality Implemented in simplest form using Phonegap.

Following is the Algo/Logic used in the Sample Application,
  • From the Phonegap app, User Enters User Name & Password,
  • From the app, JQuery-Ajax Request is made to the Servlet, Sending username & password as parameters,
  • Servlet Accepts the Parameters, Then Connects to Remote Database using JDBC and fetches Username and Passwords,
  • Matches the username and password from parameters and those fetched from database,
  • If credentials matches writes Response as "SUCCESS" else "FAIL"
  • At the Client side i.e. Phonegap App, Appropriate Alert message is shown depending on the Response Got from Servlet.

Following is the Server Side - Servlet Snippet Code,  

response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection con = null;
        ResultSet resultSet = null;      
        String param_uname = request.getParameter("uname");
        String param_pwd = request.getParameter("pwd");
        try {
            Class.forName("<DB Driver>").newInstance();
            String url = "<DB URL>";
            con = DriverManager.getConnection(url);
            String query = null;
            query = "SELECT * from APP.LOGIN";
            PreparedStatement statement = con.prepareStatement(query);
            resultSet = statement.executeQuery();
            String db_uname="";
            String db_pwd="";           
            while (resultSet.next()) {
                db_uname = resultSet.getString("UNAME");
                db_pwd = resultSet.getString("PWD");                                       
             }
            if( (param_uname.equals(db_uname)) && (param_pwd.equals(db_pwd))){
                   out.write("SUCCESS");
            } else {
                out.write("FAIL");
            }        
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

Following is the Snippet Of The HTML Code for PhoneGap Application,

    <div data-role="content" id="input_login">
        <ul data-role="listview" data-divider-theme="b" data-inset="true">
            <li data-role="list-divider" role="heading">
                User Name
            </li>           
             <li data-role="list-divider" >
                <input type="text" id="txt_username"/>
            </li>           
            <li data-role="list-divider" role="heading">
                Password
            </li>            
             <li data-role="list-divider" >
                <input type="password" id="txt_pwd"/>
            </li>           
             <li data-role="list-divider" >
                <input type="button" id="btn_login" value="Login" onclick="javascript:verifyLogin();"/>
            </li>            
        </ul>
    </div>

Following is the JavaScript Function / Code,

function verifyLogin(){       
    var uname=document.getElementById("txt_username").value;
    var pwd=document.getElementById("txt_pwd").value;   
      $.ajax({
            type : 'POST',          
            url : /Login', // Servlet URL          
            data:{
                'uname':uname,
                'pwd':pwd
            },
            success : function(data) {           
                if("SUCCESS"==data){                    
                    alert("Login Success!!");
                } else {                   
                    alert("Invalid Login!!");
                }
            },
            error : function(xhr, type) {
                alert('server error occurred');
            }
      });   
}

Following are the Screenshots For the Application,



I Hope this example will be useful for people learning PhoneGap,

Happy Coding!!

~Mayuri




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here



Wednesday, July 3, 2013

Dynamic Chart Using Google Chart API, Jquery Ajax, JDBC & JSON

Hello Friends,

I was exploring and playing with the codes of various Charts APIs since many days, First it was JFreeChart for Java Applications attracted my attention and I loved using the same. Then I started looking upon JavaScript based Charting APIs and while Googling about the same what caught my eye was Google Chats. I have also mentioned in my earlier posts that I'm a Big Fat fan of Google and love using their APIs.

Regarding Google Charts, so I started to explore Google Charts, tried those extremely simple yet useful examples given for various types of charts pie, bar, line etc...and without any setup needed they worked like WOW! 

Now the thought came to me that using this examples, I need my JavaScript client side charts to display the data stored at remote database at server, And so I started my work to accomplish this.

What I did was created a Java Srevlet which connects to my database, get the data from table, converts the data to JSON Format and sends the same as a Response, And At Client Side, Jquery - Ajax Function which will call this Servlet, Gets the data which is returned as Response, parse the Json Data to javascript array which is being used by Google Chart API to Display Charts.

Following Is the HTML / JavaScript Client Side Code,

<html>
    <head>
        <script type="text/javascript" src="js/json2.js"></script>
        <script type="text/javascript" src="js/jsonStringify.js"></script>
        <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            ////////////// Getting data from server
            var queryObject="";
            var queryObjectLen="";
            $.ajax({
                type : 'POST',
                url : 'http://localhost:8084/GoogleChartTest/GetStudentData',
                dataType:'json',
                success : function(data) {
                    queryObject = eval('(' + JSON.stringify(data) + ')');
                    queryObjectLen = queryObject.studDetails.length;
                },
                error : function(xhr, type) {
                    alert('server error occoured')
                }
            });
            var arrdata="";
            google.load("visualization", "1", {packages:["corechart"]});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                arrdata = new google.visualization.DataTable();
                arrdata.addColumn('string', 'Names');
                arrdata.addColumn('number', 'Physics');
                arrdata.addColumn('number', 'Chemistry');
                arrdata.addColumn('number', 'Biology');
                for(var i=0;i<queryObjectLen;i++){
                    var studname = queryObject.studDetails[i].studname;
                    var physics = queryObject.studDetails[i].physics;
                    var chemistry = queryObject.studDetails[i].chemistry;
                    var biology = queryObject.studDetails[i].biology;
                    arrdata.addRows([
                        [studname,parseInt(physics),parseInt(chemistry),parseInt(biology)]
                    ]);
                }
                var options = {
                    title: 'Students Performance'
                };
                var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
                chart.draw(arrdata, options);
            }
        </script>
    </head>
    <body>
        <div id="chart_div" style="width: 900px; height: 500px;"></div>
    </body>
</html>

Following is the Server Side Servlet Code Snippet, 


PrintWriter out = response.getWriter();
        Connection con = null;
        ResultSet resultSet = null;
        List<JSONObject> studDetails = new LinkedList<JSONObject>();
        JSONObject responseObj = new JSONObject();
        
            Class.forName("<jdbc driver>").newInstance();
            String url = "<jdbc url>";
            con = DriverManager.getConnection(url);
            String query = null;
            query = "SELECT * from APP.STUDENTS";
            PreparedStatement statement = con.prepareStatement(query);
            resultSet = statement.executeQuery();
            JSONObject studObj = null;
            while (resultSet.next()) {
                String studname = resultSet.getString("studname");
                String physics = resultSet.getString("physics");
                String chemistry = resultSet.getString("chemistry");
                String biology = resultSet.getString("biology");
                studObj = new JSONObject();
                studObj.put("studname", studname);
                studObj.put("physics", physics);
                studObj.put("chemistry", chemistry);
                studObj.put("biology", biology);
                studDetails.add(studObj);
            }
            responseObj.put("studDetails", studDetails);

            out.write(responseObj.toString());


And Finally, The O/P,  i.e. chart is as follows,


Preview of the Data in the Database table from which the chart is displayed is as follows,



That is All From my end for now, just thought of sharing what I did so could be useful for somebody.

Happy Coding!

~ Mayuri :)

Monday, July 1, 2013

JFreeChart - Dynamic Chart Example

Hello Friends,

I'm back again with one of the example of JFreeChart, one of the widely used charting APIs in Java.

 This is the simple example illustrates the power of Java Charting using JFreeCharts.

 This example has following features:
  •   Displays Students Results in line chart.
  •   X-Axis corresponds to Subjects
  •  Y-Axis corresponds to Marks secured
  •  Each line that is plot on the chart represents each student.
  •  Chart is dynamically populated from the values extracted from database.
  •  Student Wise Dropdown is present

Following is the Code For the example,

package com.mayuri.example;
   
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;

public class ChartDemoAppletDb extends JApplet {
ChartPanel chartPanel;
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    @Override
    public void init() {
        createDataset("All");
        chartPanel = createChart();
        chartPanel.setMouseWheelEnabled(true);
        chartPanel.setHorizontalAxisTrace(true);
        chartPanel.setVerticalAxisTrace(true);
        chartPanel.setZoomTriggerDistance(10);
        setLayout(new BorderLayout(0, 5));
        add(chartPanel, BorderLayout.CENTER);
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        panel.add(studentsWise());
        panel.add(restoreZoom());
        panel.add(enableTrace());
        panel.add(disableTrace());
        add(panel, BorderLayout.SOUTH);
    }
private JButton restoreZoom() {
        final JButton restore = new JButton(new AbstractAction("Restore") {
            @Override
            public void actionPerformed(ActionEvent e) {
                chartPanel.restoreAutoBounds();
            }
        });
        return restore;
    }


private JButton enableTrace() {
        final JButton traceEnabled = new JButton(new AbstractAction("Enable Trace") {
            @Override
            public void actionPerformed(ActionEvent e) {
                 chartPanel.setHorizontalAxisTrace(true);
                 chartPanel.setVerticalAxisTrace(true);
                 chartPanel.repaint();
            }
        });
        return traceEnabled;
    }
private JButton disableTrace() {
        final JButton traceDisabled = new JButton(new AbstractAction("Disable Trace") {
            @Override
            public void actionPerformed(ActionEvent e) {
                 chartPanel.setHorizontalAxisTrace(false);
                 chartPanel.setVerticalAxisTrace(false);
                 chartPanel.repaint();
            }
        });
        return traceDisabled;
    }
private JComboBox studentsWise() {
        final JComboBox studentsNames = new JComboBox();
        ArrayList<String> studNameList = new ArrayList<String>();
        DataProvider dataProvide = new DataProvider();
        studNameList = dataProvide.getStudentsNames();
        studentsNames.setModel(new DefaultComboBoxModel(studNameList.toArray()));
        studentsNames.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if ("All".equals(studentsNames.getSelectedItem())) {
                dataset.clear();
                 createDataset("All");
                } else {
                    String selstudname = studentsNames.getSelectedItem().toString();
                    dataset.clear();
                    createDataset(selstudname);
                }
            }
        });
        return studentsNames;
    }
     private ChartPanel createChart() {
        JFreeChart chart = ChartFactory.createLineChart(
            "Students Results",
            "Subjects",
            "Marks",
            dataset,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
            );       
        chart.setBackgroundPaint(Color.PINK);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.CYAN);
        plot.setRangeGridlinePaint(Color.BLACK);
        LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        renderer.setShapesVisible(true);
        renderer.setDrawOutlines(true);
        renderer.setUseFillPaint(true);
        return new ChartPanel(chart);
    }
private void createDataset(String condition) {
        Connection connect = null;
        ResultSet resultSet = null;
  try{
    DataProvider dataProvide = new DataProvider();
    connect = dataProvide.getDbConnection();
    String query = null;
    if("All".equals(condition)){
    query="SELECT * from APP.STUDENTS";
    } else {
    query="SELECT * from APP.STUDENTS WHERE STUDNAME = '"+condition+"'";
    }  

    PreparedStatement statement = connect.prepareStatement(query);
      resultSet = statement.executeQuery();
      while (resultSet.next()) {
        String studname = resultSet.getString("studname");
        String physics = resultSet.getString("physics");
        String chemistry = resultSet.getString("chemistry");
        String biology = resultSet.getString("biology");
        dataset.addValue(Integer.parseInt(physics), studname, "physics");
        dataset.addValue(Integer.parseInt(chemistry), studname, "chemistry");
        dataset.addValue(Integer.parseInt(biology), studname, "biology");
      }
      }catch(Exception e) {
          e.printStackTrace();
      }
    }
}

    class DataProvider {
        public Connection getDbConnection(){
        Connection con = null;
        try{
            Class.forName("<JDBC Driver>").newInstance();
            String url = "<DB URL>";
            con = DriverManager.getConnection(url);
            }
        catch(Exception e){
            e.printStackTrace();
        }
        return con;
    }

    public ArrayList<String> getStudentsNames(){
        ArrayList<String> studNameList = new ArrayList<String>();
        Connection connect = getDbConnection();
        ResultSet resultSet = null;
        try{
            studNameList.add("All");
            Statement stmt = connect.createStatement();
            String query = "SELECT STUDNAME from APP.STUDENTS ";
            resultSet = stmt.executeQuery(query);
            while(resultSet.next()){
                studNameList.add(resultSet.getString("studname"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return studNameList;
    }
}

Screenshots For the Database Table and output for the above code is as follows,





 I hope this example will be useful to to some of people Googling about JFreeChart :)

Happy Coding!

~Mayuri