Check internet connection status in android

Almost every android application these days require accessing internet for fetching and posting data. Posting and fetching data usually causes exceptions due unavailability of internet . Hence , to always good to check internet connection before starting tasks that requires  internet connection. Check this post if you want to how to make http connections.

You can also check the  kind of internet connection is available in handset.eg wifi or mobile data

The following code snippet will let you check internet availability and specify the type of internet connection available.

Step 1. Firstly  you need to add the following permission in the AndroidManifest.

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

Step 2: Use the following code to check internet status

private boolean isNetworkConnected() {
// checks for both mobile and wifi internet connection
boolean isConnectedWifi = false;
boolean isConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[]info = cm.getAllNetworkInfo();
for (NetworkInfo net : info) {
if (net.getTypeName().equalsIgnoreCase("WIFI"))
if (net.isConnected())
haveConnectedWifi = true;
if (net.getTypeName().equalsIgnoreCase("MOBILE"))
if (net.isConnected())
haveConnectedMobile = true;
}
return isConnectedWifi || isConnectedMobile;
}

Always remember to check to internet availability before performing any tasks that require internet .

Related Posts:

Making  http connection in android

Using shared preferences in android

Storing app data is an essential requirement of most applications. Android lets your store data using Shared Preferences and Sqlite database. You can use either of them, based on your requirement. Check this post to decide which one suits your requirement

Shared Preferences  stores data as key-pairs only. Key is required to read data from it. Reading amd storing data in it is very simple .But, it’s difficult to store and read large structured data . It saves  primitives data type like string, int ,booleans, floats ,long etc. It is best to use Shared Preferences when only small amount of data needs to be stored eg few app settings, user login /password etc.

Step 1: Create your shared preferences in the following way :

SharedPreferences myPreferences = this.getSharedPreferences("myPreferences", 0);

Step 2: Save values in shared preferences using editor.
“myInt” is the key and “2” is the value to be stored

SharedPreferences.Editor prefEditor = myPreferences.edit();
		prefEditor.putInt("myInt", 2);
		prefEditor.commit();

Step 3: Retrieve values from shared preferences using the key. Second parameter of getInt(“myInt”, 0) denotes the default value to be returned if no value is saved yet.

myPreferences.getInt("myInt", 0);

Complete Example:

public class SharedPreferenceActivity extends Activity implements
		OnClickListener {
	SharedPreferences myPreferences;
	EditText nameEditText, AgeEditText;
	Button saveBtn, showBtn;
	TextView showTextview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		nameEditText = (EditText) findViewById(R.id.nameEdittext_id);
		AgeEditText = (EditText) findViewById(R.id.ageEdittext_id);
		saveBtn = (Button) findViewById(R.id.saveBtn_id);
		showBtn = (Button) findViewById(R.id.showBtn_id);
		showTextview = (TextView) findViewById(R.id.showText_id);
		// creating "myPreferences" sharedPreference
		myPreferences = this.getSharedPreferences("myPreferences", 0);

		saveBtn.setOnClickListener(this);
		showBtn.setOnClickListener(this);

	}

	void setIntAppPref(int a) {
		SharedPreferences.Editor prefEditor = myPreferences.edit();
		prefEditor.putInt("myInt", a);
		prefEditor.commit();
	}

	int getIntAppPref() {
		return myPreferences.getInt("myInt", 0);
	}

	void setStringAppPref(String a) {
		SharedPreferences.Editor prefEditor = myPreferences.edit();
		prefEditor.putString("myString", a);
		prefEditor.commit();
	}

	String getStringAppPref() {
		return myPreferences.getString("myString", "");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.saveBtn_id:
			setStringAppPref(nameEditText.getText().toString());
			setIntAppPref(Integer.parseInt(AgeEditText.getText().toString()));

			break;
		case R.id.showBtn_id:
			showTextview.setText("Name:" + getStringAppPref() + '\n' + "Age:"
					+ getIntAppPref());

			break;

		default:
			break;
		}

	}

}

Screenshots:

pref1              pref2

Download the example code here

download_image.

Related Posts:

Difference between sqlite and shared preferences in android

PreferenceActivity in Android

 

Difference between sqlite and shared preferences in android

Storing app data is an essential requirement of most applications. Android lets your store data using Shared Preferences and Sqlite database. You can use either of them, based on your requirement.

Shared Preferences

Shared Preferences stores data as key-pairs only. Key is required to read data from it. Reading amd storing data in it is very simple .But, it’s difficult to store and read large structured data . It saves  primitives data type like string, int ,booleans, floats ,long etc. It is best to use Shared Preferences when only small amount of data needs to be stored eg few app settings, user login /password etc.

Sqlite Database

It stores structured data as a database. The data can be queried and hence ,this makes it possible to search database. Reading data from sqlite database is slower and more expensive then shared preferences. SQLite database is useful for just about anything and very flexible. It is best to use Sqlite when the data to be stored is large , structured and required searching .eg storing complete user details , storing data fetched by http request etc.

Related Posts:

PreferenceActivity in Android

Using shared preferences in android

Listview with header footer view android

At times we need to add some title to a list view or show some data at the very end of list view . For this we need not pass this data in adapter of listview , instead we can add it as header and views in the following way.

If you are not sure how to create a listview  you can refer these examples.

Step 1: Create a layout xml for the header and footer as per your requirement.

header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="HEADER"
    android:background="#cf9f99" />

</LinearLayout>

footer.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="FOOTER"
    android:background="#cf9f99" />

</LinearLayout>

Step 2: Now let’s inflate these header and footer views and add it to our list view .

LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
				false);
		ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
				false);
		listView.addHeaderView(header, null, false);
		listView.addFooterView(footer, null, false);



Complete Code 

LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
				false);
		ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
				false);
		listView.addHeaderView(header, null, false);
		listView.addFooterView(footer, null, false);

Complete Code

public class MainActivity extends Activity {
	ListView listView;

	static final String[] numbers = new String[] { "one", "two", "three",
			"four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
			"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
			"seventeen", "eighteen", "nineteen", "twenty", "twenty one",
			"twenty two" };
	View header;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.list_id);

		//code to add header and footer to listview
		LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
				false);
		ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
				false);
		listView.addHeaderView(header, null, false);
		listView.addFooterView(footer, null, false);

		ArrayAdapter adapter = new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, numbers);

		listView.setAdapter(adapter);

	}

}

Screenshots:

footerList                        headerList

Download this example form here .

Related Links:

GridView Array Adapter Example

ListView ArrayAdapter Example

Custom ListView Example

Custom Grid View Example

Custom GridView Android

GridView is used to display items in a two-dimensional, scrollable grid form. The grid items are automatically inserted to the layout using a Adapter.

For example,  displaying grid of icons. Item is represented by a single item view. This pattern is quite handy as it shows several icons on screen at the same time. Its helps displaying grids of data in a very simple and scrollable grid manner.

The simplest way to display a grid view is using ArrayAdapter class . You can find the gridview arrayadapter example here.

We can also create our own custom adapters using BaseAdapter class. Custom Adapters are way better than array adapters, they give you more control over the list/grid view content and UI .Here we inflate each row of GridView using a layout.

The following example explains the usage of ListView using a custom adapter.

Step1: Create the xml for the activity which contains a ListView

 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=".GridViewActivity" >

<GridView
android:id="@+id/grid_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>

</RelativeLayout>

Step 2: Create a custom layout for each row of the Grid View.

 grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/textView_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />

</LinearLayout>

Step 3: Create a custom adapter in the following way .

GridAdapter.java 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class GridAdapter extends BaseAdapter {

	String[] textArray;
	Context contxt;

	public GridAdapter(String[] textArr, Context context) {
		textArray = textArr;
		contxt=context;
	}

	@Override
	public int getCount() {

		return textArray.length;
	}

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

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

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

		// create a new LayoutInflater
		LayoutInflater inflater = (LayoutInflater) contxt
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;
		gridView = null;
		convertView = null;// avoids recycling of grid view
		if (convertView == null) {

			gridView = new View(contxt);
			// inflating grid view item
			gridView = inflater.inflate(R.layout.grid_item, null);

			// set value into textview
			TextView textView = (TextView) gridView
					.findViewById(R.id.textView_id);
			textView.setText(textArray[position]);

		}

		return gridView;
	}

}

Step 4: Create the Activity and implement custom adapter in the activity using the code mentioned below.

  • Create  GridAdapter type adapter .
  • Set GridView adapter as this custom adapter.
  • You can set listeners on your list view also.

GridViewActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

import com.example.customgridviewexample.R;

public class GridViewActivity extends Activity {
	static final String[] numbers = new String[] { "one", "two", "three",
			"four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
			"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
			"seventeen", "eighteen", "nineteen", "twenty", "twenty one",
			"twenty two" };
	GridView gridView;
	GridAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gridView = (GridView) findViewById(R.id.grid_id);
		adapter=new  GridAdapter(numbers, this);
		gridView.setAdapter(adapter);

	}

}

 

Screenshot:

customgrid

Download

You can also download the above ListView Example here.

Related Posts:

GridView Array Adapter Example

ListView ArrayAdapter Example

Custom ListView Examle

Custom list view in android

ListView  is used for arranging items in a vertical and scrollable list. ListViews are commonly used to display a large set of similar data.

For example,  displaying list of contacts. Item/row is represented by a single item view. This pattern is quite handy as it shows several contacts on screen at the same time. Its helps displaying list of data in a very simple and scrollable manner.

The simplest way to display a list view is using ArrayAdapter class . You can study how to create ListViews using array adapter here. We can also create our own custom adapters using BaseAdapter class. Custom Adapters are way better than array adapters, they give you more control over the list/grid view content and UI .Here we inflate each row of listView using a layout.

The following example explains the usage of ListView using a custom adapter.

Step1: Create the xml for the activity which contains a ListView

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" >

    <ListView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        >
    </ListView>

</RelativeLayout>

Step 2: Create a custom layout for each row of the List View.

list_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/list_item_image"
        android:layout_width="50px"
        android:layout_height="50px"
        android:layout_marginRight="10px"
        android:background="@drawable/ic_launcher" >
    </ImageView>

    <TextView
        android:id="@+id/list_item_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5px"
        android:text="@+id/label"
        android:textSize="15px" >

    </TextView>

</LinearLayout>

Step 3: Create a custom adapter in the following way .

ImageAdapter.java 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ImageAdapter extends BaseAdapter {
	private Context context;
	private final String[] StrValues;

	public ImageAdapter(Context context, String[] StrValues) {
		this.context = context;
		this.StrValues = StrValues;
	}

	// getView that displays the data at the specified position in the data set.
	public View getView(int position, View convertView, ViewGroup parent) {
		// create a new LayoutInflater
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;
		gridView = null;
		convertView = null;// avoids recycling of grid view
		if (convertView == null) {

			gridView = new View(context);
			// inflating grid view item
			gridView = inflater.inflate(R.layout.list_view_item, null);

			// set value into textview
			TextView textView = (TextView) gridView
					.findViewById(R.id.list_item_label);
			textView.setText(StrValues[position]);

		}

		return gridView;
	}

	// Total number of items contained within the adapter
	@Override
	public int getCount() {
		return StrValues.length;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

}

Step 4: Create the Activity and implement custom adapter in the activity using the code mentioned below.

  • Create  ImageAdapter type adapter .
  • Set ListView adapter as this custom adapter.
  • You can set listeners on your list view also.

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	static final String[] StrValues = new String[] { "one", "two", "three",
			"four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
			"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
			"seventeen", "eighteen", "nineteen", "twenty", "twenty one",
			"twenty two" };
	ListView listView;

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

		listView = (ListView) findViewById(R.id.listView1);
		// setting adapter on listview
		listView.setAdapter(new ImageAdapter(this, StrValues));
		//setting on item click listener
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {//displaying toast
				Toast.makeText(
						getApplicationContext(),
						((TextView) v.findViewById(R.id.list_item_label))
								.getText(), Toast.LENGTH_SHORT).show();

			}
		});

	}
}

Screenshot:

custom Listview

Download

You can also download the above ListView Example here.

Related Posts:

Simple ListView in android

Simple GridView in android

Custom GridView in android

ListView example android

ListView  is used for arranging items in a vertical and scrollable list. ListViews are commonly used to display a large set of similar data.

For example,  displaying list of contacts. Item/row is represented by a single item view. This pattern is quite handy as it shows several contacts on screen at the same time. Its helps displaying list of data in a very simple and scrollable manner.

The simplest way to display a list view is using ArrayAdapter class . You can add lists or arrays of custom objects to it and these objects are referenced using index and displayed in the TextView of ListView.

We set the ArrayAdapter to the ListView to display the items of array adapter in   it .

The following example explains the usage of ListView using ArrayAdapter.

Step1: Create the xml for the activity which contains a ListView

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" >

    <ListView
        android:id="@+id/list_id"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="80dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </ListView>

</RelativeLayout>

Step 2:  Create the Activity and use the code mentioned below.

  • Create the ArrayAdapter and add a default layout list style and string array of data to it.
  • Set ListView adapter as the ArrayAdapter.
  • You can set listeners on your list view also.
public class MainActivity extends Activity {
	ListView listView;

	static final String[] numbers = new String[] { "one", "two", "three",
			"four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
			"twelve", "thirteen", "fourteen", "fifteen", "sixteen",
			"seventeen", "eighteen", "nineteen", "twenty", "twenty one",
			"twenty two" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.list_id);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, numbers);

		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Toast.makeText(getApplicationContext(),
						((TextView) v).getText(), Toast.LENGTH_SHORT).show();
			}
		});
	}

}

Screenshot:

ListView

You can also download the above ListView Example here

Related Posts:

GridView ArrayAdapter Example

Custom Gridview Example 

Custom Listview Example