Saturday, July 27, 2013

GCM_Registration_Example

AndroidManifest.xml
---------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kundan.gcmproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
<permission android:name="com.kundan.gcmproject.permission.C2D_MESSAGE" 
    android:protectionLevel="signature" />
<uses-permission android:name="com.kundan.gcmproject.permission.C2D_MESSAGE" /> 
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.kundan.gcmproject.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    <receiver android:name=".MyBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
  <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
    <category android:name="com.kundan.gcmproject" />
  </intent-filter>
</receiver>
    </application>

</manifest>


ActivityMain.java
--------------------
package com.kundan.gcmproject;

import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
Button btn1,btn2;
TextView tv;
public static final String SenderID="1096002802846";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button) findViewById(R.id.button1);
btn2=(Button) findViewById(R.id.button2);
tv=(TextView) findViewById(R.id.textView2);
btn1.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");

registrationIntent.putExtra("app", PendingIntent.getBroadcast(v.getContext(), 0, new Intent(), 0));
registrationIntent.putExtra("sender",SenderID);
startService(registrationIntent);
System.out.println("**********"+MyBroadcastReceiver.registrationId);
tv.setText(MyBroadcastReceiver.registrationId);
Log.i("button", "button press");
}
});
        
        btn2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregIntent.putExtra("app", PendingIntent.getBroadcast(v.getContext(), 0, new Intent(), 0));
startService(unregIntent);

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

MyBroadcastReceiver.java
-------------------------------
package com.kundan.gcmproject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver{
String data1,data2;
Context ctx;
public static String registrationId;
public static String error;
public static String unregistered;
@Override
public void onReceive(Context context, Intent intent) {
ctx = context;
try {
            String action = intent.getAction();
            if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
                handleRegistration(intent);
            } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
               handleMessage(intent);
            }
        } finally {
           
           
        }
}
@SuppressWarnings("deprecation")
private void handleRegistration(Intent intent) {
       registrationId = intent.getStringExtra("registration_id");
       error = intent.getStringExtra("error");
       unregistered = intent.getStringExtra("unregistered");       
       // registration succeeded
       if (registrationId != null) {
        new MyFileaccess().Load_Data("REGID", registrationId, ctx);
       
        NotificationManager mNotificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"Registration Successful", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        Intent i = new Intent(ctx, MainActivity.class);
        PendingIntent activity = PendingIntent.getActivity(ctx, 0, i, 0);
        notification.setLatestEventInfo(ctx, "Registration Success", registrationId, activity);        
        mNotificationManager.notify(0, notification);
       
          
       }            
      
       if (unregistered != null) {
        new MyFileaccess().Load_Data("REGID","0", ctx);
        NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"UnRegistration Successful", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.number += 1;
        PendingIntent activity = PendingIntent.getActivity(ctx, 0, null, 0);
        notification.setLatestEventInfo(ctx, "UnRegistration Success", unregistered, activity);
        mNotificationManager.notify(0, notification);
       
           
       }            
       
       if (error != null) {
           if ("SERVICE_NOT_AVAILABLE".equals(error)) {
            NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"Error", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.number += 1;
        PendingIntent activity = PendingIntent.getActivity(ctx, 0, null, 0);
        notification.setLatestEventInfo(ctx, "Error in registration", error, activity);
        mNotificationManager.notify(0, notification);              
             
           } else {
              
              
           }
       }
   }
@SuppressWarnings("deprecation")
private void handleMessage(Intent intent) {        
       String data1 = intent.getStringExtra("data1");
       String data2 = intent.getStringExtra("data2");
       
   NotificationManager mNotificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
      Notification notification = new Notification(R.drawable.ic_launcher,"Message recieved from server", System.currentTimeMillis());
      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      notification.number += 1;
      Intent i = new Intent(ctx, MainActivity.class);
      PendingIntent activity = PendingIntent.getActivity(ctx, 0, i, 0);
      notification.setLatestEventInfo(ctx,data1, data2, activity);
      mNotificationManager.notify(0, notification);
      
   }

}

MyFileaccess.java
----------------------
package com.kundan.gcmproject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

public class MyFileaccess {
@SuppressWarnings("static-access")
public void Load_Data(String filename, String Datastring, Context context) {
FileOutputStream fos;

try {
fos = context.openFileOutput(filename, context.MODE_PRIVATE);
fos.write(Datastring.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block

} catch (IOException e) {
// TODO Auto-generated catch block

}

}
public String get_Data(String filename,Context context)
{
FileInputStream f = null;
String temp="";
try {
f= context.openFileInput(filename);
int n = f.available();
for(int i=0;i<n;i++)
{
temp=temp+(char)f.read();
}
f.close();
}catch (IOException e)
{
}
return temp;
}

}

activity_main.xml
------------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/RelativeLayout1"
    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=".MainActivity" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:textColor="#990000"
      
        android:text=" "
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="73dp"
        android:text="Activate" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/button1"
        android:text="Deactivate" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="17dp"
        android:text="Your Reg IDs is..."
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>




Friday, July 26, 2013

Custom Enter key

activity_main.xml
---------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/round_back"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" 
        android:singleLine="true"
        android:imeOptions="actionSearch">

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" 
        android:singleLine="true"
        android:imeOptions="actionGo"/>

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" 
        android:singleLine="true"
        android:imeOptions="flagNavigateNext"/>

    <EditText
        android:id="@+id/editText4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" 
        android:singleLine="true"
        android:imeOptions="actionSend"/>

</LinearLayout>




Image_Mask

MainActivity.java
--------------------
package com.kundan.sampletest;



public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView iv=new ImageView(this);
Bitmap source=BitmapFactory.decodeResource(getResources(),R.drawable.titli);
Bitmap result=Bitmap.createBitmap(source.getWidth(),source.getHeight(),Config.ARGB_8888);
Canvas canvas=new Canvas(result);
Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
RectF rect=new RectF(0,0,source.getWidth(),source.getHeight());
float radius=25.0f;
paint.setColor(Color.BLACK);
canvas.drawRoundRect(rect, radius, radius, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
paint.setXfermode(null);
iv.setImageBitmap(result);
setContentView(iv);




}

@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;
}

}


Thursday, July 25, 2013

Drawable Pattern

 src_one
src_two


pattern_checker.xml
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" 
    android:src="@drawable/src_one"
    android:tileMode="repeat">
    

</bitmap>
pattern_stripe.xml
---------------------
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" 
     android:src="@drawable/src_two"
    android:tileMode="mirror">

</bitmap>


activity_main.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=".MainActivity"
    android:background="@drawable/pattern_stripe" >

</RelativeLayout>




App with translucent background

style.xml
------------
<style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
                <item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item> 
    </style>

Wednesday, July 24, 2013

uninstalling .apk file from emulator

press menu->Settings->Apps->select your application from  listView ->press uninstall -> OK wait for someTimes...uninstall finished... :)

Installing .apk file in emulator

put your .apk file in \platform-tools
ie
D:\KUNDAN\adt-bundle-windows-x86-20130522\sdk\platform-tools

open the command prompt(cmd.exe) change your directory
ie

D:\KUNDAN\adt-bundle-windows-x86-20130522\sdk\platform-tools>
execute the command ie
adb install <filename>.apk
ie.
adb install jlcindia.apk

JSON Parser Example(Reading data from JSON and displaying in custom ListView)

Create a folder name raw, in res folder of your project.
inside the raw folder create a file address.json and paste the following code....


res->raw->address.json
-----------------------------
{
    "contacts": [
        {
                "id": "k001",
                "name": "Kundan Kumar",
                "email": "kk@gmail.com",
                "address": "Bangalore - karnataka",
                "gender" : "male",
                "phone": "8123561470"
        },
        {
                 "id": "S001",
                "name": "Sangam Kumar",
                "email": "ss@gmail.com",
                "address": "India",
                "gender" : "male",
                "phone": "08123565560"
               
        }
   
  ]
}


activity_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"
 
    tools:context=".MainActivity"
    android:background="@drawable/bg">

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#990000"
        android:dividerHeight="1dip"
        android:paddingTop="5dip">
    </ListView>

</LinearLayout>


image_view.xml
-------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="19dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/phoneView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nameView"
        android:layout_below="@+id/nameView"
        android:text="Phone" />

    <TextView
        android:id="@+id/nameView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>


MainActivity.java
---------------------
package com.kundan.jsonexample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends Activity {
ListView lv;
String jsonstr=null;
String[] nameID;
String[] phoneID;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
try {
InputStream in=getResources().openRawResource(R.raw.address);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
jsonstr=sb.toString();
Log.d(this.toString(), jsonstr);
//System.out.println(jsonstr);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
JSONObject jobj=new JSONObject(jsonstr);
//System.out.println(jobj);
JSONArray jarray=jobj.getJSONArray("contacts");
//System.out.println(jarray);
//JSONObject jobj1=jarray.getJSONObject(0);
//System.out.println(jobj1);
nameID=new String[jarray.length()];
phoneID=new String[jarray.length()];
JSONObject jobject=null;
for(int i=0;i<=jarray.length();i++){
jobject=jarray.getJSONObject(i);
//System.out.println(jobject.getString("name"));
//System.out.println(jobject.getString("phone"));
nameID[i]=jobject.getString("name");
phoneID[i]=jobject.getString("phone");
}
} catch (Exception e) {
 Log.e("JSON Parser", "Error parsing data " + e.toString());
}
lv.setAdapter(new MyImageAdapter(this,nameID,phoneID));
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "clicked:"+nameID[position], Toast.LENGTH_SHORT).show();
}
});
}

@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;
}

}

MyImageAdapter.java
-------------------------
package com.kundan.jsonexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

public class MyImageAdapter extends BaseAdapter {
String[] nameID;
String[] phoneID;
Context context;
public MyImageAdapter(Context context, String[] nameID,String[] phoneID) {
this.context=context;
this.nameID=nameID;
this.phoneID=phoneID;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return nameID.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.image_view, parent,false);
TextView name=(TextView) rowView.findViewById(R.id.nameView);
TextView phone=(TextView) rowView.findViewById(R.id.phoneView);
ImageView iv=(ImageView) rowView.findViewById(R.id.imageView1);
name.setText(nameID[position]);
phone.setText(phoneID[position]);
String str1=nameID[position];
if(str1.startsWith("Kundan Kumar")){
iv.setImageResource(R.drawable.fb);
}
if(str1.startsWith("Sangam Kumar")){
iv.setImageResource(R.drawable.tw);
}
return rowView;
}

}





Tuesday, July 23, 2013

Email Example

First you need to add Email/Gmail Account...then choose your email client.... :)
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:background="@drawable/background"
    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/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/title_view"
        android:textStyle="italic"
        android:textAppearance="?android:attr/textAppearanceMedium" 
        android:layout_gravity="center_horizontal"
        android:textColor="#000099"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TO:"
        android:textSize="16dip"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#000099" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Friends email_id" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subject:"
        android:textSize="16dip"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#000099" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Subject" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message:"
        android:textSize="16dip"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#000099" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="94dp"
        android:layout_weight="0.40"
        android:ems="10"
        android:gravity="top"
        android:hint="Write Your Message" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send" 
        android:textColor="#000099" 
        />

</LinearLayout>

Mainactivity.java
-------------------
package com.kundan.email;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
Button send;
EditText ed1,ed2,ed3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText) findViewById(R.id.editText1);
ed2=(EditText) findViewById(R.id.editText2);
ed3=(EditText) findViewById(R.id.editText3);
send=(Button) findViewById(R.id.button1);
send.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String to=ed1.getText().toString();
String subject=ed2.getText().toString();
String message=ed3.getText().toString();
Intent i=new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, message);
i.setType("message/rfc822");
startActivity(Intent.createChooser(i, "Choose your email client!!"));

}
});
}

@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;
}

}



Sunday, July 21, 2013

ViewPager_ImageGallery

activity_main.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"
  
    tools:context=".MainActivity" >
     <android.support.v4.view.ViewPager
 android:id="@+id/view_pager"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />

</RelativeLayout>
MainActivity.java
---------------------
package com.kundan.viewpager_imagegallery;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends Activity {

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

   ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
   ImageAdapter adapter = new ImageAdapter(this);
   viewPager.setAdapter(adapter);
}

@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;
}

}

 ImageAdapter.java
------------------------
package com.kundan.viewpager_imagegallery;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class ImageAdapter extends PagerAdapter {
Context context;
    private int[] GalImages = new int[] {
        R.drawable.one,
        R.drawable.two,
        R.drawable.three
    };
    ImageAdapter(Context context){
    this.context=context;
    }
    @Override
    public int getCount() {
      return GalImages.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
      return view == ((ImageView) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      ImageView imageView = new ImageView(context);
     
      imageView.setPadding(5, 5, 5, 5);
      imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
      imageView.setImageResource(GalImages[position]);
      ((ViewPager) container).addView(imageView, 0);
      return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
      ((ViewPager) container).removeView((ImageView) object);
    }
  }

Saturday, July 20, 2013

Drawer

activity_main.xml
---------------------
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <FrameLayout
        android:id="@+id/main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

    <ListView
        android:id="@+id/drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFF"
        android:choiceMode="singleChoice"
        android:divider="#ffffff"
        android:dividerHeight="1dip"/>

</android.support.v4.widget.DrawerLayout>

red.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"
    android:background="#990000">  

</LinearLayout>
green.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" 
    android:background="#228B22">
    

</LinearLayout>
blue.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" 
    android:background="#000080">
    

</LinearLayout>
home.xml
-----------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#999999"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Switch to right for navigation"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:text="Home"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
MainActivity.java
----------------------
package com.kundan.drawer_navigation;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends FragmentActivity{
final String[] data ={"red","green","blue"};
final String[] fragments ={
"com.kundan.drawer_navigation.FragmentOne",
"com.kundan.drawer_navigation.FragmentTwo",
"com.kundan.drawer_navigation.FragmentThree",
"com.kundan.drawer_navigation.Home"
};
ListView lv;
DrawerLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.drawer);
layout=(DrawerLayout) findViewById(R.id.drawer_layout);
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1,data);
lv.setAdapter(adapter);
lv.setBackgroundColor(Color.BLACK);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, final int position,long id) {
layout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
                     public void onDrawerClosed(View drawerView){
                             super.onDrawerClosed(drawerView);
                             FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
                             tx.replace(R.id.main, Fragment.instantiate(MainActivity.this, fragments[position]));
                             tx.commit();
                     }
});
layout.closeDrawer(lv);
}
});
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main, Fragment.instantiate(MainActivity.this,fragments[3] ));
ft.commit();
}

@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;
}

}
FragmentOne.java
------------------------
package com.kundan.drawer_navigation;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentOne extends Fragment {
public static Fragment newInstance(Context context) {
    FragmentOne f = new FragmentOne();
 
       return f;
   }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root=(ViewGroup) inflater.inflate(R.layout.red, container ,false);
return root;
}
}
FragmentTwo.java
----------------------
package com.kundan.drawer_navigation;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentTwo extends Fragment {
public static Fragment newInstance(Context context) {
    FragmentTwo f = new FragmentTwo();
 
       return f;
   }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root=(ViewGroup) inflater.inflate(R.layout.green, container ,false);
return root;
}
}
FragmentThree.java
------------------------
package com.kundan.drawer_navigation;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentThree extends Fragment {
public static Fragment newInstance(Context context) {
    FragmentThree f = new FragmentThree();
 
       return f;
   }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root=(ViewGroup) inflater.inflate(R.layout.blue, container ,false);
return root;
}
}
Home.java
------------
package com.kundan.drawer_navigation;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Home extends Fragment {
public static Fragment newInstance(Context context) {
Home f = new Home();
 
       return f;
   }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root=(ViewGroup) inflater.inflate(R.layout.home, container ,false);
return root;
}
}