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