Pages

Android Beyond Basics

This tutorial assumes you are familiar with the basic android programming. Lets move to a little higher form of android programming. In this tutorial we will cover.
  • Multiple activity call and parameter passing.
  • Database(SQLite) with android
  • List adapter
  • Menu and click handle
So without wasting any time lets begin the Journey.
We are going to build a List-managing App. You are going to build an app which will be able to show you a large and nested list.
The steps for the generation of application are :-
  1. Create a new Android Project.
  2. Add another activity for data insertion.
  3. Add menu (to MainActivity).
  4. Capture click events.
  5. Design Database
  6. Create a database Helper for your particular object.(CRUD operations)
  7. Display Saved lists in the MainActivity.
The flow of the app is like this.



At the Start of the App, the very top level of the list will appear. Clicking on the particular list will take you to the immediate children. You can create a new list-Item Under the current Item by clicking the Add button on the top Action Menu and the fourth Activity with option to insert a title and content will appear.
1. Create a new Android Project.
This tutorial assumes you are familiar with the very basics. Just click on the File->New->Project->Android Project. You will also create an Activity in this phase. Name this as MainActivity. Set the package Name to com.ktm.listapp.
2. Add another activity for data insertion.
There are two activities in this Application. One is to show the List-Items and another activity is to insert a new List Item. Add another java class in the same package. Name it ListAddActivity.java and extend it from android.app.Activity class. Create a layout for this Activity. It needs a label "Title" and then a EditText item then again a TextView "Content" and then again a EditText component. Finally two buttons, one for Save and another for cancel. Add a xml file on the res->layout folder named list_add.xml and paste the following code.
<?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:orientation="vertical" >

    <TextView
        android:id="@+id/titleLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/contentLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Content"
        android:layout_marginTop="5dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="40"
        android:inputType="textMultiLine" />

    <Button
        android:id="@+id/saveButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save"
        android:onClick="onSave"
         />
    <Button
        android:id="@+id/cancelButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:onClick="onCancel"
         />

</LinearLayout>

Note the onClick methods. This is where we bind the click event of the button with a method in the corresponding activity. The ListAddActivity.java looks like this.
public class ListAddActivity extends Activity {

    Integer parent_id;

    private EditText title;
    private EditText content;

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

        parent_id = getIntent().getExtras().getInt("parent_id");
        title = (EditText) findViewById(R.id.title);
        content = (EditText) findViewById(R.id.content);
    }

    public void onSave(View view){
        String titleText = title.getText().toString();
        String contentText = content.getText().toString();
        ListOpenHelper loh = new ListOpenHelper(this);

        loh.insertItem(new ListItem(titleText, contentText, parent_id));
        finish();
    }

    public void onCancel(View view){
        finish();
    }

}

In the onCreate Method You see parent_id getting assigned by extra parameter passed to it by the Intent. Actually this Activity is called from the first Activity and One extra parameter is passed, indicating the current context and parentList_id under which the new listItem is being saved. We will see how we pass the parameter after a few mements.
3.Add Menu
In the first three activity-images, you can see a + signed image in the Action bar. First you need to add this image or similar one res->drawable-mdpi folder of the project. Name the image as ic_add.png (all-small letters). In the res->menu folder add a xml file named activity_main.xml. Paste the given code.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings"
android:title="@string/menu_settings"
android:orderInCategory="100"
android:showAsAction="never" />
<item android:id="@+id/new_list"
android:icon="@drawable/ic_add"
android:title="Add"
android:showAsAction="ifRoom" />
</menu>

Up to now Your MainAcvivity.java class looks like this.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

4. Capture Click event.
After step 3, You will see a button in the ActionBar of MainActivity. What we need to do is bind the click event with a method in the MainActivity.java so that the method will start ListAddActivity.java. Add this method to the MainActivity class.
Integer id = -1;// at the top
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
        case R.id.new_list:
            addNewList();
            return true;
        case R.id.menu_settings :
            return true;
        default:
            return false;
        }
    }
 public void addNewList(){
        Intent i = new Intent(getBaseContext(), ListAddActivity.class);
        i.putExtra("parent_id", this.id);
        startActivity(i);
    }

This class contains all the Crud operations you need for now. We shold also add a ListItem.java as the list object. Create another package com.ktm.listapp.objects and add class ListItem.java with following code.
package com.ktm.listapp.objects;

public class ListItem {
    Integer id = 0;
    String  title = "TITLE";
    String  content = "CONTENT";
    Integer parent_id = null;
    
    public ListItem(){};
    public ListItem(Integer id, String title, String content, Integer parent_id){
        this.id = id;
        this.title = title;
        this.content = content;
        this.parent_id = parent_id;
    }
    
    public ListItem (String title, String content, Integer parent_id){
        this.title = title;
        this.content = content;
        this.parent_id = parent_id;
    }
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getParent_id() {
        return parent_id;
    }
    public void setParent_id(Integer parent_id) {
        this.parent_id = parent_id;
    }
}

5. Design Database.
Now that we have the two activities ready. We see blank activity and a action-bar button. We click on it and another activity appears with an option to insert title, content and click save , cancel. We need to do some database operations on those click events. Our ListItem has the following properties.
ListItem(id integer, title text, content text, parent_id integer)

6. Create DatabaseHelper for your particular Object.
So we create a package called com.ktm.listapp.database and create a class ListDatabaseHelper.java
package com.ktm.listapp.database;
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;

import com.ktm.listapp.objects.ListItem;

public class ListDatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "LISTAPPDB";
    public static final String LIST_TABLE_NAME = "LISTAPP";
    // queries
    public static final String TABLE_CREATE_QUERY = 
            "CREATE TABLE "    + LIST_TABLE_NAME + "(" +
                " list_id integer primary key autoincrement default 0, "
            +      "title text, "
            +      "content text, " 
            +      "parent_id integer " 
            + ")";

    public ListDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null , DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            //db.execSQL("Drop table " + LIST_TABLE_NAME);
            db.execSQL(TABLE_CREATE_QUERY);
        } catch (Exception e) {
            Log.i(LIST_TABLE_NAME, "tables already exist");
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + LIST_TABLE_NAME);

        // Create tables again
        onCreate(db);
    }

    //CRUD operations
    public void deleteAll(){

        SQLiteDatabase db = getWritableDatabase();
        db.delete(LIST_TABLE_NAME, null, null);

    }
    //insert single item
    public boolean insertItem(ListItem listItem) {
        boolean status = true;

        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put("title", listItem.getTitle());
        values.put("content", listItem.getContent());
        values.put("parent_id", listItem.getParent_id());

        status = (db.insert(LIST_TABLE_NAME, null, values) > 0);
        db.close();
        return status;
    }

    //Get all list items in a category
    public List<ListItem> getList(Integer parent_id){
        List<ListItem> listItem = new ArrayList<ListItem> ();

        String query = "SELECT * FROM " + LIST_TABLE_NAME + " WHERE parent_id = " + parent_id;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        if(cursor.moveToFirst()){
            do{
                listItem.add(new ListItem(
                        Integer.parseInt(cursor.getString(0)),
                        cursor.getString(1),
                        cursor.getString(2),
                        Integer.parseInt(cursor.getString(3))
                        ));
            } while(cursor.moveToNext());
        }
        return listItem;
    }

    //Get single list
    public ListItem getListItem(Integer id){
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(LIST_TABLE_NAME, new String[] {"list_id", "title", "content", "parent_id"}, 
                "parent_id = ?", new String[] {String.valueOf(id)}, null, null, null );

        if(cursor != null){
            cursor.moveToFirst();
        }

        ListItem listItem = new ListItem(
                Integer.parseInt(cursor.getString(0)), 
                cursor.getString(1),
                cursor.getString(2),
                Integer.parseInt(cursor.getString(3))
                );

        return listItem;
    }

    // Get count of lists inside a category
    public Integer getCount(Integer parent_id){
        return 0;
    }

    //Updating single contact
    public int update(ListItem listItem){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("title", listItem.getTitle());
        values.put("content", listItem.getContent());
        values.put("parent_id", listItem.getParent_id());

        // updating row
        return db.update(LIST_TABLE_NAME, values, "list_id = ?",
                new String[] { String.valueOf(listItem.getId()) });
    }

    //delete single contact
    public void deleteList(ListItem listItem){
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(LIST_TABLE_NAME, "list_id = ?",
                new String[] { String.valueOf(listItem.getId()) });
        db.close();
    }
}

7. Display Saved lists in the MainActivity.
Now that the Database handlers are ready, basic framework is ready, we need to view our list in the activity. Copy paste the code below in MainActivity.java.
package com.ktm.listapp;

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

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.ktm.listapp.database.ListDatabaseHelper;
import com.ktm.listapp.objects.ListItem;

public class MainActivity extends ListActivity {

    Integer id = -1;
    ListDatabaseHelper loh = new ListDatabaseHelper(this);
    String [] list = {"DB not Working"};
    Integer[] idList = {-1};
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);

        //loh.deleteAll();
        try{
            id = getIntent().getExtras().getInt("parent_id");
        }catch(NullPointerException e){
            Log.d("Exception", "The intent throws null");
        }
        list = getListTitles(id);
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, list);
        
        setListAdapter (adapter);
        
    }



    
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        
        drillListActivity(idList[position]);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
        case R.id.new_list:
            addNewList();
            return true;
        case R.id.menu_settings :
            return true;
        default:
            return false;
        }
    }
    
    
    //other than the android stuff
    //returns the array of titles
    private String[] getListTitles(Integer parent_id){
        String [] titles = null;
        Integer[] ids = null;
        
        List<String> titleList = new ArrayList<String>();
        List<Integer> idList = new ArrayList<Integer>();
        
        for(ListItem item : loh.getList(parent_id)){
            titleList.add(item.getTitle());
            idList.add(item.getId());
        }
        
        titles = new String[titleList.size()];//titleList.toArray(titles);
        ids = new Integer[idList.size()];
        
        for(int i=0;i<titleList.size(); i++){
            titles[i] = titleList.get(i);
            ids[i] = idList.get(i);
        }
        
        this.idList = ids;
        return titles;
    }
    
    public void drillListActivity(Integer parent_id){
        Intent i = new Intent(getBaseContext(), MainActivity.class);
        i.putExtra("parent_id", parent_id);
        startActivity(i);
    }
    
    public void addNewList(){
        Intent i = new Intent(getBaseContext(), ListAddActivity.class);
        i.putExtra("parent_id", this.id);
        startActivity(i);
    }

}
If anything do not work, tell me. Have fun and enjoy.

Basic concepts of JMETER

- JMeter is an open-source tool, implemented in JAVA for performance testing.
- The Performance of many type of systems could be tested using JMeter.
- Some of the systems may be, Web-servers, Database-servers, Email-servers, web-services, Java-objects, Unit-tests etc.

What is performance testing.?
- Performance testing is something, such that you check how much time a system is taking to respond or do some activity.
- For example. You are moving your web application from one server to another. You might want to compare the response time, latency, Number of Users VS Response time of the servers to determine which one is better.
- There are other commercial applications also, which provide much more flexibility in performance testing, but if you want Free, Open-source tool, JMeter is the tool.
- JMeter is mainly targeted for Regression testing(Navigating to pages) but you could also measure functional activities(submitting forms, logging-in, ...) to some extent.

Approach
- You add different objects to JMeter, like ThreadGroup(configure number of users), HTTPSamplers(http-request), Listeners(to view request response data), if-controllers(to check a logic or a value), XPath-Extractors, Regular-Expression Extractors(to extract particular data from pages or response data) etc.
- You create a test plan by arranging components, then execute the plan. JMeter will perform requests, capture the responses, and show you the statistics about the time for request and responses.
- You could also use JMeter in proxy mode to capture the request responses and ease your work.

Best Database connector code for java and oracle.


package database;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Rajan Prasad Upadhyay
 */
public class OracleConnection {
    /* parameters */
    private String username=null;
    private String password=null;
    private String host=null;
    private String port=null;
    private String sid=null;
    
    private Connection con = null;
    
    
    
    /* Query execution */
    public void executeUpdate (String query) throws SQLException{
        if(con != null){
            PreparedStatement ps = con.prepareStatement(query);
            ps.executeUpdate();
        }
    }
    public ResultSet executeQuery (String query){
        ResultSet rs = null;
        if(con != null){
            try{
                PreparedStatement ps = con.prepareStatement(query);
                rs = ps.executeQuery();
            }catch(Exception e){
                
            }
        }
        return rs;
    }
    
    /* parameters part */
    public void setConnection (String conString){
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conString, username, password);
        } catch (Exception ex) {
            //return null;
            System.out.println("Connection could not be established");
            ex.printStackTrace();
        }
    }
    public Connection getConnection() {
        return con;
    }
    public void setDefaultParameters(){
        username = "USER1";
        password = "oracle";
        host    =   "localhost";
        port    =   "1521";
        sid     =   "XE";
    }
    public String getConnectionString(){
        return "jdbc:oracle:thin:@"+host+":"+port+":"+sid;
    }
 
 
 
 /* main method for unit testing */
    public static void main(String [] args) throws SQLException{
        OracleConnection con = new OracleConnection();
        //con.setDefaultParameters();
        con.setHost("localhost");
        con.setPort("1521");
        con.setSid("XE");
        con.setUsername("USER1");
        con.setPassword("oracle");
        
        //System.out.println(con.getConnectionString()); return ;
       
        con.setConnection(con.getConnectionString());
        
        ResultSet rs = con.executeQuery("select sysdate from dual");
        
        if(rs != null){
            while(rs.next()){
                System.out.println("The date is " + rs.getString(1));
            }
        }
    }

    /* Getters and Setters */
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public String getPort() {
        return port;
    }
    public void setPort(String port) {
        this.port = port;
    }
    public String getSid() {
        return sid;
    }
    public void setSid(String sid) {
        this.sid = sid;
    }
}