Thursday, 1 August 2013

Image Pick From Gallery Android

Leave a Comment
Hello friends, lets begin with another useful exercise in android development. In this post I am going to display how to choose an image from the gallery. This post is useful to those who are making an application in which they need to access to the gallery and take out a photo from it.To demonstrate I have made a sample project named ImagePickFromGallery.

Step 1 :- activity_image_pick.xml.
In xml I am having a button to choose from gallery and one ImageView
<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"
  >
    <Button
        android:id="@+id/btn_image_pick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="120dp"
        android:text="ImagePick" />
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_image_pick"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="33dp"
        android:src="@drawable/ic_launcher" />
</RelativeLayout>

Step 2:- ImagePick.java
package com.imagepickfromgallery;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImagePick extends Activity {
   
      private static final int REQUEST_CODE = 1;
      private Bitmap bitmap;
      private ImageView imageView;
      private Button btnImagePick;
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_pick);
       
        btnImagePick = (Button) findViewById(R.id.btn_image_pick);
        imageView = (ImageView) findViewById(R.id.imageView1);
       
        btnImagePick.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                 Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, REQUEST_CODE);
           
               
            }
        });
    }
     
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
          try {
            // We need to recyle unused bitmaps
            if (bitmap != null) {
              bitmap.recycle();
            }
            InputStream stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(bitmap);
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        super.onActivityResult(requestCode, resultCode, data);
      }
}


                                                                                        Android For Beginners
Read More...

AlertDialog in Android

Leave a Comment
Today I am going  to demonstrate how to use alert dialog box in android. I have created a demo project named alertDemo. In this project on the launch of application alert box will come asking you to continue with the application with having Yes and No buttons. On the tap of buttons desired functionality happen.
Step 1:- MainActivity.java
package com.arpit.alertdemo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // settin up an alert
       
        AlertDialog.Builder alert = new AlertDialog.Builder(
                MainActivity.this);
        // set title for the alert
        alert.setTitle("AlertDemo");
        // set message
        alert.setMessage("Do you want to continue with the application?");
        alert.setPositiveButton("YES", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                   
                dialog.dismiss();   
                       
            }
        });
        alert.setNegativeButton("CANCEL", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                finish();
            }
        });
       
       
        alert.show();
       
        setContentView(R.layout.activity_main);
    }
    @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;
    }
}
Step 2:-  activity_mai.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" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</RelativeLayout>
Read More...

Tuesday, 30 July 2013

Android Architecture

Leave a Comment
  • Android runs on the top of Linux Operating System.
  • It has Dalvik Virtual Machine (DVM), optimized for mobile phones.
  • It is integrated browser based on Web kit engine.
  • Open GL ES for graphics.
  • Sqlite Support for database.
  • Media Support
  • GSM Technology
  • Bluetooth, EDGE, 3G, wi-fi

Application Fundamentals
  • It is mostly written in java programming language.
  • Final output of the android program is .apk file.
  • Android consist of Components, resources, and AndroidManifest file.
  • Components of Android are:-
  1. Activities
  2. Services
  3. Content Providers
  4. Broadcast Receiver
Activites
  • An Activity represents User Interface which is visible to the user.
  • Typically an android application have many activities.
  • Every Activity in android has a life Cycle.
  • User Interface can be built in XML or Java.
Services
  • Service performs long running operation in the background.
  • Service doesn't have any User Interface.
  • Example:- music player is the example of service.
Content Providers
  • Content Providers is the interface to data for all the application.
  • Can be used to store and retrieve data and make it accessible to all application.
  • Example:- Content Providers for the Contacts, if we want to access phonebook through any application.
Broadcast Receiver
  • It is the component that will respond to the system wide events.
  • It doesn’t have any User Interface.
  • An application can have its own Broadcast Receiver that will respond to the particular event.
  • Example :- Incoming call is an events, that Broadcast Receiver will receive and you can perform some action when any incoming call comes.
Android Manifest file
  • It is in the root of the android project folder.
  • It describes used components in the application.
  • It describes the permission need to run the application.
Read More...

Monday, 29 July 2013

How to Send Email in Android Programmatically

Leave a Comment

Today we will learn how to Send Email in android Programmatically. To demonstrate this , I have made a demo project named SendEmail. In this project I have three Textview one for Email Address, one for Subject and last one for message. I am also having one send button,on the tap of it a chooser will popup asking for  Gmail client.
Step 1:-  create 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" >

    <EditText
        android:id="@+id/editText_emailAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Email"
        android:inputType="textEmailAddress" >
    </EditText>

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

    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteTextView_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Message" >
    </MultiAutoCompleteTextView>

    <Button
        android:id="@+id/button_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Send " />

</LinearLayout>

Step 2:- ActivityMain.java
package com.arpit.sendemail;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ActivityMain extends Activity {
    TextView emailadd, sub, message;
    Button btnsend;

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

        emailadd = (TextView) findViewById(R.id.editText_emailAdd);
        sub = (TextView) findViewById(R.id.editText_subject);
        message = (TextView) findViewById(R.id.multiAutoCompleteTextView_message);
        btnsend = (Button) findViewById(R.id.button_send);

        btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String emailAddress = emailadd.getText().toString();
                String emailSubject = sub.getText().toString();
                String emailMessage = message.getText().toString();

                // below is the code for sending an email
                Intent emailIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        emailAddress);
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        emailSubject);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        emailMessage);
                startActivity(emailIntent);

            }
        });
    }
}

Step 3:- Manifest file
Need to add internet permission in the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"

    package="com.arpit.sendemail"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

   <uses-permission android:name="android.permission.INTERNET"/>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



Catch Me On: CreateAppFaster.com
Read More...

Sunday, 28 July 2013

Send sms in Android Programmatically

1 comment
Today we will learn how to send Sms in android Programmatically. It is often required to have the functionality in your application where you want to send some important message or information to other user/receiver. To demonstrate this functionality I have created a simple demo project named Smsdemo. In this project we will be having two text view one for entering number and one for text or message and one send button. On the tap of it, the message will send to number entered number.

Step 1:- create a layout in the project in layout folder, named 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" >
    <EditText
        android:id="@+id/EditText_PhoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Number"
        android:inputType="phone" >
    </EditText>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="250dp" >
        <EditText
            android:id="@+id/MainActivity_Message"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:ems="10"
            android:hint="Enter message"
            android:inputType="textMultiLine" />
    </RelativeLayout>
    <Button
        android:id="@+id/Send_msg_Btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send_Message" />
</LinearLayout>

Step 2:- create a MainActivity.java
package com.example.smsdemo;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
    Button send;
    EditText phone_Number, message;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send = (Button) findViewById(R.id.Send_msg_Btn);   
        phone_Number = (EditText) findViewById(R.id.EditText_PhoneNumber);
        message = (EditText) findViewById(R.id.MainActivity_Message);
        send.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        String phone_Num = phone_Number.getText().toString();
        String send_msg = message.getText().toString();
        try {
            SmsManager sms = SmsManager.getDefault();  // using android SmsManager            sms.sendTextMessage(phone_Num, null, send_msg, null, null);  // adding number and text
        } catch (Exception e) {
            Toast.makeText(this, "Sms not Send", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

Step 3:- AndroidManifest
To send the sms in android you need to add one permission mentioned below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.smsdemo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.smsdemo.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>
    </application>
</manifest>
Catch Me On: CreateAppFaster.com
Read More...

List in Android using ListActivity Class

Leave a Comment

List View is one of the group in android, that displays a list of scrollable items. The display of elements in a lists is a very common pattern in mobile applications. The user sees a list of items and can scroll through them. An Adapter is used to list the elements in scrollable manner, which in turn gets the data from the source such as an array or from the database and convert each elements into a view of list.
Some of the commonly used  Adapter are :-
Lets Begin with Coding, to make a list I am using ListActivity Class instead of extending Activity Class.
Step 1:- Set up your project and create the main xml file, my is activity_list.xml
<TextView 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:textSize="25dp"
    android:padding="5dp">
    </TextView>
Step 2:-  In your java file,
package com.arpit.simplelistdemo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
// I am using ListActivity class instead of Activity
public class ListActivity extends android.app.ListActivity implements OnItemClickListener {
// create the array, this is going to be displayed in a list
  String[] Language = { "JAVA", "JAVASCRIPT", "JQUERY", "JQUERYMOBILE", "C",    
            "ANDRIOD", "PHONEGAP", "DATA STRUCTURE", "WINDOWS", ".NET", "AJAX",
            "C++", "SQL", "HTML5", "CSS3" };
    ListView list;                       
    ArrayAdapter<String> adapter;   // set up an adapter
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// set up an instance of adapter and passing array and layout to it      
adapter = new ArrayAdapter<String>(this, R.layout.activity_list,
                Language);
        setListAdapter(adapter);
       
        list = getListView();
        list.setOnItemClickListener(this); // click listener on tap of element on list       
    }
    public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
       
        String str = adapter.getItemAtPosition(position).toString();
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
       
    }
}
Read More...

Friday, 26 July 2013

Check Network Connectivity In Android

Leave a Comment
Today Android Application have lot of dependency on the network to perform functionality. So it is very important to find out if is our device connected to the network before performing any network related task. So, how will you find out if your device connected to the network programmatically.
Lets follow the following steps:-
I have made a separate class to check connection, named CheckConnection.java
This class will help you to find out the network connection of your device. Just create the instance of the class where ever you want to check the network connection, and pass the context of that activity to the CheckConnection.java Class.

// follow the following code

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

public class CheckConnection {
    NetworkInfo networkInfo, mobileInfo;
    WifiManager wifiSpeedTest;
    Context context;

    public CheckConnection(Context context) {    
        this.context = context;
    }

    public Boolean checkNow() {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            networkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            mobileInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (networkInfo.isConnected() || mobileInfo.isConnected()) {
                return true;
            }
        } catch (Exception e) {
            System.out
                    .println("CheckConnectivity Exception: " + e.getMessage());
        }

        return false;
    }

}
Read More...