My Blog List

Android FirstAid Coding

A Small Help From a Small Heart
Powered by Blogger.

A software professional, who still likes to code, likes to blog and loves gadgets.

Monday 26 October 2015

Custom Listview Android

MainActivity.java


package com.example.test;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
ListView listview;
UsersAdapter adapter;
ArrayList<User> dataSource = new ArrayList<User>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createDataSource();
listview=(ListView)  findViewById(R.id.listview);

adapter = new UsersAdapter(this, dataSource);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
      User user=adapter.getItem(position);
      Toast.makeText(getBaseContext(), user.name, Toast.LENGTH_LONG).show();
                
            }
        });

}

private void createDataSource() {
User user=new User();
user.setName("Raju");
user.setAge("26");
dataSource.add(user);

user=new User();
user.setName("Rozy");
user.setAge("22");
dataSource.add(user);

user=new User();
user.setName("Meera");
user.setAge("32");
dataSource.add(user);

user=new User();
user.setName("Bibhu");
user.setAge("34");
dataSource.add(user);
user=new User();
user.setName("Prakash");
user.setAge("24");
dataSource.add(user);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar,if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class UsersAdapter extends ArrayAdapter<User> {
// View lookup cache
private  class ViewHolder {
TextView tvName;
TextView tvAge;
}

public UsersAdapter(Context context, ArrayList<User> users) {
super(context, R.layout.item_user, users);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);    
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_user, parent, false);
viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
viewHolder.tvAge = (TextView) convertView.findViewById(R.id.tvAge);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.tvName.setText(user.name);
viewHolder.tvAge.setText(user.age);
// Return the completed view to render on screen
return convertView;
}
}

}

main.xml


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

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#E09090" />

</LinearLayout>

item_user.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:orientation="vertical" >

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Name"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="23"
        android:textSize="18sp" />

</LinearLayout>


User.java

package com.example.test;

public class User {
String name,age;

public String getName() {
return name;
}

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

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}
}





Friday 23 May 2014

Calculating new width and height with maintaining aspect ratio of Image in iOS





Image original width = 100 and height = 150
Container width  = 200 and height = 200

x-ratio = Container width / Image original width = 200/100 = 2.0
y-ratio =  Container height / Image original height = 200/ 1501.33

Selected ratio = min (x-ratio, y-ratio) = 1.33

Final Image width = Image original width * Selected Ratio = 100 * 1.33 = 133
Final Image height = Image original height * Selected Ratio = 150 * 1.33 = 200

Final Image width x height = 133 x 200 (Original width x height of image was 100 x 150)

float leftOffset = (Container width - finalImageWidth) / 2;
float topOffset = (Container width - finalImageHeight) / 2;
[self.imageView setFrame:CGRectMake(leftOffset,topOffset, finalImageWidth, finalImageHeight)];
[self.imageView setImage:@"image name"];

self.imageView.contentMode = UIViewContentModeScaleAspectFit;

Wednesday 2 April 2014

Slide out menu with actionbarsherlock in android

Today I want to share my latest project, which is based on slide out menu in android like facebook iOS or Android apps.

ActionBarSherlock and support library

ActionBarSherlock (ABS) is an Android library developed by Jake Wharton, if you don't know about him or his projects check his github user:
 
 I used this library in my project.
 
 
 



















Saturday 7 September 2013

Back to Application after end of the call in iPhone

 

By using openURL we can make phone call from our app.


Problem:


It takes the users to the default Phone application after end of the call. But the users needs to go back to the app after end of the call.


Solution


NSString *phFormat=[NSString stringWithFormat:@"telprompt://0123456789"];           
[UIApplication sharedApplication] openURL:[NSURL URLWithString:phFormat]];

Splash Screen Animation on iPhone

How to show splash screen in iphone with a animation
 

AppDelegate.m
==============
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:viewController.view];
[window makeKeyAndVisible];
[NSTimer scheduledTimerWithTimeInterval:1.0/30. target:self selector:@selector(splashScreen) userInfo:nil repeats:NO];

}

- (void) splashScreen
{
//Welcome Screen
UIImageView* welcome = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)]autorelease];
welcome.image = [UIImage imageNamed:@"myimage.png"];
[window addSubview:welcome];
[window bringSubviewToFront:welcome];
//Animation Effects (zoom and fade)
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionNone forView:window cache:YES];
[UIView setAnimationDelegate:welcome];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

//set transparency to 0.0
welcome.alpha = 0.0;

//zoom effect
welcome.frame = CGRectMake(-60, -60, 440, 600);
[UIView commitAnimations];

}
 

Sunday 28 July 2013

How to show placeholder in UITextView iPhone

ViewController.h
------------------

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextViewDelegate>{
    UITextView *commentTf;
}

@end

ViewController.m
-----------------

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];   
    commentTf  = [[UITextView alloc] initWithFrame:CGRectMake(7, 40, 306, 85)];   
    [commentTf setFont:[UIFont systemFontOfSize:17.0]];   
    [commentTf setTextColor:[UIColor lightGrayColor]];      
    [commentTf setAutocapitalizationType:UITextAutocapitalizationTypeSentences];     
    commentTf.delegate=self;
    commentTf.text =@"Write your comment here";   
    [self.view addSubview:commentTf];

}
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    if (commentTf.textColor == [UIColor lightGrayColor]) {
        commentTf.text = @"";
        commentTf.textColor = [UIColor blackColor];
    }   
    return YES;
}
-(void) textViewDidChange:(UITextView *)textView
{
    if(commentTf.text.length == 0){
        commentTf.textColor = [UIColor lightGrayColor];
        commentTf.text = @"Write your comment here";
        [commentTf resignFirstResponder];
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {   
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        if(commentTf.text.length == 0){
            commentTf.textColor = [UIColor lightGrayColor];
            commentTf.text = @"Write your comment here";
            [commentTf resignFirstResponder];
        }
        return NO;
    }   
    return YES;
}
@end


Thursday 25 July 2013

SQLite Datbase in iPhone


This is the simple iPhone project which is based on  SQLite database.This is very simple way for using SQLite in out iPhone APP.
We have to add a SQLite framework in our project for using database. Do a control-click (right click) on the Frameworks folder. Click Add -> Existing Frameworks. So in the search bar type in libsqlite3. Now add  libsqlite3.0.dylib.
Here i have done all the basic database operation
  • Add/insert
  • Delete
  • Update
  • Retrieve

Demp app is developed in Xcode 4.3.2 and IOS SDK 5


AppDelegate.h
===============
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    sqlite3 *contactDB;
    NSString *databasePath;
    NSString *relinkUserId;
}

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end
Create the database structure in AppDelegate once

AppDelegate.m
===============
#import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self createDb];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
   
    self.window.rootViewController = navController;
   
 
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)createDb{
    NSString *docsDir;
    NSArray *dirPaths;
   
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    docsDir = [dirPaths objectAtIndex:0];
   
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"Test.db"]];
   
    NSFileManager *filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
       
        if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS STUDENT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT,EMAIL TEXT)";
           
            if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog( @"Failed to create STUDENT table");
            }           
           
            sqlite3_close(contactDB);
           
        } else {
            NSLog( @"Failed to open/create database");
        }
    }
   
}


@end

ViewController.h
================
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@interface ViewController : UIViewController{
    IBOutlet UITextField *nameTf,*phoneTf,*emailTf,*addressTf;
    NSString *name,*phone,*email,*address,*databasePath;
     sqlite3 *contactDB;
   
   
}
@property(nonatomic,retain)NSString *name,*phone,*email,*address;
-(IBAction)save:(id)sender;

@end


ViewController.m
===================
How to save/insert data.

-(IBAction)save:(id)sender{
   
    name=nameTf.text;
    phone=phoneTf.text;
    email=emailTf.text;
    address=addressTf.text;
   
   databasePath=[self dataBasePath];
    // NSFileManager *filemgr = [NSFileManager defaultManager];
    sqlite3_stmt    *statement;
   
    const char *dbpath = [databasePath UTF8String];
   
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
       
            NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO STUDENT (name, address, phone,email) VALUES (\"%@\", \"%@\", \"%@\",\"%@\")", name, address, phone,email];
           
            const char *insert_stmt = [insertSQL UTF8String];           
            sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
           
      
       
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSInteger lastRowId = sqlite3_last_insert_rowid(contactDB);
            NSLog(@"lastRowId==%d",lastRowId);
           
           
        }else {
            NSLog(@"Failed to add contact");
            NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(contactDB));
        }
       
        sqlite3_finalize(statement);
        sqlite3_close(contactDB);
    }   
   
}

-(NSString *)dataBasePath{
    NSString *docsDir;
    NSArray *dirPaths;
   
   
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    docsDir = [dirPaths objectAtIndex:0];
   
    // Build the path to the database file
    return [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"Test.db"]];
   
}



How to retrieve data from table
==========

-(void)readStudentlist{
   self.studentList=[[NSMutableArray alloc] init];
    // NSFileManager *filemgr = [NSFileManager defaultManager];
    const char *dbpath = [[self dataBasePath] UTF8String];
    if(sqlite3_open(dbpath , &contactDB) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = "select * from STUDENT order by NAME asc";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(contactDB, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row
                int rowID = sqlite3_column_int(compiledStatement, 0);
                //NSLog(@"primaryKey==%d",primaryKey);
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aAdd = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                NSString *aPh = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                NSString *aEmail = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
               
                NSLog(@"%@",aName);
               
                CustomerVO *vo = [[CustomerVO alloc] init];   
                vo.sName=aName;
                vo.sAddress=aAdd;
                vo.sPhone=aPh;
                vo.sEmail=aEmail;
                vo.sId=rowID;
                [self.studentList addObject:vo];
             }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);
       
    }
    sqlite3_close(contactDB);  
  
}


Delete a specific data
======================
-(void)deleteStudent:(int)rowId{

    const char *dbpath = [[self dataBasePath] UTF8String];
    sqlite3_stmt    *statement;
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSString *deleteSQL = [NSString stringWithFormat: @"delete from STUDENT where id=%d",rowId];
       
        const char *del_stmt = [deleteSQL UTF8String];
       
        sqlite3_prepare_v2(contactDB, del_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            //[self dismissModalViewControllerAnimated:YES];
            //NSInteger lastRowId = sqlite3_last_insert_rowid(contactDB);
            NSLog(@"deleted folder");
           
        } else {
            NSLog(@"Failed to add contact");
            NSLog(@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(contactDB));
        }
        sqlite3_finalize(statement);
        sqlite3_close(contactDB); 
    }
}



CustomerVO.h
=============
#import <Foundation/Foundation.h>
@interface CustomerVO : NSObject{
NSString *sName;
NSString  *sAddress;
NSString  *sPhone;
NSString  *sEmail;
NSInteger sId;
}
@property (assign, nonatomic) NSInteger sId;
@property (nonatomic, retain) NSString *sName,*sAddress,*sPhone,*sEmail;

@end


CustomerVO.m
=============
#import "CustomerVO.h"
@implementation CustomerVO
@synthesize sName,sAddress,sEmail,sPhone,sId;
@end