Saturday 17 May 2014

How to animate an image to rotate with your finger touch in android

A simple animation to rotate an image with finger touch both left and right.


Lets see how to rotate image with 2D animation. I've used a steering wheel for this to make some sense.





Step 1 : Place an image file in your xml 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:background="#ffffff" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="@drawable/wheel"
android:contentDescription="@string/wheel" />

</RelativeLayout>


Step 2 : Let the main class implement onTouchListener and use the MotionEvent for rotation. Just copy the below code.

MainActivity.java :

package com.exampl.simplegame;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnTouchListener{
private ImageView wheel;
private double mCurrAngle = 0;
private double mPrevAngle = 0;
ImageView bask;

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

wheel=(ImageView)findViewById(R.id.imageView1);
wheel.setOnTouchListener(this);
}

@Override
public boolean onTouch(final View v, MotionEvent event) {
final float xc = wheel.getWidth() / 2;
final float yc = wheel.getHeight() / 2;

final float x = event.getX();
final float y = event.getY();

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
wheel.clearAnimation();
mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
break;
}
case MotionEvent.ACTION_MOVE: {
mPrevAngle = mCurrAngle;
mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));
animate(mPrevAngle, mCurrAngle, 0);
System.out.println(mCurrAngle);
break;
}
case MotionEvent.ACTION_UP : {
mPrevAngle = mCurrAngle = 0;
break;
}
}
return true;
}

private void animate(double fromDegrees, double toDegrees, long durationMillis) {
final RotateAnimation rotate = new RotateAnimation((float) fromDegrees, (float) toDegrees,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(durationMillis);
rotate.setFillEnabled(true);
rotate.setFillAfter(true);
wheel.startAnimation(rotate);
System.out.println(mCurrAngle);
}
}

Friday 16 May 2014

How to set custom font for text view or button in android

To have your own customized application of your own theme make your text look your style with custom font for your textviews and buttons.

You can check this link for custom font for spinners in android.

For custom fonts for textviews and buttons follow the simple steps given in this post.



Step 1 : In your Layout file place some text views and buttons as required for your app.

Step 2 : 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 typeface of your font and assign it for your buttons and textviews in your mainactivity.

MainActivity.java :

package com.exam.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

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

Typeface Font = Typeface.createFromAsset(getAssets(),"fonts/idr.ttf");

TextView tv1 = (TextView)findViewById(R.id.textView1);
TextView tv2 = (TextView)findViewById(R.id.textView2);
Button bt1 = (Button)findViewById(R.id.button1);

tv1.setTypeface(Font);
tv2.setTypeface(Font);
bt1.setTypeface(Font);
}

How to create custom dialog box or alert box in android

Here's a simple alert box with customization. We create the alert box through a xml layout, here we can drag any type of widgets, text fields etc.. like spinners, edit text, image in a alert box.


To create simple alert box without creating xml layout check this link.

By creating alert box though xml layout it provides a wide variety of options to be inserted in a alert box easily.





Step 1 : Create an android project. And in layout folder create a new layout for alert box.

Customize your layout file how your alert box should look like.

custom_layout.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
android:layout_width="match_parent"
 android:layout_height="wrap_content">
 
<TextView
android:id="@+id/title"
android:src="@drawable/batman"
android:layout_width="match_parent"
android:layout_height="64dp"
android:text="LOGIN"
android:gravity="center"
android:textSize="35sp"
android:background="#FFFFBB33"/>

<EditText
android:id="@+id/username"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="username" />
 
<EditText
android:id="@+id/password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="password"/>
</LinearLayout>

Step 2 : In your main activity file create alert dialog and inflate the view for alert box.

MainActivity.java :

package com.exam.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;

public class MainActivity extends Activity {

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

public void logout(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = this.getLayoutInflater();
alertDialog.setView(inflater.inflate(R.layout.custom_layout, null));

/* When positive (yes/ok) is clicked */
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel(); // Your custom code
}
});

/* When negative (No/cancel) button is clicked*/
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish(); // Your custom code
}
});
alertDialog.show();
}
}

Thursday 15 May 2014

Creating Alert box or Dialog box in android while onClick button.

This example program is for beginners those who want alert box in their application. I will create a alert box for logout that closes the application. With two options y/n.


To create alert box using xml and customize alert box check this link.

This is how your alert box looks.



I have just place a button in this activity, on-clicking this button pops out a alert box and asks for confirmation for logout.

MainActivity.java : 


package com.exam.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button logout = (Button)findViewById(R.id.button1);
logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
logout();
}
});
}

public void logout(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
 
alertDialog.setTitle("Logout"); // Sets title for your alertbox

alertDialog.setMessage("Are you sure you want to Logout ?"); // Message to be displayed on alertbox

alertDialog.setIcon(R.drawable.logout1); // Icon for your alertbox

/* When positive (yes/ok) is clicked */
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
finish();
Toast.makeText(MainActivity.this,"Successfully Logged Out", Toast.LENGTH_LONG).show();  
}
});

/* When negative (No/cancel) button is clicked*/
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}

Wednesday 14 May 2014

How to set custom font, Font size, Font color and Text background for spinner in android

Customize your spinner as you like with simple steps. Change your font color and size of your spinner text and even background of your text. Make your app look your way.

You will go through some simple steps to make changes to your android spinner's font color, font size, background color and font type.


For customizing your font type for 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"
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="44dp" />
</RelativeLayout>


Step 2: In your layout file create two android xml layout file.

First : 
selected_item.xml with TextView.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#FF5050"
android:textSize="30sp">
</TextView>


Second :
drpdown_item with CheckedTextView.

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:singleLine="true"
android:ellipsize="marquee"
android:textColor="#0099CC"
android:textSize="30sp"
android:background="#4d4d4d" >
</CheckedTextView>


Step 3: This is your main activity class according to your need call the method.
MainActivity.java:

package com.exam.customspinner;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {

String list[]={"Jan","Feb","March","April"};

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

/* Call the method you wish */

spinnermeth();
// spinnermeth1(); // Make changes to those two file to get desired result
}

public void spinnermeth(){
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.selected_item, list);
mySpinner.setAdapter(adapter);
}

public void spinnermeth1(){
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.selected_item, list);
adapter.setDropDownViewResource(R.layout.dropdown_item);
mySpinner.setAdapter(adapter);
}
}


Thursday 10 April 2014

Parse JSON format data from SOAP Web service in Android

As JSON is so much preferred for android which is said to be easier to parse, faster and power saving lets try a simple example on JSON parsing. In this example we will learn how to parse JSON data from SOAP web service and use in our android program.

Check this post if your service is in XML format.

Lets take a simple JSON format data.
Example: 

[
  {
      "J_Name" : "yashwanth",
      "J_Id" : "04",
      "J_Place":"Hosur",
      "J_Phone":"9876543210"
  }
]




Step 1 : Create a new project in Eclipse IDE File ⇒ New ⇒ Android Application Project and fill all the required details.

Step 2 : In your layout file place some text fields and align it as required.


Step 3 : Add Internet Permission 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="www.andygeeks.blogspot.com"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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="www.andygeeks.blogspot.com.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 4 : 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 and gson Jar file.

Step 5 : Now call the web service and get details with asynctask. Paste this below code in your MainActivity class file.

MainActivity.java :


package www.andygeeks.blogspot.com;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.json.JSONArray;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
   
boolean timeoutexcep=false,httpexcep=false,genexcep=false;
   
private static final String TAG_NAME = "J_Name";
private static final String TAG_ID = "J_Id";
private static final String TAG_PLACE = "J_Place";
private static final String TAG_MOBILE = "J_Phone";
   
public static String dist="Krishnagiri",type="P",no="50";
String Name,Id,Place,Phone;
   
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new pay().execute();
}

class pay 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://www.xxxxxx.com/xxxx/xxx.asmx";
final String SOAP_ACTION = "http://tempuri.org/xxxxx";
final String METHOD_NAME = "xxxxx";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("sDistrict", dist);
request.addProperty("sTaxType", type);
request.addProperty("sTaxNo", no);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

String responseJSON=response.toString();
JSONArray jarray =new JSONArray(responseJSON);

Name=jarray.getJSONObject(0).getString(TAG_NAME);
Id=jarray.getJSONObject(0).getString(TAG_ID);
Place=jarray.getJSONObject(0).getString(TAG_PLACE);
Phone=jarray.getJSONObject(0).getString(TAG_MOBILE);

System.out.println(request);
System.out.println(responseJSON);

}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(UnknownHostException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
genexcep=true;
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(genexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}

else{
tableview();
}
timeoutexcep=false;httpexcep=false;genexcep=false;
}
}

public void tableview(){
try{
TextView name = (TextView)findViewById(R.id.textView5);
name.setText(Name);

TextView door = (TextView)findViewById(R.id.textView6);
door.setText(Id);

TextView ward = (TextView)findViewById(R.id.textView7);
ward.setText(Place);

TextView mobile = (TextView)findViewById(R.id.textView8);
mobile.setText(Phone);
}
catch(Exception e){
}
}
   
@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;
}
}

Friday 14 February 2014

Scroll multiple TableLayout Horizontally and Vertically in android



This will allow you to scroll a table layout vertically and each table layout can be scrolled horizontally

First Picture : Scroll Layout containing four table layout

Second Picture : Single table layout scrolled horizontally to right.





Third Picture : Layout scrolled vertically down

Fourth Picture : Single table layout scrolled horizontally toLeft.





OverView:

<ScrollView>
  <LinearLayout>

    <TextView> // Heading 1
<HorizontalScrollView>
  <TableLayout>
    <TableRow>
      <TextView>
    </TableRow>
  </TableLayout>
</HorizontalScrollView>


  <TextView> // Heading 2
<HorizontalScrollView>
  <TableLayout>
    <TableRow>
      <TextView>
    </TableRow>
  </TableLayout>
</HorizontalScrollView>


  </LinearLayout>
</ScrollView>

Layout file :

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

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
android:id="@+id/head1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="@string/head1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TableLayout
android:id="@+id/tablelayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableRow
android:id="@+id/Tablerow1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>

<TableRow
android:id="@+id/Tablerow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
</TableLayout>
</HorizontalScrollView>

<TextView
android:id="@+id/head2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="@string/head2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TableLayout
android:id="@+id/tablelayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableRow
android:id="@+id/Tablerow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>

<TableRow
android:id="@+id/Tablerow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView19"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
</TableLayout>
</HorizontalScrollView>

<TextView
android:id="@+id/head3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="@string/head3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TableLayout
android:id="@+id/tablelayout5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableRow
android:id="@+id/Tablerow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView25"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView26"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView27"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>

<TableRow
android:id="@+id/Tablerow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView31"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView34"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView35"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView36"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
</TableLayout>
</HorizontalScrollView>

<TextView
android:id="@+id/head4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="@string/head4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TableLayout
android:id="@+id/tablelayout6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableRow
android:id="@+id/Tablerow7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView38"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView39"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView40"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView41"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView42"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>

<TableRow
android:id="@+id/Tablerow8"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" >

<TextView
android:id="@+id/textView43"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column1"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column2"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView45"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column3"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView46"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column4"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView47"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column5"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/textView48"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="@string/Column6"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
</TableLayout>
</HorizontalScrollView>
</LinearLayout>

</ScrollView>

How to get data from SOAP web service as object contains array of values

Here we shall see how to get data from SOAP web service when the response is returned as an object in XML format. When the response is object you have to create a bean class and retrieve the data. When you get single values for each variable use this post.

And when you get single value for variables (Eg. Name= yashwanth; Age=25; place=Hosur) Check this link.









Step 1 : Create a new project in Eclipse IDE File ⇒ New ⇒ Android Application Project and fill all the required details.

Step 2 : In your layout file place some text fields and align is as required.

Activity_main.xml:


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

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TableLayout
android:id="@+id/tl1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableRow
android:id="@+id/tabrow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_weight="1"
android:textAlignment="center"
android:text="@string/Id"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/Name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/Place"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

<TextView
android:id="@+id/textView4"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/District"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

</TableRow>
</TableLayout>

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="-100dp"
android:scrollbars="vertical" >

<TableLayout
android:id="@+id/tl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</TableLayout>
</ScrollView>
</LinearLayout>
</HorizontalScrollView>

Step 3 : Add Internet Permission 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.webservice2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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.webservice2.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 4 : 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 you can find it Here.

Step 5 : Now crate a new class in your existing package and name that class as Bean. Now paste the below code in your bean class file.

Bean.java :


package com.exam.webservice2;

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

public class Bean implements KvmSerializable
{
public String Id;
public String Name;
public String Place;
public String District;

public Bean(){}

public Bean(String Id,String Name, String Place,String District)
{
this.Id = Id;
this.Name=Name;
this.Place=Place;
this.District=District;
}

public Object getProperty(int arg0) {

switch(arg0)
{
case 0:
return Id;
case 1:
return Name;
case 2:
return Place;
case 3:
return District;
}
return null;
}

public int getPropertyCount() {
return 4;
}

@SuppressWarnings("rawtypes")
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Id";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Name";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Place";
break;
case 3:
info.type = PropertyInfo.STRING_CLASS;
info.name = "District";
break;

default:
break;
}
}

public void setProperty(int index, Object value) {
switch(index)
{
case 0:
Id = value.toString();
break;
case 1:
Name = value.toString();
break;
case 2:
Place = value.toString();
break;
case 3:
District = value.toString();
break;

default:
break;
}
}
}

Step 6 : Now call the web service and get details with asynctask. Paste this below code in your MainActivity class file.

MainActivity.java :


package com.exam.webservice2;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
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 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.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

String typ="P",uu="500229";
boolean timeoutexcep=false,httpexcep=false,generalexcep=false;
Bean[] personList2;
TableLayout ll;
String[] Id,Name,District,Place;
int i;

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

new propdetail().execute();
}

class propdetail 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.162.1.10/Test/Service.asmx";
final String SOAP_ACTION = "http://tempuri.org/GetDetails";
final String METHOD_NAME = "GetDetails";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("sTaxType", typ);
request.addProperty("sUserId", uu);

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 {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();

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

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

for (int j = 0; j < personList2.length; j++) {
SoapObject so = (SoapObject) response.getProperty(j);
Bean person2 = new Bean();
person2.Id = so.getProperty(0).toString();
person2.Name= so.getPropertyAsString(1).toString();
person2.Place=so.getPropertyAsString(6).toString();
person2.District=so.getPropertyAsString(7).toString();
personList2[j] = person2;
}

Id = new String[personList2.length];
Name = new String[personList2.length];
Place = new String[personList2.length];
District = new String[personList2.length];

for (int i = 0; i < personList2.length; i++)
{
Place[i] = Arrays.asList(personList2[i].Id).toString();
Id[i] = Arrays.asList(personList2[i].Name).toString();
Name[i] = Arrays.asList(personList2[i].Place).toString();
District[i] = Arrays.asList(personList2[i].District).toString();

System.out.println(Id[i]);
System.out.println(Name[i]);
System.out.println(District[i]);
System.out.println(Place[i]);
}
}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(ConnectException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
generalexcep=true;
e.printStackTrace();
}
return null;
}

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


if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(generalexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}
else {
tableview();
}
timeoutexcep=false;httpexcep=false;generalexcep=false;
}
}
public void tableview(){

ll = (TableLayout) findViewById(R.id.tl);
for (i = 0; i < personList2.length; i++)
{
final TableRow tr = new TableRow(this);
LayoutParams lp = new LayoutParams(150,LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

tr.setId(i);

tr.setLayoutParams(lp);
lp.setMargins(0, 20, 0, 0);

final TextView tvLeft = new TextView(this);
tvLeft.setLayoutParams(lp);
tvLeft.setText(Id[i]);

final TextView tvCenter = new TextView(this);
tvCenter.setLayoutParams(lp);
tvCenter.setText(Name[i]);

final TextView tvRight = new TextView(this);
tvRight.setLayoutParams(lp);
tvRight.setText(Place[i]);

final TextView tvend = new TextView(this);
tvend.setLayoutParams(lp);
tvend.setText(District[i]);

tr.addView(tvLeft);
tr.addView(tvCenter);
tr.addView(tvRight);
tr.addView(tvend);

ll.addView(tr, new TableLayout.LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Thursday 13 February 2014

How to get data from SOAP webservice object in Android

Here we shall see how to get data from SOAP web service when the response is returned as an object in XML format. When the response is object you have to create a bean class and retrieve the data. When you get single values for each variable use this post. we will also see how to parse XML data from .NET web service soap object in android.

Check this post if your service is in JSON format.

And when you get many values for single variable(Eg. Name= yashwanth, Prabhakar, Abdul, John; Id=1,2,3,4; Place = Hosur, bang, trichy, chennai ) check this post.







Step 1: Create a new project in Eclipse IDE File ⇒ New ⇒ Android Application Project and fill all the required details.

Step 2: In your layout file place some text fields and align is as required.

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_marginTop="97dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView4"
android:layout_marginTop="24dp"
android:text="Phone"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="26dp"
android:text="Place"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="20dp"
android:text="Age"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_centerHorizontal="true"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_centerHorizontal="true"
android:text=""

android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/name"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/palce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_alignLeft="@+id/phone"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Step 3: Add Internet Permission 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.webservice1"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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.webservice1.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 4: 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 5: Now crate a new class in your existing package and name that class as Bean. Now paste the below code in your bean class file.

Bean.java :


package com.exam.webservice1;

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


public class Bean implements KvmSerializable
{
public String Name;
public String Place;
public String Age;
public String Phone;

public Bean(){}

public Bean( String Name,String Place,String Age,String Phone)
{
this.Name=Name;
this.Place=Place;
this.Age=Age;
this.Phone=Phone;
}

public Object getProperty(int arg0) {
switch(arg0)
{
case 0:
return Name;
case 1:
return Place;
case 2:
return Age;
case 3:
return Phone;
}
return null;
}

public int getPropertyCount() {
return 4;
}

@SuppressWarnings("rawtypes")
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Name";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Place";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Age";
break;
case 3:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Phone";
break;
default:
break;
}
}

public void setProperty(int index, Object value) {
switch(index)
{
case 0:
Name = value.toString();
break;
case 1:
Place = value.toString();
break;
case 2:
Age = value.toString();
break;
case 3:
Phone = value.toString();
break;
default:
break;
}
}
}

Step 6: Now call the web service and get details with asynctask. Paste this below code in your MainActivity class file.

MainActivity.java :


package com.exam.webservice1;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

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 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.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

boolean timeoutexcep=false,httpexcep=false,generalexcep=false;
String UserName="yuki",Id="y475";

String name,place,age,phone;

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

new Persondetails().execute();
}

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

class Persondetails 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/Java/Service1.asmx";
final String SOAP_ACTION = "http://tempuri.org/CheckDetails";
final String METHOD_NAME = "CheckDetails";

SoapObject request2 = new SoapObject(NAMESPACE, METHOD_NAME);

request2.addProperty("sUserName", UserName);
request2.addProperty("sId", Id);


Bean C = new Bean();
PropertyInfo pi = new PropertyInfo();
pi.setName("Bean");
pi.setValue(C);
pi.setType(C.getClass());
request2.addProperty(pi);
SoapSerializationEnvelope envelope2 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope2.dotNet = true;
envelope2.setOutputSoapObject(request2);
envelope2.addMapping(NAMESPACE, "Bean", new Bean().getClass());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope2);
SoapObject response2 = (SoapObject) envelope2.getResponse();


System.out.println("check Request" + request2);
System.out.println("check response" + response2);

envelope2.addMapping(NAMESPACE, "Panchayat",new Bean().getClass());
androidHttpTransport.call(SOAP_ACTION, envelope2);
Bean[] personobj = new Bean[response2.getPropertyCount()];
Bean beanobj = new Bean();

for (int j = 0; j < personobj.length; j++) {
SoapObject pii = (SoapObject) response2.getProperty(j);
beanobj.Name = pii.getProperty(1).toString();
beanobj.Place = pii.getProperty(2).toString();
beanobj.Age = pii.getProperty(3).toString();
beanobj.Phone = pii.getProperty(4).toString();

personobj[j] = beanobj;
}

name=beanobj.Name;
age=beanobj.Place;
place=beanobj.Age;
phone=beanobj.Phone;

}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(ConnectException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
generalexcep=true;
e.printStackTrace();
}
return null;

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

if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(generalexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}

else {
display();
}
timeoutexcep=false;httpexcep=false;generalexcep=false;
}

private void display() {

TextView t1=(TextView)findViewById(R.id.name);
t1.setText(name);
TextView t2=(TextView)findViewById(R.id.palce);
t2.setText(place);
TextView t3=(TextView)findViewById(R.id.age);
t3.setText(age);
TextView t4=(TextView)findViewById(R.id.phone);
t4.setText(phone);
}
}
}



Saturday 8 February 2014

Change backgroung activity color with your voice in android

Tell your application to change your activity background color through your voice command. And you can also move to the next activity by voice command. The voice recognition in android is a cool feature that user can interact with the application.


Background


Image                            Color






On "Next" starts next activity







Step 1: Create new project in your res drawable put some image for your background and the mic image also.

Step2: In res
values rightclick on values folder new other and create a new xml and name it as color.xml

color.xml :


<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="green">#317533</color>
<color name="black">#000000</color>
</resources>


Step 3: And in your layout leave a text what to do and a mic image.

AndroidManifest.xml :

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

<Button
android:id="@+id/speakButton"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"
android:background="@drawable/mic" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Tap mic and speak your color"
android:textSize="20sp" />

Step 4: Then right click on your project package create a new android activity.

Step 5: Finally in your MainActivity copy the below code

MainActivity.java :


package com.examp.voice;

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

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class VoiceActivity extends Activity {

private static final int REQUEST_CODE = 1234;

ArrayList<String> colorlist;
Button speakButton;

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

speakButton = (Button) findViewById(R.id.speakButton);

// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
speakButton.setEnabled(false);
Toast.makeText(getApplicationContext(), "No voice recognition service", Toast.LENGTH_LONG).show();
}

speakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startVoiceRecognitionActivity();
}
});
}

private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak your colour");
startActivityForResult(intent, REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try{

if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
colorlist = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
}
super.onActivityResult(requestCode, resultCode, data);

for(int i=0;i<5;i++)
{
if(colorlist.get(i).equalsIgnoreCase("red"))
{
getWindow().setBackgroundDrawableResource(R.drawable.red);
}
else if(colorlist.get(i).startsWith("green"))
{
getWindow().setBackgroundDrawableResource(R.color.green);
}
else if(colorlist.get(i).contains("blue"))
{
getWindow().setBackgroundDrawableResource(R.drawable.blue);
}
else if(colorlist.get(i).equalsIgnoreCase("black"))
{
getWindow().setBackgroundDrawableResource(R.color.black);
}
else if(colorlist.get(i).equalsIgnoreCase("yellow"))
{
getWindow().setBackgroundDrawableResource(R.drawable.yellow);
}
else if(colorlist.get(i).equalsIgnoreCase("next")||colorlist.get(i).equalsIgnoreCase("start"))
{
Intent in=new Intent(VoiceActivity.this,SecActivity.class);
startActivity(in);

}
else if(colorlist.get(i).contains("stop")||colorlist.get(i).contains("finish"))
{
finish();
}
else
{
}}
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "Color not recognized", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

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

Thursday 6 February 2014

Populate spinners using object returned by soap web service in android. Using string array as response from .net web service.

Populate the spinner with response from the web service . Where the response is in string array format.







Step 1: Create new project and in your layout file place a spinner.

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="30dp" />

</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.district"
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.district.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: Then in your main class copy this code.

MainActivity.java
:

package com.exam.district;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
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;
import android.widget.Toast;

public class MainActivity extends Activity {

String list[];
boolean exc=false;

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

new addassdist().execute();
}

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

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

private final String SOAP_ACTION = "http://tempuri.org/GetDistrict";
private final String METHOD_NAME = "GetDistrict";
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.160.1.1/district/service.asmx";

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

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

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();

System.out.println("response"+response);
int intPropertyCount = response.getPropertyCount();
list= new String[intPropertyCount];

for (int i = 0; i < intPropertyCount; i++)
{
list[i] = response.getPropertyAsString(i).toString();
}
}

catch (Exception e) {
exc=true;
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {

if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(exc)
{
Toast.makeText(MainActivity.this,"Error" , Toast.LENGTH_LONG).show();
}
else{
spinner();
exc=false;
}
}
}

public void spinner(){

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

ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list);
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) {
// your code
}
});
}

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