Tuesday, 29 December 2015

Logical questions and answers in java

1> Print max. number among multiple numbers?

public class MyMaxNum
{
    public static void main(String[] args) 
       {
           
int[] m={12,23,85,1004,65,19,46,700,12,300};
int largst=0;
for (int i = 0; i < m.length; i++)
           {
largst=m[i]; 
}
for (int i = 0; i < m.length; i++)
          {
if(m[i]>largst)
{
largst=m[i];
}
}
System.out.println("Maximum Number:"+largst);


       }
}

OutPut:  Maximum Number: 1004




2> Print min. number among multiple numbers?

public class MyMinNum
{
    public static void main(String[] args) 
       {
           
int[] m={12,23,85,1004,65,19,46,700,12,300};
int min=0;
for (int i = 0; i < m.length; i++)
        {
min=m[i]; 
}
for (int i = 0; i < m.length; i++)
       {
if(m[i]>min)
{
min=m[i];
}
}
System.out.println("Minimum number:"+min);
    }
}

OutPut:  Minimum number: 12




3> Print multiple of 3?

public class MyMultiple
{
    public static void main(String[] args) 
       {
             for (int i = 1; i < 20; i++)
{
if(i%3==0)
{
System.out.print(i+",");
}
}
        }
}

OutPut:   3,6,9,12,15,18,


4> Print Fabbonocci series?

public void MyFabonocci
{
          public static void main(String[] args)
         {
                 // fabonocci series  0,1,1,2,3,5,8,13,21
                 int a=0; int b=1; int c=0;

                 System.Out.Print(a+","+b);
                 for(int i=0;i<7;i++)
                {
                        c=a+b;
                       System.Out.Print(","+c);   
                       a=b;
                       b=c;
                }

         }

}

OutPut: 0,1,1,2,3,5,8,13,21


5> find out  Factorial of 5?

package Test;
public class TestCalss
{
public static void main(String[] args)
     {
int res=1;
// here give i value as factorial number for which you required.
for (int i = 5; i>0; i--)
{
res=res*i;
}
System.out.println(res);
}
}

OutPut: 120

6> How to print power of a number?

      ///  Example for 10^3
      // Here base is 10 and exponential is 3
      package test;
      public class TestCalss
     {
public static void main(String[] args)
             {
int base=10;
int exp=3;
int res=1;

while(exp!=0)
{
 res=res*base;
 exp--;
}

System.out.println(res);
            }

       }

OutPut: 1000
  

7> Print sum of Natural number upto 20?

     package Test;
     public class TestCalss
    {
          public static void main(String[] args)
         {
             int res=0;
             for (int i =0; i <=20; i++)
             {
                 res=res+i;
             }
             System.out.println(res);
        }
   }

OutPut:  210


8> print ODD number upto 20

    public class TestCalss
   {
        public static void main(String[] args)
         {
              //odd number
              //1,3,5,7,9,11,13,15,17,19
             for (int i = 1; i <20; i++)
             {
if(i%2==1)
{
System.out.println(i+",");
}
              }
         }
}

OutPut:  1,3,5,7,9,11,13,15,17,19,
9> print EVEN number upto 20

    public class TestCalss
   {
        public static void main(String[] args)
         {
              //Even number

             for (int i = 1; i <20; i++)
             {
if(i%2==0)
{
System.out.println(i+",");
}
              }
         }
}

OutPut:  2,4,6,8,10,12,14,16,18,20,


10> Print prime numbers up to 100?


      for (int i = 1; i <100; i++)
{
boolean m=true;
for (int j = 2; j <i; j++)
{
if(i%j==0)
{
m=false;
}
}
if(m)
{
System.out.print(i+" ");
}

}

Output: 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 





Friday, 25 December 2015

Example for Thread in android

package com.example.trhead;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

   
        for(int i=0;i<100;i++){
        System.out.println("Main Thread :"+i);
       
       try{
        Thread.sleep(1000);
       }catch(Exception e){
        e.printStackTrace();
       }
        }
     
     
 
     
        new Thread(){
       
        public void run(){
 

                for(int i=0;i<100;i++){
                System.out.println("Seperate Thread :"+i);
               
               try{
                Thread.sleep(1000);
               }catch(Exception e){
                e.printStackTrace();
               }
                }
         
        }
        }.start();
 
         
    }

}

Tuesday, 22 December 2015

integration of Google maps with location

Step 1>  Download google play service lib project from below URL

 https://github.com/aporter/coursera-android




Step 2> Create a new Project and   add Google-Play-Service lib project  to the GoogleMaps project as library project.

Step 3> In activity_main.xml import fragment  from Layout which supports the SupportMapFragment as below

         (OR)
Write the below code in activity_main.xml


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

    <fragment
        android:id="@+id/fragment1"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
.

step 4> write the following code in MainActivity.xml

package com.example.googlemaps;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {

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

     
        SupportMapFragment f=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.fragment1);
        final GoogleMap gMap=f.getMap();
     
        final LocationManager lManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000, 1000,new LocationListener()
        {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onLocationChanged(Location location)
{
MarkerOptions opt=new  MarkerOptions();
   opt.position(new LatLng(location.getLatitude(), location.getLongitude()));
gMap.addMarker(opt);
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15));

lManager.removeUpdates(this);
}
});
     
     
     
    }


}

Step 6> Generate Your Own google maps API key.


Step 7> replace following code in Manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlemaps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

 
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="com.example.googlemaps.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>
 
     
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
        <meta-data android:name="com.google.android.geo.API_KEY"       android:value="Here You have to give your own Google API key"/>
 
    </application>
 
</manifest>







Thursday, 17 December 2015

What is Service in Android?

Service

A service is an Android application component that run in background and has no visual UI. While the user is working on the foreground UI, services can be used to handle the processes that need to be done in the background. A service can be started by another Android application components such as an activity or other services and it will continue to run in the background even after the user switches to another application. Thus services are less likely to be destroyed by Android system to free resources, than Activities.

Ex:
example of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service.

Type of Service:
2 types
  1. Started(Unbound)
  2. Bound

1) Started Service

Its a type of service which is not bounded to any components. Once started, it will run in the background even after the component that started the service gets killed. It can be run in the background indefinitely and should stop by itself after the operation its intended to carry out is completed.

A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.

service lifecycle






Ex: Playing an Music

Step 1: 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:orientation="vertical"  android:background="#FFFFFF" >

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="19dp"
        android:text="Start Service" />

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="35dp"
        android:text="Stop Service" />

    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next Page" />
    
</LinearLayout>

Step 2: activity_next.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"   android:background="#FFFFFF"  >
    
  <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_marginLeft="96dp"  
        android:layout_marginTop="112dp"     android:textColor="#000000" 
        android:text="Next Page" />  
    
    
    
</LinearLayout>




Step 3:  MainActivity.java


package com.example.servicesex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
Button buttonStart, buttonStop,buttonNext;  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = (Button) findViewById(R.id.buttonStart);  
        buttonStop = (Button) findViewById(R.id.buttonStop);  
        buttonNext = (Button) findViewById(R.id.buttonNext);  
    
        buttonStart.setOnClickListener(this);   
        buttonStop.setOnClickListener(this);  
        buttonNext.setOnClickListener(this);  
    }
public void onClick(View v)
{
switch (v.getId())
{
 case R.id.buttonStart:
   startService(new Intent(getApplicationContext(), MyService.class));
   break;
   
 case R.id.buttonStop:
   stopService(new Intent(getApplicationContext(),MyService.class));
   break;
   
 case R.id.buttonNext:
  Intent intent=new Intent(this,NextPage.class);  
      startActivity(intent);  
      break;
}
}

}





Step 4:   MyService.java


package com.example.servicesex;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service{

MediaPlayer mPlayer;
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "onBind...", 2000).show();
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub 
super.onCreate();
Toast.makeText(getApplicationContext(), "oncreate", 2000).show();
mPlayer=MediaPlayer.create(this,R.raw.tuhimerishab);
mPlayer.setLooping(false); 
mPlayer.start();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), "onStart", 2000).show();
//mPlayer.start();
}

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("ondestoryee"); 
Toast.makeText(getApplicationContext(), "onDestroy", 2000).show();
mPlayer.stop();
}
}



Step 5: NextStep.java

package com.example.servicesex;

import android.app.Activity;
import android.os.Bundle;

public class NextPage extends Activity
{
    @Override
protected void onCreate(Bundle savedInstanceState) 
    {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next); 
}
}



Step 6:  Add service tag in AndroidManifest.java

 <service android:name=".MyService" android:enabled="true"></service>
        <activity android:name=".NextPage"/>











Wednesday, 16 December 2015

Intents in Android

Android Intents

==> Dictionary meaning of Intent is Intention/ purpose that means intention to do action.

==> Intent is nothing but a message that is passed between Activities, Content Providers, broadcast             Receivers, services  etc.

 Ex:   if we want to invoke  a new Activity we need to pass new Activity ,

          if we want to start other application from your Activity , then we need to fire an Intent.  That means we are telling te Android system to make something happen.


Usage of Intents in Android

1) to start service
2) to launch Activity
3) to display list of contacts
4) to Broadcast a message
5) to dial phone call etc.

Type of Intents in Android

mainly there are 2 types.
1) Implicit intent
2) Explicit intent


Implicit intent

   Implicit intent does not specify the component, in such case Intents provides information of available components that is to be invoked which are provided by system.

 Ex:
    1)   Intent i =new Intent(Intent.Action_View);
          i.setData(Uri.parse("http://www.tutorialforandroidbypatel.blogspot.in"));
          startActivity(i);

   2)    //For making a call programatically
          Intent i=new Intent(Intent.Action_Call);
          i.setData(Uri.parse("tel:9999999999"));
          startActivity(i);


Explicit Intent

Explicit intent specifies the component, in such case intent provides the external Activity name which is to be invoked. Also we can pass information from one Activity to another Activity.


      Ex:           startActivity(new Intentt(getApplicationcontext(), NewActivity.class));



Android startActivityForResult 

Using this we can send information from one Activity to another Activity vice versa. This requires the Result from Activity2 to Activity1.

in such case Automatically onActivityResult of Activity1 will invoke and it will receive the result which Activity2 returns.




Ex:
Step 1) Activity1.java
// write the below code in  onClick event of get Button.


public void get(View v)
{
     Intent i=new Intent(getApplicationContext(), Activity2.class);
     startActivityForResult(i,2);
}
protected void onActivityResult(int requestcode, int resultcode, Intent data)
{
          super.onActivityResult(requestcode,resultcode,data);
 
          if(requestcode==2)
         {
             string msgfromActivity2 = data.getStringExtra("MESSAGE");
             tv1.setText(msgfromActivity2);
          }
}





Step 2)   Activity2.java


// write the below code in onClick event of set button

   public void set(View v)
  {
         Intent i=new Intent();
         i.putExtras("MESSAGE" , tv2.getText().toString());
         setResult(2,i);
         finish();
   }



Example for different  Intents use in Android?


Step 1> Write below code in 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:orientation="vertical" >
 
    <EditText android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/txtCall"/>
 
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/btnCall"
        android:text="Dial"/>
 
 
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Navigate to Another app"
        android:id="@+id/btnAppNavi"
        android:layout_marginTop="20dp"/>
 
 
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Navigate to Activity"
        android:id="@+id/btnActvitiyNavi"
        android:layout_marginTop="20dp"/>
 
 

</LinearLayout>




Step 2> Write the below in MainActivity.java file
package com.example.intentsexample;
import java.util.jar.Pack200.Packer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

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

        Button btnDial=(Button)findViewById(R.id.btnCall);
        Button btnActivityNavigate=(Button)findViewById(R.id.btnActvitiyNavi);
        Button btnNavigateApp=(Button)findViewById(R.id.btnAppNavi);
 
     
        btnDial.setOnClickListener(new OnClickListener()
        {
@Override
public void onClick(View arg0)
{
  EditText txt=(EditText)findViewById(R.id.txtCall);
 Intent i=new Intent();
 i.setAction(Intent.ACTION_DIAL);
 Uri.Builder builder=new Uri.Builder();
 builder.path(txt.getText().toString());
 builder.scheme("tel");
 i.setData(builder.build());
 startActivity(i);
}
});
     
        btnActivityNavigate.setOnClickListener(new OnClickListener()
        {
@Override
public void onClick(View arg0) {
Intent i=new Intent();
i.setComponent(new ComponentName(getApplicationContext(), Activity2.class));
startActivity(i);

}
});
     
        btnNavigateApp.setOnClickListener(new OnClickListener()
        {
@Override
public void onClick(View arg0)
{
PackageManager pm=getPackageManager();
Intent i=pm.getLaunchIntentForPackage("");
startActivity(i);
}
});
     
    }


}




    Step 3> Create a new activity2.xml file and write below.


  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"  android:background="#FFFFFF">
 
 
    <TextView android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="Welcome to new Activity"
        android:textSize="30dp"
        android:gravity="center"
        android:textColor="#000000"/>

</RelativeLayout>





Step 4> Create a new Actvity2.java and write the below code.

package com.example.intentsexample;

import android.app.Activity;
import android.os.Bundle;

public class Activity2 extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.activity2);

}
}



Step 5> Write the below code in Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.intentsexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity android:name=".Activity2" android:screenOrientation="portrait"></activity>
     
        <activity
            android:name="com.example.intentsexample.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>



Output:















what is mean by Activity in Android

         Activities


Defination:  Activity is an single individual user interface screen, with this we can place all UI components  ( or ) Widgets in single screen. 

An Application may contains number of Activities ,each Activity operates independently. But can be linked to one another by declaring all created individual  Activity in AndroidManifest.xml file.



Activity Life Cycle

There are mainly 7 methods. Those are

1)   onCreate()      ==> Called when Activity is first created                           
    2)   onStart()         ==> Called when Activity becomes visible to user                
3)   onResume()    ==> Called when Activity will start interacting with user  
  4)   onPause()        ==> Called when Activity is not visible to user                   
    5)   onStop()          ==> Called when Activity is no longer visible to user           
6)   onRestart()      ==> Called when Activity is stopped, prior to start            
7)   onDestroy()     ==> Called when Activity is Destroyed                             






Interview questions for Android

Q:  What are the Android Application Components?
Ans:  There are mainly 5 Types.
          1) Activities
          2) Services
          3) Content Providers
          4) Broadcast Receivers
          5) Intents.

making phone call progmatically in android

    Intent callIntent = new Intent(Intent.ACTION_CALL);
 callIntent.setData(Uri.parse("tel:1234567899"));
 startActivity(callIntent);

Tuesday, 15 December 2015

example for setting date time to calendar dynamically

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date=null;
try
{
date = sdf.parse(15/12/2015 16:34:32);
//Calendar calendar =  Calendar.getInstance(Locale.getDefault());
  _calendar.setTime(date);

}
catch(Exception e)
{

}




// Here "HH" indicating hour-of-d-day

//if we declare as  "hh" it means hour

Friday, 11 December 2015

Important point in Android




Android Features:

1: what is the difference b/w implicit intents and explicit intents?
Ans:
intent which has target component name( which we created our own Activity name) is explicit intent.
the intent which don't know target  component name is known as a implicit intents




Important code:


Q: How to get system current date?
Ans:
//Get Current Date
Calendar c=Calendar.getInstance();
SimpleDateFormat dfm=new SimpleDateFormat("MM/dd/yyyy");
currentdate=dfm.format(c.getTime());

Q: how to set minimum date to Date Picker in android?

Ans:
public void dpd2()
{
Calendar c=Calendar.getInstance();
DatePickerDialog d=new DatePickerDialog(this, new OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
txtTo.setText((monthOfYear+1)+"/"+dayOfMonth+"/"+year);
}
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));


String d1=txtFromDate.getText().toString();
StringTokenizer token1=new StringTokenizer(d1, "/");
//month
String s1=token1.nextToken();
//date
String s2=token1.nextToken();
//year
String s3=token1.nextToken();

Date date=new GregorianCalendar(Integer.parseInt((s3)),Integer.parseInt((s1))-1,Integer.parseInt((s2))).getTime();
long diff=date.getTime();
d.getDatePicker().setMinDate(diff);
d.show();
/*
d.getDatePicker().setMaxDate(System.currentTimeMillis());
d.show();*/
}


Q: Generate Random number in Android?

Ans:   public static class RandomGenerator
{
 private static Random random = new Random((new Date()).getTime());

   public static String generateRandomString(int length)
   {
     char[] values = {'A','B','C','D','E','F','G','H','I','J',
              'K','L','M','N','O','P','Q','R','S','T',
              'U','V','W','X','Y','Z','0','1','2','3',
              '4','5','6','7','8','9'};


     for (int i=0;i<5;i++)
     {
         int idx=random.nextInt(values.length);
          out += values[idx];
     }
     return out;
   }
}







Q1>  what is the difference between dp and px?
ans: px=pixels, which means absollute value,
     dp/dip= density indepandent pixels, this is alternative of px. if we use 'px' , ex: if we downloded the app for other resollution the size will not automatically streach.
             we can overcome this with the help of 'dip/dp'.



Q2>  getting last file name vlaue(2014_102822.jpg)  from following  String
     String picturePath=storage/camera/internal/2014_102822.jpg

Ans:
       String filename="";
       StringTokenizer token1=new StringTokenizer(picturePath, "/");
       while (token1.hasMoreElements())
  {
  filename=token1.nextToken();
}


Q3> for removing "java heap space error" in eclipse android?

     --->Windows > Preferences > Java > Installed JREs

     --->Check the JRE version you are using

     --->Click “Edit” to open “Edit JRE” dialogue box

     --->Now add “-Xms768m -Xmx1024m” argument to “Default VM Arguments”.



Q4> for specific keyboard in android?

--> Give this in strings.xml file as
         
            <string name="myAlphaNumeric">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</string>
and add to edittext

android:digits="@string/myAlphaNumeric"

Q5> who founded Android?
Ans:  
  Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin,Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired by Google in 2005.


Q6> Cntrl+ Space Not Working?
Ans:
For some reason Kepler changes the settings for Content Assist on Juno workspaces.
Checking the Java Proposals checkbox in Preferences -> Java\Editor\Content Assist\Advanced should resolve this problem.



Q7> What is the difference between activity and Fragment?
Ans:
A. fragment is a part of an activity, which contributes its own UI to that activity. Fragment can be thought like a sub activity.
  Where as the complete screen with which user interacts is called as activity. An activity can contain multiple
  fragments.Fragments are mostly a sub part of an activity.

B. An activity may contain 0 or multiple number of fragments based on the screen size. A fragment can be reused in multiple
  activities, so it acts like a reusable component in activities.

C. A fragment can't exist independently. It should be always part of an activity. Where as activity can exist with out any fragment in it.



Q8> Make a phone call from fragment
Ans:
String phno=phn.getText().toString();
Intent callintent=new Intent(Intent.ACTION_CALL);
callintent.setData(Uri.parse("tel:"+phno));
startActivity(callintent);


-- And add this permission in manifest.xml

<uses-permission android:name="android.permission.CALL_PHONE"/>


Q9> Set max lenght to edttext
Ans:
txtPatientName.setFilters(new InputFilter[] { new InputFilter.LengthFilter(125) });



Q10> How to difference between two dates?
Ans:

public String validationfrom()
 {
   String msg="";
   String dateStart = txtFromDate.getText().toString();
String dateStop =txtTo.getText().toString();
   SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy");
   Date d1=null;
   Date d2=null;
  long diffDays=0;
 //  String daysdiff = "";
   try
   {
    d1 = sdf.parse(dateStart);
d2 = sdf.parse(dateStop);
 long d=d2.getTime()-d1.getTime();

 diffDays = d / (24 * 60 * 60 * 1000);
//  String dif=""+diffDays;
}
   catch (Exception e)
   {
    //Toast.makeText(getApplicationContext(),"catch", 2000).show();
}
   if(diffDays>7)
   {
     msg=msg+"Select maximum Date for 7 Days Period";
   }
   if(txtFromDate.getText().toString().equalsIgnoreCase("") || txtTo.getText().toString().equalsIgnoreCase(""))
      {
      msg=msg+", Please select Dates";
      }
/* if(txtFromDate.getText().toString().equalsIgnoreCase(""))
{
msg=msg+", From Date";
}
if(txtTo.getText().toString().equalsIgnoreCase(""))
{
msg=msg+", To field";
}*/
return msg;
 }



Q11> How to underline text in android?

Ans:
btnshowmore.setPaintFlags(btnshowmore.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);


Q12> How make specific text underline with bold  and colored?

Ans: tvComments.setText(Html.fromHtml(": Risk High/<font color=\"#FF0000\"><b><u>update</u></b></font> your values"));




Q13> Date picker dialog main usable property?
Ans:
dpd.getDatePicker().findViewById(Resources.getSystem().getIdentifier("year", "id", "android")).setEnabled(false);



Q14> set dynamic height and widht to any component?
Ans:
lst_todo_System.setLayoutParams(new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 20));


Q15> http://www.mayanklangalia.blogspot.in/search/label/facebook%20integration


Q16> how to set underline to text?
Ans:
btnshowmore.setPaintFlags(btnshowmore.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);



Q17> How to Navigating from one app to another App?
Ans:
PackageManager pm = activity.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.example.healthkos");
startActivity(intent);

Q18> How to set dialog fragment background as Trasperent?
Ans:

Dailog d;

d.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));


Q19>    How to find out date is in between two dates?


try{

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date1=sdf.parse("2010-12-05");
Date date2=sdf.parse("2010-12-15");

Date date3=sdf.parse("2010-12-07");

if(date3.compareTo(date1)>=0  && date3.compareTo(date2)<=0)
{
      System.out.println("date is in between these dates...");
}
else
{
      System.out.println("out of in between these days");
}

}
catch(Exception e)
{
}







Sample example for Runnable method in android

package com.example.testandproj;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class MainActivity extends Activity
{
Handler myhHandler=new Handler();

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


        checkNetConnection();  
    }

    private void checkNetConnection()
    {
Toast.makeText(getApplicationContext(), "wel...", 2000).show();
    myhHandler.postDelayed(run1, 5000);
    }
   
   

Runnable run1=new Runnable() {

@Override
public void run() {

checkNetConnection();
}
};
   
   
   
}