Thursday, April 18, 2013

Passing an object as parameter to a method

Passing an object as parameter is always a confusing concept. here is a java code given below which might help you understand this concept .

/*========================================*/

public class HelloWorld{
     public static void main(String []args){
       myroom obj = new myroom();
       dadsroom obj1 = new dadsroom();
       obj1.love(obj);
     }
}
 class myroom{
public int x;
    public int y =3;
}
class dadsroom{
 void love(myroom o){
       System.out.println(o.x +"and"+ o.y);
   }
}
/*========================================*/

SHOULD I CALL IT EXPLANATION ? :
 I've created three class in above code, one is HelloWorld which combines the main method, next is myroom, and last one is dadsroom. In main method, I've created an object of myroom "obj" and another object of dadsroom "obj1". dadsroom is having a method love which is receiving object of myroom and then printing instance variable using object of myroom. In main, I've called love method using object of class dadsroom and passing object of myroom  as parameter..

Let's have a formal EXPLANATION:
what i am trying to do is, i am having a template of myroom and also a template of dadsroom through their objects, now I am adding a room which is same as myroom(every thing is same as myroom cause it is instance of myroom) into dadsroom, now a room which is same as myroom is attached with dadsroom, I can access every feature (which was having myroom) through dadsroom. An object of myroom is attached with dadsroom by passing object of myroom.

Sunday, April 14, 2013

More about Activity Life Cycle with an example.

Hey there, Here is an example of Activity life cycle, This will illustrate more about how onCreate(), onStart(), onResume, onPause(), onStop() call in activity Life Cycle, I have Created two activity and given toast in each method, when you navigate the application Toast will pop on the screen as per Activity Life cycle.

<!-- ================First layout (main.xml)=====================-->

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

<!-- ===================End of main.xml====================== -->


/*=========ActivityLifeCycleActivity (Corrosponding code to main.xml) ========*/
package com.hellboys.act;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ActivityLifeCycleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "1 onCreate()",Toast.LENGTH_LONG).show();
       
        Button b1;
        b1 = (Button) findViewById(R.id.but);
        b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(ActivityLifeCycleActivity.this,abhi.class);
startActivity(intent);
}
});
    }
   
    public void onStart(){
    super.onStart();
    Toast.makeText(getBaseContext(), "1 onStart()",Toast.LENGTH_LONG).show();
    }
   
    public void onResume(){
    super.onResume();
    Toast.makeText(getBaseContext(), "1 onResume()",Toast.LENGTH_LONG).show();
    }
   
    public void onPause(){
    super.onPause();
    Toast.makeText(getBaseContext(), "1 onPause()",Toast.LENGTH_LONG).show();
    }
   
    public void onStop(){
    super.onStop();
    Toast.makeText(getBaseContext(), "1 onStop()",Toast.LENGTH_LONG).show();
    }
}
/*=============End of ActivityLifeCycleActivity=================*/

<!-- ================Second layout (abhi.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:orientation="vertical" >

    <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
<!-- =====================End of abhi.xml======================= -->


/*=========Second Activity(Java code corresponding to abhi.xml) ========= */
package com.hellboys.act;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class abhi extends Activity{
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.abhi);
Toast.makeText(getBaseContext(), "2 onCreate()", Toast.LENGTH_LONG).show();
}

public void onStart(){
super.onStart();
Toast.makeText(getBaseContext(), "2 start()", Toast.LENGTH_LONG).show();
}
public void onResume(){
super.onResume();
Toast.makeText(getBaseContext(), "2 onResume()", Toast.LENGTH_LONG).show();
}
public void onPause(){
super.onPause();
Toast.makeText(getBaseContext(), "2 onPause()", Toast.LENGTH_LONG).show();
}
public void onStop(){
super.onStop();
Toast.makeText(getBaseContext(), "2 onstop()", Toast.LENGTH_LONG).show();
}
}
/*=================End of abhi============================*/


/*==========================Do +1 if like ....... ========================*/





Wednesday, March 27, 2013

Sending E-mail through your Application using Mail Clients


It may possible that we need to send E-mail through our Application, The Code is given below for sending E-mail. It uses the mail client installed in Android phone, Oftenly it doesn't work on the emulator because emulator doesn't have a pre-installed mail-client, we need to install E-mail Client first on emulators then this will work on emulator, you can directly run this your phone.

On Emulator Since no client installed, it'll work fine on phone.


<!-- --------------------------------------- XML file------------------------------------------------- -->
<?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:orientation="vertical" >

<TextView
        android:id="@+id/fp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="forget Password?"
        android:layout_gravity="center" />

</LinearLayout>
<!-- ------------------------- End of XML file------------------------------------------------- -->



/*======================== Java File ==================================*/
public class forget extends Activity {
public void onCreate(Bundle savedInstanceActivity ){
super.onCreate(savedInstanceActivity);
setContentView(R.layout.authenticate);

TextView fp = (TextView)findViewById(R.id.fp);
fp.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try{
Uri uri = Uri.parse("mailto:ashutiwari4@gmail.com");
Intent emailIntent = new Intent(Intent.ACTION_SENDTO,uri);
emailIntent.setType("message/rfc822");
final String aEmailList[]  = {"ashutiwari4@gmail.com"};
emailIntent.putExtra(Intent.EXTRA_EMAIL, aEmailList);
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"Sample Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "this is extra");
startActivity(Intent.createChooser(emailIntent, "Select Email Application"));
}
catch(Exception ex){
Toast.makeText(forget.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
Log.e("SendEmail","Can't send email",ex);
}
}
});
}
}

/*===================== End of Java File ============================*/

Context Menu in Android


Hey friends, In this post I'm gonna explain you how to create List view ?, how to perform specific task on each item selection?, How to create Context Menu and how to perform specific task on  selection of context Item.... So lots of things are there in this post.... So, use it n Enjoy!!

List View  On Single Touch

Context Menu On Long press
/*The Code Goes Here!!*/
<!-- --------------------------------------------------------- XML File ---------------------------------- -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/lay" >

    <ListView
        android:id="@+id/listView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>
<!-- --------------------------------------- End of XML File ------------------------------------------- -->


/*============================== Java File===========================*/
public class Context1Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final ListView lv = (ListView) findViewById(R.id.listView2);
        String[] list = new String[] {"Home","Office","Office2"};
       
        BaseAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
        lv.setAdapter(adapter);
        /*Registering for context Menu */
        registerForContextMenu(lv);
        /*Setting onItemClick listener so that on clicking, it will work accordingly "single click" */
     
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener()
        {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
if(lv.getItemAtPosition(arg2)=="Home")
home();
if(lv.getItemAtPosition(arg2)=="Office")
office();
if(lv.getItemAtPosition(arg2)=="Office2"){
office2();
}
}
      });
     
        /* set onClickListner listener on the whole layout(Liner layout) so that whenever user will click on
          screen it will provide option for adding location*/
       
        LinearLayout ll = (LinearLayout)findViewById(R.id.lay);
        //registerForContextMenu(ll); //this can be use for open a context menu by clicking on screen
        ll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Context1Activity.this, "linerlayout click", Toast.LENGTH_LONG).show();
}
});
    }
   /*-------------------------Function body for each item in list -------------------------------------*/
    public void home(){
    Toast.makeText(Context1Activity.this,"home single click", Toast.LENGTH_LONG).show();
    }
    public void office(){
    Toast.makeText(Context1Activity.this,"office single click", Toast.LENGTH_LONG).show();
    }
    public void office2(){
    Toast.makeText(Context1Activity.this,"office2 single click", Toast.LENGTH_LONG).show();
    }
   
    /*--------------------------------------------------------------------------------------------------*/
    /* For implementing context menu, two methods should be implement,
     * one is onCreateContextMenu for creating context menu which will add menu
     * other one is OnContextItemSelected for performing action on selecting the items
     */
 
    @Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
     inflater.inflate(R.menu.activity_main, menu); //select layout which should pop up in context menu
 menu.add("Add Location!");
 menu.add("Delete");
 menu.add("Rename");
}
   
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onContextItemSelected(item);
if(item.getTitle()=="Add Location!"){
Addloc();
}
if(item.getTitle()=="Delete"){
Delete();
}
if(item.getTitle()=="Rename"){
Rename();
}
return true;
}
/*----------------------------function body for context menu----------------------------------*/
public void Addloc(){
Toast.makeText(this,"Add location", Toast.LENGTH_LONG).show();
}
public void Delete(){
Toast.makeText(this,"Delete Message", Toast.LENGTH_LONG).show();
}
public void Rename(){
Toast.makeText(this,"Rename message", Toast.LENGTH_LONG).show();
}
/*------------------------------------------------------------------------------------------------*/
}
/*=========================End of Java File===========================*/

Dialog Box with Positive and Negative Button In Android


Android Supports many kind of Dialog Boxes, In this post I tried to explain Dialog Box with a XML EditText, a Negative and a Positive Buttons as shown in Fig., In further post I'll try to explain some other kind of Dialog box. Here is code for Dialog Box --->

/* ========================Code goes Here!! ===============================*/
public class DialogActivity extends Activity {
private static final int DLG_EXAMPLE1=0;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate (savedInstanceState);
setContentView(R.layout.main);

Button b = (Button)findViewById(R.id.ADD_Location );
b.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
showDialog(DLG_EXAMPLE1);
}});
}
// Method for Creating Dialog box
@Override
protected Dialog onCreateDialog(int id ){
switch(id){
case DLG_EXAMPLE1:
return createExampleDialog(); // Function call, body is defined below
default :
return null;
}
}

// This method is used for setting the dialogbox
@Override
protected void onPrepareDialog(int id,Dialog loginPrompt){
switch(id){
case DLG_EXAMPLE1:
final EditText first = (EditText)loginPrompt.findViewById(R.id.rf1);
first.setText(""); // setting the editbox blank
final EditText second = (EditText)loginPrompt.findViewById(R.id.rf2);
second.setText("");
break;
}
}

//Body the function createExampleDialog()
private Dialog createExampleDialog(){
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.userpasslayout, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Register Yourself!!");
alert.setIcon(R.drawable.logo);
alert.setMessage("Fill information carefully!");
alert.setView(textEntryView);
AlertDialog loginPrompt = alert.create();

//PositiveButton Onclick Listener
alert.setPositiveButton("Register", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(DialogActivity.this, "So you think!", Toast.LENGTH_LONG).show();
return;
}
});

//NegativeButton onclick Listener
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// NegtiveButton works automatic it will perform cancel of the dialog box;
return;
}
});
return alert.create();
}
/*=====================================================================*/

How to create Option Menu In Android !


In android, we oftentimes need to create Option Menu, Here are two methods we need to override as shown in example given below-

public class DialogActivity extends Activity {

private static final int ADD_LOC = Menu.FIRST;
private static final int CHANGE_PASS = Menu.FIRST+1;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate (savedInstanceState);
setContentView(R.layout.main);
}
/*====================== Option menu creation==========================*/
/*------------------------------------menu creation--------------------------------------------*/
@Override
public boolean onCreateOptionsMenu(Menu menu){
menu.add(0,ADD_LOC,0,"Add Location").setIcon(R.drawable.add);
/* 1st argument->group id, ADD_LOC -> item_id, 3rd argument -> appearance of item in menu,
last argument -> Name which will apper on the menu */
menu.add(0,CHANGE_PASS,0,"Rename").setIcon(R.drawable.change);
//AlphabeticShortcut(alphaChar) can be used here for selection item through pressing a key Input
return true;
}
/*-----------------------------------Item Selection-----------------------------------------------*/
@Override
public boolean onOptionsItemSelected(MenuItem item){

switch(item.getItemId()){
case ADD_LOC:
Toast.makeText(DialogActivity.this, "So, YOu can EDIT ?", Toast.LENGTH_LONG).show();
// Your code goes here for case One..., Here I have given a Toast on option item selection
return true;
case CHANGE_PASS:
Toast.makeText(DialogActivity.this, "So, YOu can RENAME ?", Toast.LENGTH_LONG).show();
// Your code goes here for case Two...
return true;
}
return false;
}
/*------------------------------------------------------------------------------------------------------*/
/*====================================================================*/
}

Saturday, March 16, 2013

Start with Android ...


Hey There, I was wondering, If I could help you on android application development... So I am starting a section, This section aims to help you on some Important concepts about Android and more about application development problem, such as basic XML creation, placing listeners in corresponding java files, Context menu creation, Option menu creation, Progress bar creation, Various Dialog Box, DATABASE(SQLite), Mail APIs, Sending Mail without using E-mail Client, Services, Broadcast Receiver, Sending SMS, Sending Text via Bluetooth, Animations, ListView, Splash Screen and much more ...... So just Stay tuned ... .. HaPPy AnDrOId Learning ...... :)