Thursday 30 January 2014

How to set custom font for spinner in android

To set custom font for spinner we need to create our own SpinnerAdapter with our Typeface for getView and getDropDownView().

You will get your font style for spinner in just three simple steps.

To make other customization to your spinner check this link







Step 1: Just create a spinner in your layout

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

<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
</RelativeLayout>

Step 2: Create a folder in Assets and name it as fonts. Then paste your typeface (fontname.ttf) file in fonts folder.

Step 3: create a ViewGroup spinner method and call the method.
MainActivity.java:


package com.exam.spintypeface;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {

String list[]={"ϪÂah","jäH‹"};
Typeface tfavv;

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

public <ViewGroup> void spinner2meth(){
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list)
{
public View getView(int position, View convertView, android.view.ViewGroup parent) {
tfavv = Typeface.createFromAsset(getAssets(),"fonts/Avvaiyar.ttf");
TextView v = (TextView) super.getView(position, convertView, parent);
v.setTypeface(tfavv);
v.setTextColor(Color.RED);
v.setTextSize(35);
return v;
}

public View getDropDownView(int position, View convertView, android.view.ViewGroup parent) {
TextView v = (TextView) super.getView(position, convertView, parent);
v.setTypeface(tfavv);
v.setTextColor(Color.RED);
v.setTextSize(35);
return v;
}
};

adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter1);
}

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

Saturday 25 January 2014

Populate spinners using object returned by soap web service in android.

Here we populate two spinners with strings returned from soap object web service depend upon item selected in first spinner we call the second service and display values in second spinner.

If your web service response is string array and you need to populate only one spinner check this link







Step 1: Design your layout file. Here I've given simple design with two spinners.

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

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="25dp"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceLarge" />

<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="25dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/spinner1"
android:layout_below="@+id/spinner1"
android:layout_marginTop="26dp"
android:text="@string/state"
android:textAppearance="?android:attr/textAppearanceLarge" />

<Spinner
android:id="@+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="26dp" />

</RelativeLayout>

Step 2: Add uses permission Internet in your project manifest file.

AndroidManifest.xml:

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

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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.exam.blog.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>

Step 3:Include the KSOAP2 jar file in to your project.
Right click project ⇒ Properties ⇒ Java build path ⇒ Libraries Tab ⇒ Add External Jars ⇒ browse and add KSOAP2 Jar file.

Step 4: create a new class file in your package and name it as Bean.

Bean.java:

package com.exam.twospinner;

import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;

public class Bean implements KvmSerializable
{
public String Country;
public String State;

public Bean(){}

public Bean(String Country,String State) {
this.Country= Country;
this.State=State;
}

@Override
public Object getProperty(int arg0) {
switch(arg0)
{
case 0:
return Country;
case 1:
return State;
}
return null;
}

@Override
public int getPropertyCount() {
return 2;
}
@Override

public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Country";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "State";
break;
default:
break;
}
}

@Override
public void setProperty(int index, Object value) {
switch(index)
{
case 0:
Country= value.toString();
break;
case 1:
State= value.toString();
break;
default:
break;
}
}
}

Step 5: Then in your main class copy this code.

MainActivity.java :

package com.exam.blog;

import java.io.IOException;
import java.util.Arrays;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {

String[] stringArray,stringArray2;
String country;

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

//Asynctask class for webservice to populate first spinner


class country extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {

final String SOAP_ACTION = "http://tempuri.org/GetCountryDetails";
final String METHOD_NAME = "GetCountryDetails";
final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://192.168.1.1/test/service.asmx";

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
Bean C = new Bean();
PropertyInfo pi = new PropertyInfo();
pi.setName("Bean");
pi.setValue(C);
pi.setType(C.getClass());
Request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(Request);
envelope.addMapping(NAMESPACE, "Bean",new Bean().getClass());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
System.out.println("Request:"+Request);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
System.out.println("MainActivity.onCreate()"+response);
envelope.addMapping(NAMESPACE, "Bean",new Bean().getClass());
androidHttpTransport.call(SOAP_ACTION, envelope);
Bean[] countrylist = new Bean[response.getPropertyCount()];

for (int j = 0; j < countrylist.length; j++) {
SoapObject pii = (SoapObject) response.getProperty(j);
Bean beanobject = new Bean();
beanobject.Country = pii.getProperty(0).toString();
countrylist[j] = beanobject;
System.out.println("person: " + beanobject.Country);
}

int i = 0;
stringArray = new String[countrylist.length];
for (i = 0; i < countrylist.length; i++) {
stringArray[i] = Arrays.asList(countrylist[i].Country).toString().replace("[", "").replace("]", "");
System.out.println("stringarray: " + stringArray);
}
}
catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
spinner1meth();
}
}

//Method for populating spinner 1

public void spinner1meth(){

Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stringArray);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
country= (String) parent.getItemAtPosition(pos);

new state().execute();

}
});
}

//Asynctask class for webservice to populate second spinner

class state extends AsyncTask<Void, Void, Void> {

private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {

final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://192.168.1.1/test/service.asmx";
final String SOAP_ACTION = "http://tempuri.org/GetStateDetails";
final String METHOD_NAME = "GetStateDetails";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("sCountry", country);
Bean C = new Bean();
PropertyInfo pi = new PropertyInfo();
pi.setName("Bean");
pi.setValue(C);
pi.setType(C.getClass());
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
envelope.addMapping(NAMESPACE, "Bean",new Bean().getClass());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
System.out.println("response" + request);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();

Log.i("myApp", response.toString());
System.out.println("response" + response);

envelope.addMapping(NAMESPACE, "Bean",new Bean().getClass());
androidHttpTransport.call(SOAP_ACTION, envelope);
Bean[] statelist = new Bean[response.getPropertyCount()];

for (int j = 0; j < statelist.length; j++) {
SoapObject pii = (SoapObject) response.getProperty(j);
Bean beanobject = new Bean();
beanobject.State = pii.getProperty(1).toString();
statelist[j] = beanobject;
System.out.println("person1: " + beanobject.State);
}

int i = 0;
stringArray2 = new String[statelist.length];
for (i = 0; i < statelist.length; i++) {
stringArray2[i] = Arrays.asList(statelist[i].State).toString().replace("[", "").replace("]", "");
System.out.println("stringarray: " + stringArray2);
}
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}


@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
spinner2meth();
}
}

//Method for populating spinner2

public void spinner2meth(){
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stringArray2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onNothingSelected(AdapterView<?> parent) {
}

@Override
public void onItemSelected(final AdapterView<?> parent,
View view, final int pos1, long id) {
// your code after selecting state in second spinner
}
});
}

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

Saturday 18 January 2014

Custom titlebar with Network status on your application

An effective and useful way to find out whether we are connected to internet or not. Let's show the user's network connectivity in the App.










Step 1: Create a new andy project in eclipse. Then in layout folder create a new Android XML file.

Name the file as titlebar.xml

titlebar.xml
:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="44dip"
android:background="#888888"
android:gravity="center_vertical"
android:orientation="horizontal" >

<ImageView
android:id="@+id/appicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:contentDescription="@string/contentdesc"
android:src="@drawable/ic_launcher"
android:layout_marginLeft="10dp" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/appicon"
android:layout_marginLeft="10dp"
android:text="@string/apptitle"
android:textAppearance="?android:attr/textAppearanceSmall" />

<ImageView
android:id="@+id/netstatimg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:contentDescription="@string/contentdesc1"
android:gravity="right"
android:src="@drawable/ic_launcher" />

</RelativeLayout>

Step 2: Now create another XML file in res/values Name it as customtheme.xml

customtheme.xml :


<?xml version="1.0" encoding="utf-8"?>
<resources>

<style name="appTheme" parent="@android:style/Theme.Black">
<item name="android:textColor">#ffffff</item>
<item name="android:windowTitleBackgroundStyle">@style/titleBarBackground </item>
<item name="android:windowTitleSize">44dip</item>
</style>

<style name="titleBarHeading" parent="@android:style/TextAppearance">
<item name="android:textSize">25sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">#444444</item>
</style>

<style name="titleBarBackground">
<item name="android:background">@android:color/transparent</item>
<item name="android:padding">0px</item>
</style>
</resources>

Step 3: And your Project Manifest file should contain the following code:

Add ACCESS_NETWORK_STATE in uses permission in AndroidManifest file.


AndroidManifest.xml:

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/appTheme" >

Step 4: Now paste two images for network connected and disconnected in drawable folder. For good result let the size of the image be 150 x 150 in .png format. Make sure that your images indicates network connectivity and disconnection.

Step 5: Paste the following code in your MainActivity.java class file.

MainActivity.java


package com.examp.one;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private boolean isConnected = false;
TextView st;
private NetworkChangeReceiver receiver;
ImageView imageview;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
st=(TextView)findViewById(R.id.status);
imageview = (ImageView)findViewById(R.id.netstatimg);
}

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

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
System.out.println("Receieved notification about network status");
isNetworkAvailable(context);
}

private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if(!isConnected){
System.out.println("Now you are connected to Internet!"); //prints on logcat
st.setText("Connected");//Set text when connected
st.setTextColor(Color.parseColor("#059e1e"));// set color of text to green
imageview.setImageResource(R.drawable.connected1);//set connected image
Toast.makeText(context, "Connected to Network",
Toast.LENGTH_LONG).show();//make a tost to display connection
isConnected = true;
}
return true;
}}}}

System.out.println("You are not connected to Internet!");//prints on logcat
st.setTextColor(Color.parseColor("#fa051c"));// set color of text to red
st.setText("Disconnected");//Set text when connected
imageview.setImageResource(R.drawable.disconnected1);//set disconnected image
Toast.makeText(context, "Not Connected to any Network",
Toast.LENGTH_LONG).show();// Make a toast to display disconnection
isConnected = false;
return false;
}
}