Tuesday, July 30, 2013

Send Email Via Gmail with Java Mail API in Android

Hi Guys!

Today I am sharing the code to send the email via gmail to any gmail user without interfere of any application with help of java mail API.
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.
In our application we are going to use following things from JavaMail API:
  • Multipart class: - it allow to device message into multipart so that long message can be sent easily.
  • Session: - in order to send mail we need to create session between hosts.
  • InternetAddress : it contains address , simply maid ID (example: abc@gmail.com).
For use of this you need to download the some jar file from Here.
1.  additional.jar
2. mail.jar
3. activation.jar

Download these jar file and make a java build path with your project.

Lets Start the coding to make a android project.

activity_main.xml















MainActivity.java

package com.sunil.sendmail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sunil.sendmail.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
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{

Session session=null;
ProgressDialog pdialog=null;
Context context=null;
EditText reciept=null;
EditText sub=null;
EditText msg=null;
String recpient=null;
String subject=null;
String textmessage=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
Button login = (Button) findViewById(R.id.mBtnSubmit);
reciept=(EditText)findViewById(R.id.editText_to);
sub = (EditText) findViewById(R.id.editText_sub);
msg = (EditText) findViewById(R.id.editText_text);


login.setOnClickListener(this);


}

@Override
public void onClick(View v) {

recpient= reciept.getText().toString();
subject= sub.getText().toString();
textmessage= msg.getText().toString();

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Your Gmail-ID", "Your Gmail_password");
}
});
pdialog = ProgressDialog.show(context, "", "Sending Mail...",true);
RetreiveFeedTask task= new RetreiveFeedTask();
task.execute();
}


class RetreiveFeedTask extends AsyncTask {


protected String doInBackground(String... urls) {
try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("
Your Gmail-ID"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recpient));
message.setSubject(subject);
message.setContent(textmessage, "text/html; charset=utf-8");

Transport.send(message);


}
catch (MessagingException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();

}
return null;
}

protected void onPostExecute(String feed) {
pdialog.dismiss();
reciept.setText("");
msg.setText("");
sub.setText("");
Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG).show();

}
}


}

Add the INTERNET permission in the AndroidManifest file .
  <uses-permission android:name="android.permission.INTERNET"/>

You can download the source code Send Mail.

Cheers Guys!

Wednesday, July 24, 2013

Google Map Android API V2 with Location GeoCoding

Hi Guys,

Today I am sharing the code about Google Map Android V2 and get the location on map by Geo-coding.
In this new version of Google Map Android there are many things are changed now.

1. For using  this new feature you have installed the Google Play Service in your android SDK Manager. So need to installed. After installed this feature of sdk then automatically created the the google play service library project in your default folder (sdk\extras\google\google_play_services\libproject) .
Because we need to add this library project with our new android project with Google Map.
See the screen shot.

2. Now need to create the Google API key from Google API console. 
 Before create the new Google API key you need to switch on service of Google Map Android V2 from your Google Services. Please see the screen shot.
  



3. Now the next step need to create the SHA1 finger print by using the keytool and your project name.
So create the the Android name folder inside the C drive (C:\Android ) of your computer. And put the two file inside this folder. 1. debug.keystore 2. keytool.exe


4. In the next step you need to run the command on cmd to generate the SHA1 finger print key by using this keystore. So the command is :
keytool -list -v -keystore "C:\Android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
After run this command on cmd it will create the SHA1 finger key.


5. In this step you just copy thus SHA1 key from cmd and paste on the Google console of configure android key for API project with your android project package name.

After that your API key will show on your Google console. Now you can use that API key in your project.

6. Now need to import the Google-play -service_lib project in your eclipse. This project is stored inside the (sdk\extras\google\google_play_services\libproject).

7. So here we start the create the new project name "GoogleMapLocationAPIV2" and set the target with Google API and add the Google play service library project with this project. See the screen shot.


  • Then right click of project  select , Click �Android Tools -> Add Support Library �. In the new API it is already available then no need to add. Add only in below API.

activity_main.xml




MainActivity.java

package com.sunil.apiv2map.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sunil.apiv2map.R;

public class MainActivity extends FragmentActivity {

Button mBtnFind;
GoogleMap mMap;
EditText etPlace;

private static final String TAG="MainActivity";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG+"onCreate", "onCreate call");
// Getting reference to the find button
mBtnFind = (Button) findViewById(R.id.btn_show);

// Getting reference to the SupportMapFragment
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

// Getting reference to the Google Map
mMap = mapFragment.getMap();


//MapFragment mapfragment =(MapFragment) getFragmentManager().findFragmentById(R.id.map);
// mMap=mapfragment.getMap();
// Getting reference to EditText
etPlace = (EditText) findViewById(R.id.et_place);

// Setting click event listener for the find button
mBtnFind.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// Getting the place entered

Log.v(TAG+"onClick", "onClick call");
String location = etPlace.getText().toString();

if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}

String url = "https://maps.googleapis.com/maps/api/geocode/json?";

try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

String address = "address=" + location;

String sensor = "sensor=false";


// url , from where the geocoding data is fetched
url = url + address + "&" + sensor;
Log.v(TAG+"onClick", "url is: "+url);
// String modifiedURL= url.toString().replace(" ", "%20");

// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();

// Start downloading the geocoding places
downloadTask.execute(url);



}
});

}

private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);


// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}

data = sb.toString();

br.close();

}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}

return data;

}


/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask{

String data = null;

// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}

// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result){

ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}

}


class ParserTask extends AsyncTask>>{

JSONObject jObject;


@Override
protected List> doInBackground(String... jsonData) {

List> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();

try{
jObject = new JSONObject(jsonData[0]);

/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);

}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}

// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List> list){

// Clears all the existing markers
mMap.clear();

for(int i=0;i hmPlace = list.get(i);

double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));

String name = hmPlace.get("formatted_address");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name);

mMap.addMarker(markerOptions);

// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}

}

GeocodeJSONParser.java

package com.sunil.apiv2map.activity;

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

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

public class GeocodeJSONParser {

public List> parse(JSONObject jObject){

JSONArray jPlaces = null;
try {
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}

return getPlaces(jPlaces);
}


private List> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List> placesList = new ArrayList>();
HashMap place = null;

/** Taking each place, parses and adds to list object */
for(int i=0; i getPlace(JSONObject jPlace){

HashMap place = new HashMap();
String formatted_address = "-NA-";
String lat="";
String lng="";


try {
// Extracting formatted address, if available
if(!jPlace.isNull("formatted_address")){
formatted_address = jPlace.getString("formatted_address");
}

lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");


place.put("formatted_address", formatted_address);
place.put("lat", lat);
place.put("lng", lng);


} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}

Now to add the manifest file the API key and Permissions . Please see the screen shot.


After run the project Google Map is loaded and  find the location "btm layout Bangalore" screen looks like that:


And you can use the functionality of ZOOM when click on + button the location looks like that.


You can download the source code GoogleMapLocationAPIV2

Cheers Guys!!

Saturday, July 20, 2013

Fragment List With Image and text with Detail

Hi Guys!

Today I am sharing the important code of fragment list view with image and text. I am using android support library  for this fragment.
A Fragment represents a behavior or a portion of user interface in an Activity. More detail about the fragment visit the android developer site here

Why would we use a fragment?

You can create all your logic in an Activity and then manipulate the screen based on device size and orientation but the amount of code to pro grammatically draw views and implement all the logic based on layout and/or orientation will be make the whole project more complex than it needs to be. This is where fragments come to rescue, you can separate out the logic based on a functional entity rather than how the whole application looks to the end user.

Fragment is available in android support library for more detail visit the android developer site here

Here we are using the cursor adapter for showing the item in list view with help of fragment by using the functionality onCreateView(). So lets start the coding the fragment that managed the portrait and landscape mode. And in details page we can use the the view pager that makes to swipe the item details from left to right. For more details about the View Pager please visit the android developer site here
I am not add to all code but added some code that are important to show this structure. 

 
Please watch the video.
 Screen shot in landscape mode:



layout/activity_main.xml








layout-land/activity_main.xml








fragment_list_selector








fragment_listview.xml






fragment_image_pager.xml









list_row_item.xml









>






CustomArrayAdapter.java

package com.example.fragmentactionbar;


import java.util.ArrayList;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomArrayAdapter extends ArrayAdapter{

private static final String TAG="CustomArrayAdapter";
private final int mLayoutResourceId;
private DataItem[] dataitem1=null;



public CustomArrayAdapter(Context context, int textViewResourceId, DataItem[] dataitem) {
super(context, textViewResourceId, dataitem);
Log.v(TAG, "CustomArrayAdapter call");
mLayoutResourceId = textViewResourceId;
dataitem1=dataitem;
}

@Override
public int getCount() {
Log.v(TAG, "Size of the list is:" +dataitem1.length);
return dataitem1.length;
}

@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {

final ItemViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(mLayoutResourceId, null);

holder = new ItemViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.list_row_image_imageview);
holder.nameText = (TextView) convertView.findViewById(R.id.textView_friendname);
holder.nikeNameText = (TextView) convertView.findViewById(R.id.textview_friendnickname);
convertView.setTag(holder);
}
else {
holder = (ItemViewHolder) convertView.getTag();
}

DataItem item=getItem(position);
String name = item.getName();
int imageResId = item.getImageResId();
String nikename =item.getNickname();

Log.v(TAG, "name is: "+name);
Log.v(TAG, "nick name is: "+ nikename);


// Get a smaller version of the image to display in the list for less memory usage
Resources res = getContext().getResources();
int dimensInPixels = res.getDimensionPixelSize(R.dimen.list_row_image_item_dimensions);
Bitmap sampledBitmap = ImageUtils.decodeSampledBitmapFromResource(getContext().getResources(),
imageResId, dimensInPixels, dimensInPixels);

// Update the views
holder.nameText.setText(name);
holder.imageView.setImageBitmap(sampledBitmap);
holder.nikeNameText.setText("Nick Name: "+nikename);

return convertView;
}

private class ItemViewHolder {
public ImageView imageView;
public TextView nameText;
public TextView nikeNameText;
}


}

ItemListFragment.java

package com.example.fragmentactionbar;


import java.util.ArrayList;


import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ItemListFragment extends Fragment implements OnItemClickListener, ImageSelector{

private static final String TAG="ItemListFragment";
private ListView mListView;
private CustomArrayAdapter cursorArrayAdapter;
private OnItemSelectedListener mParentOnItemSelectedListener;
private Boolean status;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate: savedInstanceState " + (savedInstanceState == null ? "ture" : "false") + " null");

if (savedInstanceState != null) {
status = false;
}
else {
status = true;
}
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.v(TAG+"onAttach", "onAttach call");

Fragment parentFragment = getParentFragment();
if (parentFragment != null && parentFragment instanceof OnItemSelectedListener) {
mParentOnItemSelectedListener = (OnItemSelectedListener) parentFragment;
}

else if (activity != null && activity instanceof OnItemSelectedListener) {
mParentOnItemSelectedListener = (OnItemSelectedListener) activity;
}

else if (mParentOnItemSelectedListener == null) {
Log.w(TAG, "onAttach: niether the parent fragment or parent activity implement OnImageSelectedListener, "
+ "image selections will not be communicated to other components");
}

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.v(TAG, "onCreateView: savedInstanceState " + (savedInstanceState == null ? "true" : "false") + " null");
View v = inflater.inflate(R.layout.farfment_listview, container, false);

mListView = (ListView) v.findViewById(R.id.fragment_image_list_listview);
mListView.setOnItemClickListener(this);
cursorArrayAdapter=new CustomArrayAdapter(getActivity(), R.layout.list_row_item, StaticItemData.getImageItemArrayInstance());
mListView.setAdapter(cursorArrayAdapter);
mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);

// If first creation of fragment, select the first item
if (status && cursorArrayAdapter.getCount() > 0) {

// Default the selection to the first item
mListView.setItemChecked(0, true);
}

// initial onCreate
if (status) {
status = false;
}

return v;
}

@Override
public void onItemClick(AdapterView arg0, View arg1, int position, long id) {
Log.d(TAG, "onItemClick: " + "pos: " + position + " id: " + id);

// Highlight the selected row
mListView.setItemChecked(position, true);
if (mParentOnItemSelectedListener != null) {
DataItem dataItem= cursorArrayAdapter.getItem(position);
mParentOnItemSelectedListener.onItemSelected(dataItem, position);
}
}

@Override
public void setImageSelected(DataItem dataItem, int position) {

if (isResumed()) {
// If the selected position is valid, and different than what is
// currently selected, highlight that row in the list and
// scroll to it
if (position >= 0 && position < cursorArrayAdapter.getCount()
&& position != mListView.getCheckedItemPosition()) {
Log.d(TAG, "setImageSelected: title = " + dataItem.getName() + " position = " + position);

// Highlight the selected row and scroll to it
mListView.setItemChecked(position, true);
mListView.smoothScrollToPosition(position);
}
}
}


}

ItemPagerFragment.java

package com.example.fragmentactionbar;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ItemPagerFragment extends Fragment implements OnPageChangeListener, ImageSelector{

private static final String TAG="ItemPagerFragment";
private ViewPager mViewPager;
private ItemPagerAdapter mImagePagerAdapter;
private OnItemSelectedListener mParentOnImageSelectedListener;
private DataItem[] mPagerImageItems;


@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.v(TAG, "onAttach");

// Check if parent fragment (if there is one) implements the image
// selection interface
Fragment parentFragment = getParentFragment();
if (parentFragment != null && parentFragment instanceof OnItemSelectedListener) {
mParentOnImageSelectedListener = (OnItemSelectedListener) parentFragment;
}
// Otherwise, check if parent activity implements the image
// selection interface
else if (activity != null && activity instanceof OnItemSelectedListener) {
mParentOnImageSelectedListener = (OnItemSelectedListener) activity;
}
// If neither implements the image selection callback, warn that
// selections are being missed
else if (mParentOnImageSelectedListener == null) {
Log.w(TAG, "getting null");
}
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate: savedInstanceState " + (savedInstanceState == null ? "==" : "!=") + " null");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v(TAG, "onCreateView: savedInstanceState " + (savedInstanceState == null ? "==" : "!=") + " null");

// Inflate the fragment main view in the container provided
View v = inflater.inflate(R.layout.fragment_image_pager, container, false);

// Setup views
mViewPager = (ViewPager) v.findViewById(R.id.fragment_image_pager_viewpager);
mPagerImageItems = StaticItemData.getImageItemArrayInstance();
mImagePagerAdapter = new ItemPagerAdapter(mPagerImageItems);
mViewPager.setAdapter(mImagePagerAdapter);

// Listen for page changes to update other views
mViewPager.setOnPageChangeListener(this);

return v;
}


@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.v(TAG, "onViewCreated");
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v(TAG, "onActivityCreated");
}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.v(TAG, "onViewStateRestored");
}


@Override
public void onPageScrollStateChanged(int state) {
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}

@Override
public void onPageSelected(int position) {
Log.d(TAG, "onPageSelected: " + position);

// Inform our parent listener that an image was selected
if (mParentOnImageSelectedListener != null) {
mParentOnImageSelectedListener.onItemSelected(mPagerImageItems[position], position);
}
}


@Override
public void setImageSelected(DataItem dataitem, int position) {
if (isResumed()) {
// If the selected position is valid, and different than what is
// currently selected, move the pager to that image
if (position >= 0 && position < mImagePagerAdapter.getCount()
&& position != mViewPager.getCurrentItem()) {
Log.d(TAG, "setImageSelected: title = " + dataitem.getName() + " position = " + position);

// Move the view pager to the current image
mViewPager.setCurrentItem(position, true);
}
}
}

}

MainActivity.java

package com.example.fragmentactionbar;


import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.ViewGroup;


public class MainActivity extends FragmentActivity {

private static final String TAG="MainActivity";
private ViewGroup framelayoutmain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Log.v(TAG, "onCreate: savedInstanceState " + (savedInstanceState == null ? "true" : "false") + " null");
setContentView(R.layout.activity_main);


if (savedInstanceState != null) {

}
else {
framelayoutmain = (ViewGroup) findViewById(R.id.activity_main);
if (framelayoutmain != null) {
Log.i(TAG, "onCreate: adding framelayoutmain to MainActivity");

// Add image selector fragment to the activity's container layout
ItemSelectorFragment imageSelectorFragment = new ItemSelectorFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(framelayoutmain.getId(), imageSelectorFragment,ItemSelectorFragment.class.getName());

// Commit the transaction
fragmentTransaction.commit();
}

}
}

}
Screen shot in portrait mode:
Cheers Guys!!

Monday, July 15, 2013

ListFragment with Support Library

Hi Guys!

Today I am going to share the code the ListFragment. ListFragment  class is available inside the the android support v4 library.
Fragment is a new concept which is introduced in Android 3.0 and its higher versions.
A fragment that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. 
ListFragment hosts a List View object that can be bound to different data sources, typically either an array or a Cursor holding query results.
For mode details, you can visit the android developer site for ListFragment.

 

activity_main.xml








FriendsList.java

package com.sunil.fragmentlistview;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class FriendsList extends ListFragment implements OnItemClickListener{

String[] myFrriends = new String[] {
"Sunil Gupta",
"Abhishek Tripathi",
"Awadhesh Diwakar",
"Amit Verma",
"Jitendra Singh",
"Ravi Jhansi",
"Ashish Jain",
"Sandeep Pal",
"Shishir Verma",
"Ravi BBD"
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayAdapter adapter= new ArrayAdapter(inflater.getContext(), android.R.layout.simple_list_item_1, myFrriends);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
// this code for item click of the list

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

getListView().setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView adapter, View view, int position, long id) {

Toast.makeText(getActivity().getBaseContext(), "Item clicked: " + myFrriends[position], Toast.LENGTH_LONG).show();

}
}

MainActivity.java

package com.sunil.fragmentlistview;

import com.sunil.fragmentlistview.R;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {

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

Saturday, July 13, 2013

What is Fragment ? And Start With HelloFragment

Hi guys!!

Today I am going to discuss about Fragment. Now it is available with new API open source library android-support v4 or v7 or v13.  android-support v13 is the recent api library.
So lets start to know about fragment the question is arises first what is Fragment?

What is Fragment in Android?

  • A fragment is a class implementing a portion of an activity.
  • A fragment represents a particular operation or interface running within a larger activity.
  • Fragments must be embedded in activities; they cannot run independent of activities.
  • Most fragments define their own layout of views that live within the activity�s view hierarchy.  
  • A fragment has its own life-cycle, closely related to the life-cycle of its host activity. 
  • A fragment can be a static part of an activity, instantiated automatically during the activity�s creation.
  • Or, you can create, add, and remove fragments dynamically in an activity at run-time.

What is Life cycle of Fragment ?

Fragments have a few extra life cycle callbacks managing interaction with the activity:
onAttach(Activity) => Called when the fragment has been associated with the activity.
onCreateView(LayoutInflater, ViewGroup, Bundle) => Called to create the view hierarchy associated   
 with the fragment.
onActivityCreated(Bundle) => Called when the activity�s onCreate() method has returned.
onDestroyView() => Called when the view hierarchy associated with the fragment is being removed.
onDetach() => Called when the fragment is being disassociated from the activity.


  Fragment Implemented ?

Fragments were added to the Android API in Honeycomb, API 11.
The primary classes related to fragments are:
android.app.Fragment 
android.app.FragmentManager 
android.app.FragmentTransaction
 
The primary classes related to fragments are available in library package are:
android.support.v4.app.FragmentActivity
android.support.v4.app.Fragment
android.support.v4.app.FragmentManager
android.support.v4.app.FragmentTransaction
 
To use the Compatibility Package features, your activity must use android.support.v4.app. FragmentActivity as a base class, rather than android.app.Activity or one of its subclasses. 
 
Lets start the use of this fragment with Simple Hello Fragment. 

main.xml





hello_fragment.xml





HelloFragment

package com.sunil.fragment;

import com.sunil.fragment.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class HelloFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_fragment_layout, null);
return v;
}

}

MainActivity.java

package com.sunil.fragment;

import com.sunil.fragment.R;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {

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

Cheers Guys!!

Please share this site guys!
KidsMitra

Tuesday, July 2, 2013

Mostly Used Android Code

Hi Guys!

Today I share the code that are mostly used in the android. I collected the all the small part of the code that are used most of the cases. I hope you also enjoyed with this.

1. How to Disable Home Button



@Override
public void onAttachedToWindow()
{
this.getWindow().setType(WindowManager.
LayoutParams.TYPE_KEYGUARD_DIALOG);
super.onAttachedToWindow();
}

2. How to Disable Back Button



@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}

3. How to Disable Soft Keypad




final EditText txtName = (EditText) findViewById(R.id.txtName);
txtName.setInputType(InputType.TYPE_NULL);


4. How to Make Static Rotation/orientation in Android


//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
or
//if you want to lock screen for always Landscape mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

5. How to Disable screen Rotation/orientation in Android (better way is java code)


//put this code in Manifest file, activity tag
android:screenOrientation="nosensor"
android:configChanges="keyboardHidden|orientation|screenSize"

/* or even you can do it by programmatically -- just put
Configuration code in onResume method before calling super
like this */
@Override
protected void onResume() {
int currentOrientation = getResources().getConfiguration()
.orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE)
{
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
else {
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
super.onResume();
}


6. How to Disable Title Bar and Make Full Screen View


//1. put this line to manifest file in Application tag
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

//2. put below code in your activity onCreate method

//to disable notification bar (Top Bar)
requestWindowFeature(Window.FEATURE_NO_TITLE);


//to set full screen view
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

//make sure code should be before calling below method
setContentView(R.layout.main);

7. How to Create Alert Dialog Box in Android




AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("App has been started..")
.setCancelable(false)
.setTitle("Alert Box")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();


8. How to Create Toast message in Android



Toast.makeText(getApplicationContext(), "I am splash message..",
Toast.LENGTH_LONG).show();

9. How to create Progress Dialog in Android




ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);

10. Load Home Screen Programmatically in Android


Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain)

11. Start/Load Activity from Activity



//put this code where you want to load another Activity
Intent intent = new Intent(FirstActivty.this, SecondActivity.class);

//below 2 lines (Flags) are optional
// 1. if set, it will clear the back stack
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

// 2. If set, this activity will become the start of a new task
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

12. Make a Phone Call




String mobileNo = "+9189000000";
String uri = "tel:" + mobileNo.trim() ;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);

//add permission to Manifest file




13. How to check WiFi is Connected or Not


public void chekcWifiConnectDisconnect() {
ConnectivityManager connManager = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
Log.v("Debug", "Wifi is connectd..");
} else {
Log.v("Debug", "Wifi is not connectd..");
}

}

//dont forget to put Wifi permission in manifest file

 

Copyright @ 2013 Android Developers Tipss.