Fundamentals
Introduction
1st Android Application

OOPS Concepts
Class
Object
Abstraction
Encapsulation

Polymorphism
Inheritance
Message Passing
Dynamic Binding

UI Controls
TextView
Button
Toggle Button
CheckBox
Radio Button
Spinner
ProgressBar
SeekBar
RadioGroup
RatingBar
Switch
EditText
AutoComplete
TextView

MultiAutoComplete
TextView

ImageView
ImageButton
Gallery
MediaPlayer
VideoView
MediaController

TimePicker
DatePicker
CalendarView
Chronometer
Analog Clock
Digital Clock

Layouts
LinearLayout
RelativeLayout
GridLayout
TableLayout
FrameLayout
Fragment

Composite
ListView
ExpandableListView
GridView
ScrollView
SearchView
Sliding Drawer
Tab Widget
WebView

Transitions
Image Switcher
StackView
TextSwitcher
ViewAnimator
View Flipper
View Switcher

Advanced
Request Focus
View
View Stub
TextureView
Gesture Overlay View

SurfaceView
NumberPicker
Zoom Button
Zoom Controls
AbsoluteLayout

Database
SharedPreference
SQLite DB
MySQL DB

Webservices
Check HttpURLConnection
Single Webservice Call
Multi Webservice Call
ListView from Webservice
SQLite from Webservice
Data from Database

Telephone Manager
IMEI
IMSI
Phone Type
Sim Type
Network Type

Content Providers
Contact Provider
BookMark Provider
Own Provider


Message & Networking
Send SMS
SMS with Reports
Group SMS

Send E-Mail
Download Binary Data


Location Based Service
Display Google Map
Events with Google Map

Android Services
Create Service
Create Longtime Service

Asynchronous Task
Repeating Services
IntentService

Activity from a Service
Bind Activity to Service


Sample Projects
HMS
CNB
Login Screen
Camera Event
Browse Option
QR Code Events
Accelerometer Sensor
EditText from Spinner

Android EditText from Spinner

  1. EditText depend upon Spinner in Android
  2. EditText depend upon Spinner from MySQL DB

Note                     Download ADT Plugin Here.
Here I am using,
OS : Linux (Ubuntu 12.04)
Eclipse : Juno (Version 4.2.0)
Android API Level : 3 to 'n' as per need
Emulator API Level : It will be displayed in output image

A. EditText depend upon Spinner in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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="60dp" />
 
    <EditText
        android:id="@+id/editText1"
        android:hint="EditText"
        android:editable="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.editspinner_ex1;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
 
public class MainActivity extends Activity {
 
	Spinner spinner;
	EditText text;
	
	List<String> list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		spinner = (Spinner) findViewById(R.id.spinner1);
		text = (EditText) findViewById(R.id.editText1);
		
		list = new ArrayList<String>();
		list.add("Item 0");
		list.add("Item 1");
		list.add("Item 2");
		list.add("Item 3");
 
		ArrayAdapter<String> adp = new ArrayAdapter<String>
			(this, android.R.layout.simple_dropdown_item_1line, list);
		adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		
		spinner.setAdapter(adp);
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
 
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				switch(arg2) {
				
					case 0 :
						text.setText("Value 0");
						break;
					case 1 :
						text.setText("Value 1");
						break;
					case 2 :
						text.setText("Value 2");
						break;
					case 3 :
						text.setText("Value 3");
						break;
					default :
						text.setText("Nothing");
						break;
				}				
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.editspinner_ex1"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.editspinner_ex1.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 5 : Open res ->values ->strings.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">EditSpinner_Ex1</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output


Output









B. EditText depend upon Spinner from MySQL DB


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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="60dp" />
 
    <EditText
        android:id="@+id/editText1"
        android:hint="EditText"
        android:editable="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.editspinner_ex2;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
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.EditText;
import android.widget.Spinner;
 
public class MainActivity extends Activity {
 
	Spinner spinner;
	EditText text;
	
	InputStream is=null;
	String result=null;
	String line=null;
	
	List<String> list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		spinner = (Spinner) findViewById(R.id.spinner1);
		text = (EditText) findViewById(R.id.editText1);
		
		SpinnerValues();
		
		ArrayAdapter<String> adp = new ArrayAdapter<String>
			(this, android.R.layout.simple_dropdown_item_1line, list);
		adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		
		spinner.setAdapter(adp);
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
 
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				
				String item = getEditTextValue(arg2);
				
				text.setText(item);
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void SpinnerValues() {
		// TODO Auto-generated method stub
	    	
		try {
		
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
			HttpResponse response = httpclient.execute(httppost); 
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch(Exception e) {
		
	        	Log.e("Fail 1", e.toString());
		}     
	        
		try {
		
			BufferedReader reader = new BufferedReader
					(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			while ((line = reader.readLine()) != null) {
			
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		}
		catch(Exception e) {
		
			Log.e("Fail 2", e.toString());
		}     
	       
		try {
			
			JSONArray jarray = new JSONArray(result);
			JSONObject jobject = null;
			
			list = new ArrayList<String>();
			
			for(int i=0; i<jarray.length(); i++) {
				
				jobject = jarray.getJSONObject(i);
				list.add(jobject.getString("id"));
			}
			
		}
		catch(Exception e) {
		
			Log.e("Fail 3", e.toString());
		}
	}
	
	private String getEditTextValue(int arg) {
		// TODO Auto-generated method stub
		
		String item = null;
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		 
		nameValuePairs.add(new BasicNameValuePair("id",list.get(arg).toString()));
		
		try {
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://10.0.2.2/getText.php");
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost); 
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch(Exception e) {
		
	        	Log.e("Fail 1", e.toString());
		}     
	        
		try {
		
			BufferedReader reader = new BufferedReader
					(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			while ((line = reader.readLine()) != null) {
			
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		}
		catch(Exception e) {
		
			Log.e("Fail 2", e.toString());
		}     
	       
		try {
			
			JSONObject jobject = new JSONObject(result);
						
			item = jobject.getString("uname");
		}
		catch(Exception e) {
		
			Log.e("Fail 3", e.toString());
		}
		
		return item;
	}
 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.editspinner_ex2"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    
    <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="balaji.editspinner.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 5 : Open res ->values ->strings.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">EditSpinner</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
 
</resources>

Step 6 : Create select.php and add following code :

<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="Sample";
 
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
 
$r=mysql_query("select * from student",$con);
 
while($row=mysql_fetch_array($r)) {
 
	$flag[]=$row;
}
 
print(json_encode($flag));
mysql_close($con);
?>

Step 7 : Create getText.php and add following code :

<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="Sample";
 
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
 
$id = $_REQUEST['id'];

$r=mysql_query("select * from student where id = '$id'",$con);
 
while($row=mysql_fetch_array($r)) {
 
	$flag=$row;
}
 
print(json_encode($flag));
mysql_close($con);
?>

Step 8 : Our output will be like this :


Output


Output


Output









SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com