Wednesday, 20 March 2013

PieChart using AChartEngine

AChartEngine is now the most widely used jar in the world to draw various types of following charts.

            1. Graphical chart
            
            2. Line chart

            3. Bar chart

            4. Scatter chart

            5. Time chart

            6. Pie chart

This article is about draw pie chart using achartengine.

Sample screen shot of pie chart drawn using achartengine.


This pie chart has the following options.

        1. Movable

        2. Zoomable

        3. Clickable

To draw this chart first you have to import achartengine jar into your project folder. If you are using eclipse  then right click on your project --> Build Path --> Configure Build Path --> Libraries tab --> Add External JARs. This is the way to import external jars into our project.

Coding:

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/chart"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal" >
    </LinearLayout>

</LinearLayout>


AChartEnginePieChartActivity.java

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AChartEnginePieChartActivity extends Activity { 

private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };

private static double[] VALUES = new double[] { 10, 11, 12, 13 };

private static String[] NAME_LIST = new String[] { "A", "B", "C", "D" };

private CategorySeries mSeries = new CategorySeries("");

private DefaultRenderer mRenderer = new DefaultRenderer();

private GraphicalView mChartView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);

for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}

if (mChartView != null) {
mChartView.repaint();
}

}

@Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);

mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();

if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was clicked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});

mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was long pressed", Toast.LENGTH_SHORT);
return false; 
} else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT);
return true;       
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
else {
mChartView.repaint();
}
}
}

Related article Pie Chart in Android without using external jar

Thank You

Monday, 11 March 2013

SQLite Database Example

This is simple sqlite database tutorial without using External database. If you want to know how use external database in android then please click me!
To create and access a table in android using SQLite is very simple. The following method will show how to create a table and see column names of that table in android.
public void table1() {

  db = this.getWritableDatabase();

  db.execSQL("CREATE TABLE IF NOT EXISTS table1(id INTEGER PRIMARY KEY AUTOINCREMENT , description TEXT)");
  // to see colomn names in our table1
  Cursor t = db.rawQuery("PRAGMA TABLE_INFO(table1)", null);
  if (t.moveToFirst()) {
   do {
    Log.i("", t.getString(0) + " " + t.getString(1));
   } while (t.moveToNext());
  }
  t.close();
  db.close();

 }
And the following sample code is used to insert data into table.
public void inserIntoTable1(String desc) {

  db = this.getWritableDatabase();
  ContentValues cv = new ContentValues();
  try {
   db.beginTransaction();
   cv.put("description", desc);
   db.insert("table1", null, cv);
   db.setTransactionSuccessful();

  } catch (Exception ex) {

  } finally {
   db.endTransaction();
   db.close();
  }
 }
And the following code is used to access data from our table. The method will return data as list.
public List<String> getData() {
  db = this.getReadableDatabase();
  List<String> data = new ArrayList<String>();
  Cursor c = db.rawQuery("SELECT * FROM table1", null);
  while (c.moveToNext()) {
   data.add(c.getString(1));
  }
  c.close();
  db.close();
  return data;
 }
Now we can populate those data into our listview.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, list); 
  mylist = (ListView) findViewById(R.id.listView1);
  mylist.setAdapter(adapter);
Full code. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

<LinearLayout>
DBHelper.java
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;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

 final static String dbname = "Sample";
 SQLiteDatabase db;

 public DBHelper(Context context) {
  super(context, dbname, null, 1);
  // TODO Auto-generated constructor stub
 }

 public void table1() {

  db = this.getWritableDatabase();

  db.execSQL("CREATE TABLE IF NOT EXISTS table1(id INTEGER PRIMARY KEY AUTOINCREMENT , description TEXT)");
  // to see colomn names in our table1
  Cursor t = db.rawQuery("PRAGMA TABLE_INFO(table1)", null);
  if (t.moveToFirst()) {
   do {
    Log.i("", t.getString(0) + " " + t.getString(1));
   } while (t.moveToNext());
  }
  t.close();
  db.close();

 }

 public void inserIntoTable1(String desc) {

  db = this.getWritableDatabase();
  ContentValues cv = new ContentValues();
  try {
   db.beginTransaction();
   cv.put("description", desc);
   db.insert("table1", null, cv);
   db.setTransactionSuccessful();

  } catch (Exception ex) {

  } finally {
   db.endTransaction();
   db.close();
  }
 }

 public List<String> getData() {
  db = this.getReadableDatabase();
  List<String> data = new ArrayList<String>();
  Cursor c = db.rawQuery("SELECT * FROM table1", null);
  while (c.moveToNext()) {
   data.add(c.getString(1));
  }
  c.close();
  db.close();
  return data;
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
 }

 @Override
 public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
  // TODO Auto-generated method stub

 }

}

SQLiteActivity.java
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class SQLiteActivity extends Activity {

 DBHelper dbhelper;
 Button save;
 EditText discription;
 ListView mylist;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  dbhelper = new DBHelper(this);

  accessTable1();
  loadMyList();
 }

 private void accessTable1() {
  dbhelper.table1();
  discription = (EditText) findViewById(R.id.editText1);
  save = (Button) findViewById(R.id.button1);
  save.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    dbhelper.inserIntoTable1(discription.getText().toString());
    loadMyList();
   }
  });
 }

 private void loadMyList() {
  List<String> list = dbhelper.getData();
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, list); 
  mylist = (ListView) findViewById(R.id.listView1);
  mylist.setAdapter(adapter);
 }
}


Reduce your work by using SQLiteHelper.jar

sample screen shot

 

Thank You

Tuesday, 5 March 2013

SQLite Databases using External DB


This is tutorial for accessing external DB from assets folder. In android We can create sqlite database by using SQLite Database Browser. Now the question is how to access this database in source code. The answer is very simple. Store the database in assets folder that is placed in project folder.


Then we can access this database in dbhelper class using

context.getAssets().open(DB_NAME);

After this we should copy this database to our root directory. Why because our SQLiteOpenHelper reads data from root directory only. for this we have to open new empty file in root directory by using.
private String DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
String DB_NAME = "database";
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
then we have to copy our data to this empty file by using.
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

Now we can access our data from root directory db to our project easily. Sample project to implement external sqlite database access in android.

DBHelper.java
package com.android.sqlite;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

 private static String DB_NAME = "database";
 private SQLiteDatabase db;
 private final Context context;
 private String DB_PATH;

 public DBHelper(Context context) {
  super(context, DB_NAME, null, 1);
  this.context = context;
  DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
 }

 public void createDataBase() throws IOException {

  boolean dbExist = checkDataBase();
  if (dbExist) {

  } else {
   this.getReadableDatabase();
   try {
    copyDataBase();
   } catch (IOException e) {
    throw new Error("Error copying database");
   }
  }
 }

 private boolean checkDataBase() {
  File dbFile = new File(DB_PATH + DB_NAME);
  return dbFile.exists();
 }

 private void copyDataBase() throws IOException {

  InputStream myInput = context.getAssets().open(DB_NAME);
  String outFileName = DB_PATH + DB_NAME;
  OutputStream myOutput = new FileOutputStream(outFileName);
  byte[] buffer = new byte[1024];
  int length;
  while ((length = myInput.read(buffer)) > 0) {
   myOutput.write(buffer, 0, length);
  }

  // Close the streams
  myOutput.flush();
  myOutput.close();
  myInput.close();

 }

 public Cursor getData() {
  String myPath = DB_PATH + DB_NAME;
  db = SQLiteDatabase.openDatabase(myPath, null,
    SQLiteDatabase.OPEN_READONLY);
  Cursor c = db.rawQuery("SELECT * FROM master", null);
   // Note: Master is the one table in External db. Here we trying to access the records of table from external db.
  return c;
 }

 @Override
 public void onCreate(SQLiteDatabase arg0) {
  // TODO Auto-generated method stub
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
 }
}

And
ExternalDBActivity.java
package com.android.sqlite;

import java.io.IOException;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ExternalDBActivity extends Activity {
 /** Called when the activity is first created. */
 DBHelper dbhelper;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  String[] from = new String[] { "_id", "columnName1", "columnName2" };
  int[] to = new int[] { R.id.TextView1, R.id.TextView2, R.id.TextView3 };

  dbhelper = new DBHelper(this);
  try {
   dbhelper.createDataBase();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  Cursor c = dbhelper.getData();
  
  SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    getApplicationContext(), R.layout.list, c, from, to);
  
   ListView list = (ListView) findViewById(R.id.ListView1);
  
   list.setAdapter(adapter);
 }
}

main.xml
<?xml version="1.0" encoding="utf-8"?<
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" <

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" <
    </ListView<

</LinearLayout<
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/TextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/TextView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />

</LinearLayout>
Related article How to create and use SQLite database dynamically

Reduce your work by using SQLiteHelper.jar

Thank You