To Add the Cover Flow in Android

The basic idea is that the Coverflow widget works very much like the standard Android Gallery widget, but with the addition of the rotation of the images. For more background information on the Coverflow widget see my original post

1>Write the Two Class 1. CoverFlow and second is Your Activity in which onCreate() is Present

 

 
public class CoverFlow extends Gallery {

private Camera mCamera = new Camera();
private int mMaxRotationAngle = 60;
private int mMaxZoom = -120;
private int mCoveflowCenter;

public CoverFlow(Context context) {
super(context);
this.setStaticTransformationsEnabled(true);
}

public CoverFlow(Context context, AttributeSet attrs) {
super(context, attrs);
this.setStaticTransformationsEnabled(true);
}

public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setStaticTransformationsEnabled(true);
}

public int getMaxRotationAngle() {
return mMaxRotationAngle;
}
public void setMaxRotationAngle(int maxRotationAngle) {
mMaxRotationAngle = maxRotationAngle;
}
public int getMaxZoom() {
return mMaxZoom;
}

public void setMaxZoom(int maxZoom) {
mMaxZoom = maxZoom;
}
private int getCenterOfCoverflow() {
return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}

private static int getCenterOfView(View view) {
return view.getLeft() + view.getWidth() / 2;
}
protected boolean getChildStaticTransformation(View child, Transformation t) {

final int childCenter = getCenterOfView(child);
final int childWidth = child.getWidth() ;
int rotationAngle = 0;

t.clear();
t.setTransformationType(Transformation.TYPE_MATRIX);

if (childCenter == mCoveflowCenter) {
transformImageBitmap((ImageView) child, t, 0);
} else {
rotationAngle = (int) (((float) (mCoveflowCenter - childCenter)/ childWidth) * mMaxRotationAngle);
if (Math.abs(rotationAngle) > mMaxRotationAngle) {
rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
}
transformImageBitmap((ImageView) child, t, rotationAngle);
}

return true;
}

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCoveflowCenter = getCenterOfCoverflow();
super.onSizeChanged(w, h, oldw, oldh);
}

private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) {
mCamera.save();
final Matrix imageMatrix = t.getMatrix();;
final int imageHeight = child.getLayoutParams().height;;
final int imageWidth = child.getLayoutParams().width;
final int rotation = Math.abs(rotationAngle);

mCamera.translate(0.0f, 0.0f, 100.0f);

if ( rotation < mMaxRotationAngle ) {
float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
mCamera.translate(0.0f, 0.0f, zoomAmount);
}

mCamera.rotateY(rotationAngle);
mCamera.getMatrix(imageMatrix);
imageMatrix.preTranslate(-(imageWidth/2), -(imageHeight/2));
imageMatrix.postTranslate((imageWidth/2), (imageHeight/2));
mCamera.restore();
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CoverFlow coverFlow;
coverFlow = new CoverFlow(this);

coverFlow.setAdapter(new ImageAdapter(this));

ImageAdapter coverImageAdapter = new ImageAdapter(this);
coverFlow.setAdapter(coverImageAdapter);
coverFlow.setSpacing(-25);
coverFlow.setSelection(4, true);
coverFlow.setAnimationDuration(1500);
setContentView(coverFlow);
}

public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;

private FileInputStream fis;

private Integer[] mImageIds = {
R.drawable.icon1,
R.drawable.icon2,
R.drawable.icon3,
R.drawable.icon4,
R.drawable.icon14,
R.drawable.icon5,

};

private ImageView[] mImages;

public ImageAdapter(Context c) {
mContext = c;
mImages = new ImageView[mImageIds.length];
}
public boolean createReflectedImages() {
final int reflectionGap = 4;
int index = 0;
for (int imageId : mImageIds) {
Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
imageId);
int width = originalImage.getWidth();
int height = originalImage.getHeight();

//This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);

//Create a Bitmap with the flip matrix applied to it.
//We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);

//Create a new bitmap with same width but taller to fit reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width
, (height + height/2), Config.ARGB_8888);

//Create a new Canvas with the bitmap that's big enough for
//the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
//Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
//Draw in the gap
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
//Draw in the reflection
canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);

//Create a shader that is a linear gradient that covers the reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
//Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);

ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmapWithReflection);
imageView.setLayoutParams(new CoverFlow.LayoutParams(120, 180));
imageView.setScaleType(ScaleType.MATRIX);
mImages[index++] = imageView;

}
return true;
}

public int getCount() {
return mImageIds.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new CoverFlow.LayoutParams(130, 130));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
drawable.setAntiAlias(true);
return i;

}
public float getScale(boolean focused, int offset) {
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}

}

Loading data in listview on scroll without refreshing list

This tutorial will give you brief idea about how to load the data in ListView on scroll down.

i came across this situation when i was developing the app where only 10 records to be displayed at start. On scroll the list when user reaches the last record more data gets added to the list like facebook posts.

The idea behind this was to get 10 records from web service first and display the list.

Using the method

public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount)

of OnScrollListener Check whether the scroll reached to the end

start background task to fill further data and on completion call notifyDatasetChanged() method of List adapter

package com.nanostuffs.antique; 

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

public class Main extends ListActivity implements OnScrollListener {

List<ListItems> list;
public ProgressDialog dialog;
String url=””;
int page =1;
ListView lv;
AListAdapter listAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
dialog = new ProgressDialog(this);
url =”http://yourwebserviceurl.com + page=”+page;
/**
* fill the list randomly for first view
*/
try{
new PerformBackgroundTask().execute(“”);
}catch (Exception e) {
if(dialog.isShowing())
dialog.dismiss();
e.printStackTrace();
Toast.makeText(getBaseContext(),”No Result Found”, Toast.LENGTH_LONG).show();
}
lv = getListView();
lv.setOnScrollListener(this);
}
/**
* load data using background task
*/
class PerformBackgroundTask extends AsyncTask<String, Void, String> {
List<ListItems> list1 ;
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);

//check if we got the data
if(list1==null){
if (dialog.isShowing()) {
dialog.cancel();
}
}else{
if(list!=null){
// instanciate the adapter once
if(listAdapter== null){
listAdapter = new AListAdapter(Main.this, (ArrayList<ListItems>) list);
setListAdapter(listAdapter);
}
//
listAdapter.notifyDataSetChanged();
}
if (dialog.isShowing())
dialog.cancel();
}
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage(“Please  wait…”);
dialog.show();
}
@Override
protected String doInBackground(String… params) {
// TODO Auto-generated method stub
try{

// get the data from web service
list1 = new XMLReader().getDetailItemList(url);

//check if previous data available  then add new data to the same arraylist
if(list!=null){
list.addAll(list1);
}else
{
list =list1;
}
}catch (Exception e) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
return “”;
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(totalItemCount>10){
boolean loadMore = /* maybe add a padding */
firstVisibleItem + visibleItemCount >= totalItemCount-1;

Log.d(“onScroll:”,”loadMore f=” + firstVisibleItem + “, vc=” + visibleItemCount + “, tc=” +totalItemCount);
if(loadMore) {
page++;
new PerformBackgroundTask().execute(“”);
}else{
Log.d(“recrd”, “NO”);
}
}
}
//Debug.stopMethodTracing();
}

public int checkDataSize() {
// check if the data available
/**
* do your loading of data
*/
return result.length();

}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

}

 

Set Timer in Blackberry Application

This Code shows how to set Timer in your blackberry Application.

Step-1: Implement Runnable interface.And add unimplemented methods.And set this fields.

private long startTime;
private Thread updater;
private boolean isRunning= false;
private final static SimpleDateFormat timerFormat = new SimpleDateFormat(“ss.SSS”);
private final Runnable displayUpdater= new Runnable()
{
public void run()
{
displayElapsedTime(System.currentTimeMillis() – SecondScreen.this.startTime);
}
};

Step-2: Add this Method.

private void displayElapsedTime(long elapsedTime)
{
edField1.setText(”        “+timerFormat.format(new Date(elapsedTime)));
}

step-3:

public void run() {
try
{
while(isRunning)
{
UiApplication.getUiApplication().invokeAndWait(displayUpdater);
Thread.sleep(50);
}
}
catch(InterruptedException ie) {}
}

Step-4: Inside the FieldChanged Method.

To Start the timer –

if(start == field){
startTime= System.currentTimeMillis();
isRunning= true;
updater= new Thread(this);
updater.start();
}

To Stop the Timer –

if(stop == field){
if(isRunning)
{
long elapsed= System.currentTimeMillis() – startTime;
isRunning= false;
displayElapsedTime(elapsed);
Thread.yield();
currentTime = edField1.getOriginal().toString();
}
}

 

 

Salesforce form integration (web-to-lead) with PHP and cURL

In the example below I am only showing the basic process. I am leaving out the validation code for the fields and any submission code to MySQL database.

One security advantage of this process is hiding your organisation id within a variable in the submission page rather than on the live page with the form.

// SF Org Id.
$oid = "0113543434646";

I first check if cURL is enabled before processing any further.

// Make sure cURL is enabled
if (!function_exists('curl_init')) {
	error("Curl is not setup on this PHP server and is
    required for this script");
}

I then loop through all the data input from the form. I first check there is data there (twice). Then I loop through each POST data using a foreach. Within the foreach loop I run stripslashes()function to stop the backslashes getting added twice. I don’t do any other form of validation as the data is going to Salesforce and I rely on them checking the data. At the end I add the organisation to the array.

if (isset($_POST)) {

if (count($_POST) == 0) exit("Error.  No data was passed
     to this script.");

// variable to hold cleaned up a version of $_POST data
$cleanPOST = array();	

// Loop through the $_POST data and process it
foreach ($_POST as $key=>$value){
 $cleanPOST[stripslashes($key)] = stripslashes($value);
}

// Add the Org ID
$cleanPOST["oid"] = $oid;

} else {
 exit("Error.  No data was passed to this script.");
}

Once the POST data is in an array we can send it to Salesforce. I have commented each step below. I add a return URL to the data sent which then redirects the user to that URL. You could do the redirect in the PHP file itself.

// Create a new cURL resource
$ch = curl_init();	

if (curl_error($ch) != "") {
    echo "Error: $errorn";
}

// Point to the Salesforce Web to Lead page
curl_setopt($ch, CURLOPT_URL,
"http://www.salesforce.com/servlet/servlet.WebToLead");

// Set the method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Pass POST data
curl_setopt(
$ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));

curl_exec($ch); // Post to Salesforce
curl_close($ch); // close cURL resource

Java : Object oriented programming language (Part – 1)

Java is a programming language developed by James Gosling at Sun Microsystems. It is an object oriented programming language. Now, what is mean by ‘Object oriented’ ? In object oriented programming, everything is in the form of object. Objects are the fundamental units in object oriented language, which are having their own behavior, specific purpose.

Syntax of Java is just like C++. One of the key feature of Java is, it is platform independent language, which makes Java language as most powerful language among the other languages. Platform independent means program written on one platform can run on any other platform provided the platform must have JVM (Java Virtual Machine).

As Java is an object oriented language it follows all the four features of it. They are as follows :

1. Inheritance

2. Encapsulation

3. Polymorphism

4. Data Binding.

Happy Coding……………..!!!!!!!!!!!

Maximum number of custom fields allowed for Developer’s edition of Salesforce.com

I was creating custom fields for a particular site and just got notification that the maximum number of custom fields reached. Please contact your administrator. The maximum number of custom fields allowed for developer’s edition are 500 fields/per object. Similarly for professional edition it is 100 fields/object.Additional restrictions apply for activities, long text area fields, relationship fields, and roll-up summary fields.

Which framework is best for PHP?

These days, Website Developer, Designer or Programmer asks a common question all the time-“Which framework is best for PHP?“. Because of availability of various frameworks like CodeIgniter, CakePHP, Zend, Symfony, Yii, etc., my answer is- its depends on following points(or we have to consider following points):

  • What is my application going to do?
  • which framework has a stable community?
  • which framework has a good resource available?
  • which framework is under solid development phase and not in “discontinued” mode?

Once you have the answer, you need to know that there are basically three types of framework though they offer MVC or HMVC work flow.

  1. Some frameworks are liberal.
  2. Some frameworks are too strict.
  3. Some of them are over strict and configuration junky.

Take a look, Codeigniter, It is extremely liberal, allowed me to write bad code. means we can called model inside view. Its a very light weight and good for small project or application.

Now take a look on CakePHP, as per conventions it is strict type. But as per standard and as a requirement for big application, it fits.

Take a look on Symfony, its a moving into strict and configuration junky type.

in short, if you are a beginner with MVC and want to learn a framework from the heart, start with Zend Framework or CakePHP. Soon you will realize that you may not have to move or use any other framework unless the situation requires it. Saying that, there are other very good frameworks out there like Yii, CodeIgniter and Kohana etc.

Getting a Maps API Key from Google in Andriod Application

The MapView class in the Maps external library is a very useful class that lets you easily integrate Google Maps into your application. It provides built-in map downloading, rendering, and caching of Maps tiles, as well as a variety of display options and controls.

Because MapView gives you access to Google Maps data, you need to register with the Google Maps service and agree to the applicable Terms of Service before your MapView will be able to obtain data from Google Maps. This will apply whether you are developing your application on the emulator or preparing your application for deployment to mobile devices.

Registering for a Maps API Key is simple, free, and has two parts:

  1. Registering the MD5 fingerprint of the certificate that you will use to sign your application. The Maps registration service then provides you a Maps API Key that is associated with your application’s signer certificate.
  2. Adding a reference to the Maps API Key in each MapView, whether declared in XML or instantiated directly from code. You can use the same Maps API Key for any MapView in any Android application, provided that the application is signed with the certificate whose fingerprint you registered with the service.

Getting the MD5 Fingerprint of the SDK Debug Certificate:

1. first get the full path of “debug.keystore” ,

By default, build tools create the debug keystore in the active AVD directory. The location of the AVD directories varies by platform:

  • Windows Vista: C:Users<user>.androiddebug.keystore
  • Windows XP: C:Documents and Settings<user>.androiddebug.keystore
  • OS X and Linux: ~/.android/debug.keystore
  • If you are using Eclipse/ADT and are unsure where the debug keystore is located, you can select Windows > Prefs > Android > Build to check the full path, which you can then paste into a file explorer to locate the directory containing the keystore.

2. then open command prompt, locate the keytool (which is present in C:\jdkbin> folder)

3. then run the following command.

$ keytool -list -alias androiddebugkey 
-keystore <path_to_debug_keystore>.keystore 
-storepass android -keypass android

here <path_to_debug_keystore > is replace by full path in above first step.
now press enter .

it will ask password.
do not write any thing in password just again press enter.

It will give MD5 fingerprint key , note down it.

 

Registering the Certificate Fingerprint with the Google Maps Service

When you are ready to register for a Maps API Key, load this page in a browser:

http://code.google. com/android/maps-api-signup.html

To register for a Maps API Key, follow these steps:

  1. If you don’t have a Google account, use the link on the page to set one up.
  2. Read the Android Maps API Terms of Service carefully. If you agree to the terms, indicate so using the check-box on the screen.
  3. Paste the MD5 certificate fingerprint of the certificate that you are registering into the appropriate form field.
  4. Click “Generate API Key”

use this unique key in your application .

You will get result ,

Thanks

Movement from Unity 3d into Unity 3D iOS or Android

if u want to using buttons use this it will work in unity 3d and ios

void OnGUI()
{
    if(GUI.RepeatButton(new Rect(50,210,40,40),"up"))
    {
       transform.Translate(Vector3.forward*Time.deltaTime*50); 

    }

    if(GUI.RepeatButton(new Rect(50,280,40,40),"down"))
    {
       transform.Translate(Vector3.back*Time.deltaTime*50);

    }

    if(GUI.RepeatButton(new Rect(10,250,40,40),"left"))
    {
       transform.Rotate(Vector3.down, 90*Time.deltaTime);
    }

    if(GUI.RepeatButton(new Rect(90,250,40,40),"right"))
    {
       transform.Rotate(Vector3.up, 90*Time.deltaTime);
    }
}

other wise,

u can use joystick for the movement in ios. the standard package is present in standard assets mobile in the unity itself.
so u try it once.
In menu->assets->import package->standard assets(mobile)