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