1

Radio Button Example Android

Posted by Arjun Singh on 23:16
Radio buttons are used when you have multiple choices but you have to select only one.

In  Android,  Radio buttons are grouped together by  android.widget.RadioGroup class.If radio buttons are inside Radio group so when one radio button is selected then all others becomes unselected.

Now,I am going to make radio group "Gender " with two radio buttons "Male" &  "Female".

activity_main.xml



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

    <TextView
        android:id="@+id/txtGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="GENDER"
        android:textColor="#0198E1"
        android:textSize="16sp"
        android:textStyle="bold" >
    </TextView>

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="2dp"
        android:background="#0198E1" />

    <LinearLayout
        android:id="@+id/linearlayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <RadioGroup
            android:id="@+id/rgGender"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/rdbMale"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:checked="true"
                android:text="Male"
                android:textColor="#0198E1"
                android:textSize="16sp"
                android:textStyle="bold" />

            <RadioButton
                android:id="@+id/rdbFemale"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="Female"
                android:textColor="#0198E1"
                android:textSize="16sp"
                android:textStyle="bold" />
        </RadioGroup>
    </LinearLayout>

    <TextView
        android:id="@+id/txtSelGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Selected Gender"
        android:textColor="#0198E1"
        android:textSize="16sp"
        android:textStyle="bold" >
    </TextView>

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="2dp"
        android:background="#0198E1" />

    <TextView
        android:id="@+id/txtSelGenderValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textColor="#0198E1"
        android:textSize="16sp"
        android:textStyle="bold" >
    </TextView>

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="submit" />

</LinearLayout>


layout preview





















MainActivity,java




package com.arjun.radiobuttondemo;



import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity implements OnCheckedChangeListener {

Button btnSubmit;
RadioButton rdbMale, rdbFemale;
RadioGroup rgGender;
TextView txtSelecteGender;
String gender ="Male";
Context ctx;

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

ctx = this;

init();

rgGender.setOnCheckedChangeListener(this);

btnSubmit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
txtSelecteGender.setText(gender);
}
});



}

public void init() {
btnSubmit =(Button)findViewById(R.id.btnSubmit);
rgGender = (RadioGroup) findViewById(R.id.rgGender);
rdbMale = (RadioButton) findViewById(R.id.rdbMale);
rdbFemale = (RadioButton) findViewById(R.id.rdbMale);
txtSelecteGender =(TextView) findViewById(R.id.txtSelGenderValue);
}

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

@Override
public void onCheckedChanged(RadioGroup group, int position) {
// TODO Auto-generated method stub
switch (position) {
case R.id.rdbMale:
gender = "Male";
System.out.println("Male");
break;
case R.id.rdbFemale:
gender = "Female";
System.out.println("FeMale");
break;

default:
break;
}
}

}


after clicking submit button it will show selected gender





0

SetError method in EditText box

Posted by Arjun Singh on 10:52
Today we are going to implement set error method for edittext.It is useful for diaplaying message if  user enters something wrong or leave it blank.

MainActivity,java

package com.arjun.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

EditText edtname;
Button btncheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtname =(EditText)findViewById(R.id.edtName);
btncheck = (Button)findViewById(R.id.btnCheck);
btncheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(edtname.getText().length() ==0)
{
edtname.setError("Please fill name...");
}
}
});
}


}



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

    <EditText
        android:id="@+id/edtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="47dp"
        android:layout_marginTop="28dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edtname"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="76dp"
        android:text="Button" />

</RelativeLayout>


Output






0

Installing app on memory card by default

Posted by Arjun Singh on 10:14
Add following line in manifest file of your android app.Your app will install in memory card by default

Add only this line:
android:installLocation="preferExternal"
and permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


eg-
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.arjun.Medic" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".MedicActivity" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name =".add"></activity> <activity android:name =".history"></activity> </application> </manifest>


0

Parsing JSON String in Android

Posted by Arjun Singh on 08:22



Suppose i store my JSON response in string response.
String response = {
    "name": "John Smith",
    "age": 32,
    "employed": true,
    "address": {
        "street": "701 First Ave.",
        "city": "Sunnyvale, CA 95125",
        "country": "United States"
    },
    "children": [
        {
            "name": "Richard",
            "age": 7
        },
        {
            "name": "Susan",
            "age": 4
        },
        {
            "name": "James",
            "age": 3
        }
    ]
}


{ = This sign respresent that it is JSONObject node.
 [= This sign represnt that it is JSON Array node.

 so we will parse the response in this way,

 JSONObject objres = new JSONObject(response);

   String Name =objres.getString("name").// it will fetch name and store its value in variable Name.

   String Age =objres.getString("age").// it will fetch age and store its value in variable Age.

   String Employed =objres.getString("employed").// it will fetch employed and store its value in variable Employed.

  Note:  "address": { is an JSONObject node inside object objres.

   JSONObject objAddress = objres.getJSONObject(address);

       String Street =objAddress.getString("street").// it will fetch street and store its value in variable Street

   
       String City =objAddress.getString("city").// it will fetch city and store its value in variable City

   Note:  "children": [ is an JSONArray inside object objres.

       JSONArray childrenArray = objres.getJSONArray("children");

       //Following code will give value of  element at zeroth  to last position in array..suppose i am having more than 1 element in array so i will use for loop to get value of each element.

       for (int J = 0; J < childrenArray.length(); J++) {

       JSONObject menuObject = childrenArray.getJSONObject(J);

       String chName= menuObject.getString("name");
       String chAge= menuObject.getString("age");
       }


0

SD Card in Android Enulator

Posted by Arjun Singh on 07:40
Creating Sd card in emulator is east task.Just Follow these steps:

step 1:Open your Android Virtual device manager(AVD)

step 2:select your emulator

step 3:Edit your emulator

step 4:must specified size of your SD card 1024MB.

step 5:in hardware option click new set property add SD card support: yes(value)

step 6:start your emulator, in eclipse window–>showview–>other->android–>file explorer

step 7->In file explorer open mnt->sdcard and using pushfile button for insert your file and image
step 8:DONE

0

AsyncTask in Android

Posted by Arjun Singh on 03:32
In Android, Services are used to keep running the application in background..If You want to small task in background then what you will do ??. In that case you have to use AsyncTask.
                     If your appication requires connection with server,loading and uploading data to server etc. In such cases,your appication becomes more complex.You can solve this by using AsyncTask.You can show a user some kind of notification or progressdialog box to display something on main screen while loading data from server in background without interuppting the main thread.

        
                       AsyncTask is an abstract class that provides several methods managing the interaction between the UI thread and the background thread. it’s implementation is by creating a sub class that extends AsyncTask and implementing the different protected methods it provides.

We are now going to create AsyncTasj sub class by like this:

class ServerTask extends AsyncTask<Params,Progress,Result>
{
}

It contains three parameter:
  1. Params: parameter info passed to be used by the AsyncTask.
  2. Progress: the type of progress that the task accomplishes.
  3. The result returned after the AsyncTask finishes.
Next step is we have to override the protected methods of AsyncTask class that defined its LifeCycle.

Methods:
  1. onPreExecute: the first method called in the AsyncTask, called on the UI thread.
  2. doInBackground: the method that executes the time consuming tasks and publish the task progress, executed in background thread.
  3. onProgressUpdate: method that updates the progress of the AsyncTask, run on the UI thread.
  4. onPostExecute: the final method that gets called after doInBackground finishes, here we can update the UI with the results of the AsyncTask.
  5. onCancelled: gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask.

    Example:
     public class Details extends Activity {
      
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.details);
            ctx =this;
          
            
             readWebpage();
        }
      
      
      
        private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
     
                for (String url : urls) {
              
            //    do background task

                }
                return String();
              
            }
          
            @Override
            protected void onPreExecute() {
              
                 ploading = ProgressDialog.show(ctx,"" ,"");
                 ploading.setContentView(R.layout.wheel);
                 ploading.setCancelable(true);
            }

            @Override
            protected void onPostExecute(String result) {
          
              
              
                ploading.dismiss();
                //set the loaded data in your ui
              
                }

            }
          
        }
        public void readWebpage() {
            DownloadWebPageTask task = new DownloadWebPageTask();
            task.execute(new String[] { "http://"www.arjun30.blogspot.in"});

        }
      

    }




     


    0

    Difference between Handler and AsyncTask

    Posted by Arjun Singh on 03:00
    The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.

    AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
    exapmle:if you want to download something and while downloading you can show ProgressDialog to user without interupting the execution of main ui thread.

    Both can be used to update the ui from background thread.
    You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.


    You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.



    Copyright © 2009 arjuns blog All rights reserved. Theme by Laptop Geek. | Bloggerized by FalconHive.