Friday, November 30, 2012

Reflection image of imageview in android

Here I create reflection of image as a shadow of image in android.


Below is full example of this.
My xml file for imageview..

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

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:src="@drawable/ic_launcher" />
       

</LinearLayout>

Java file for this....

Thursday, November 29, 2012

Battery Info in android.

Here is example for how to get Battery information in android.

Example:

Code for 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/txtinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />


</LinearLayout>

Code for Java file.

public class MainActivity extends Activity {
 private TextView batteryinfo;
 private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context arg0, Intent intent) {
   // TODO Auto-generated method stub
   int level = intent.getIntExtra("level", 0);
   batteryinfo.setText(String.valueOf(level) + "%");
  }
 };

 @Override
 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.activity_main);
  batteryinfo = (TextView) this.findViewById(R.id.txtinfo);
  this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 }
}

AutoCompleteTextView in android.

As we input character the item display accordingly as a hint. This is done using autocomplitedtextview in android.


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

    <AutoCompleteTextView
        android:id="@+id/AutoCompleteTextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="This text here" />

</LinearLayout>

Code for Java file.

public class MainActivity extends Activity {

 private static final String[] samplearray = new String[] { "android", "android-phone", "android-tablet", "Nokia", "iphone", "ipad" };

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

  ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, samplearray);
  AutoCompleteTextView autotxt = (AutoCompleteTextView) findViewById(R.id.AutoCompleteTextView01);
  autotxt.setAdapter(arrAdapter);
 }

}

Output:






Draw a line in android using canvas

In this post we learn that how to draw a line in android using canvas.

For draw a line in your layout follow this code.

Create one class DrawView which extends View.

public class DrawView extends View {
    Paint paint = new Paint();

    public DrawView(Context context) {
        super(context);
        paint.setColor(Color.BLACK);
    }

    @Override
    public void onDraw(Canvas canvas) {
            canvas.drawLine(0, 50, 350, 50, paint);
    }

}

Now from your main Activity create Object of this class and in setContentView method add that view.

Code for Activity is like this.

public class MainActivity extends Activity {
    DrawView drawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        setContentView(drawView);

    }
}

See the output of this example.



Monday, November 26, 2012

Convert Drawable to Bitmap and send it to Another Activity


In this post we convert our Drawable to Bitmap and pass that bitmap to another activity using Intent

For more update about android click below link
To convert your Drawable to Bitmap use following code snippet in android.R

Bitmap bitmap = ((BitmapDrawable)d).getBitmap();

For passing that bitmap to another activity using intent use this below code snippet.

intent.putExtra("Bitmap", bitmap);

And for fetch that bitmap intent in another activity use this

Bitmap bitmap = (Bitmap)this.getIntent().getParcelableExtra("Bitmap");

Click below link for more update about android

Fetch IMEI No in Android

We can fetch IMEI No of our phone using TelephonyManager in android.
Use below code snippet for fetch IMEI No of android phone.

Friday, November 23, 2012

Use of radiogroup and checkbox in an single activity

How to make use of radiogroup.setonCheckedchangelistener and checkbox.setonCheckedchangelistener in a single activity?

http://www.varemads.com/category/android/

This question asked many times because of setonCheckedchangelistener  confusion.
how to find which component is checked either Radiogroup or Checkbox.

Here you need no implement two diffrent CheckedChangeListener for radio group and checkbox.

OnCheckedChangeListener is for radio group and android.widget.CompoundButton.OnCheckedChangeListener is for checkbox.
you need to implement two different CheckedChangeListener refer below code for both radio group and checkbox.

Java file code

public class abcd extends Activity implements OnCheckedChangeListener,android.widget.CompoundButton.OnCheckedChangeListener{

  RadioGroup rd;
  CheckBox cx;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);

  rd  =  (RadioGroup) findViewById(R.id.radioGroup1);
  cx = (CheckBox) findViewById(R.id.checkBox1);
  
  rd.setOnCheckedChangeListener(this);
  cx.setOnCheckedChangeListener(this);
  

 }
 @Override
 public void onCheckedChanged(RadioGroup group, int checkedId) {

  // Here you can get your Radio button checked id
  System.out.println("radiogroup checked");
  
 }
 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  System.out.println("checkbox checked");
  
 }
 
}

Xml file for this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton" />
    </RadioGroup>

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CheckBox" />

</LinearLayout>


http://www.varemads.com/category/android/
Hope this post helpful for you...

Thursday, November 22, 2012

Change Text color within String android.

Change Text color within String in Texview.

This below is code snippet for change color within a textview in android.

Click below link for update about android

    String first = "This color is ";
String next = "<font color='#EE0000'>red</font>";
**YOUR_TEXTVIEW**.setText(Html.fromHtml(first + next));


Custom Toast in android

In this tutorial I create custom toast message in android.


To create custom toast message first of all create layout for your toast message.
Here I create customtoast.xml in res/layout/customtoast.xml
Below is xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_toast_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF"
    android:orientation="horizontal"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="5dp" />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />

</LinearLayout>


Java code display custom toast is paste below.


public class abcd extends Activity {

 private Button toast;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);
  
  toast = (Button) findViewById(R.id.button1);
  toast.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {

    LayoutInflater inflater = getLayoutInflater();
     
    View layout = inflater.inflate(R.layout.customtoast,
      (ViewGroup) findViewById(R.id.custom_toast_layout_id));
    ImageView image = (ImageView) layout.findViewById(R.id.image);
    image.setImageResource(R.drawable.ic_launcher);
    TextView text = (TextView) layout.findViewById(R.id.text);
    text.setText("Button clicked!");
    // Toast...
    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
   }
  });
 }
}

Output:

Hope this post is helpful for you...

Click below link for more update about android

Wednesday, November 21, 2012

Full screen in android

Hiding the title bar & status bar is used in applications to show full screen to user.
Hide the Status bar through code.

Click below link for more update about android

Using JAVA code


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the Title Bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// Hide the Status Bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

Using XML



Hide the Title bar through AndroidManifest.xml


<activity  android:name=".YourClassName"
android:theme="@android:style/Theme.NoTitleBar"/>

Hide the Status bar through AndroidManifest.xml

<activity  android:name=".YourClassName"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>

Click below link for more update about android

Open Url in Android Web-browser

In this tutorial we learn how to open url from android web-browser.


The below code snipet is useful for this

 String strURL = "http://www.google.com";
  Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(strURL));
  startActivity(myIntent);

If some time tour URl not contain "http://" or "https://" that time you need to check this below condition.

if (!url.startsWith("http://") && !url.startsWith("https://")){
   url = "http://" + url;
  }

Check Internet Connection

In this tutorial we learn about how to check whether internet connection is available or not in android.


for this first of all you need to give to permission in your manifest file.

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

Now show below example for more detail.

Your main activity xml file look like this.

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content
        android:layout_height="wrap_content"
        android:text="Check Internet" />

</LinearLayout>

In your Activity JAVA file first of check internet connection using ConnectivityManager class.

ConnectivityManager connectivity = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

Your java file looks like this.


public class abcd extends Activity {

 private Button checkinternet;
 boolean isInternetPresent;

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

  checkinternet = (Button) findViewById(R.id.button1);
  checkinternet.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    isInternetPresent = checkInternet();

    if (isInternetPresent) {

     showAlertDialog("Internet Connection", "You have internet connection", true);
    }
    else {
     showAlertDialog("Internet Connection", "You have no internet connection", false);
    }
   }
  });
 }

 public boolean checkInternet() {

  ConnectivityManager connectivity = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connectivity != null) {
   NetworkInfo[] info = connectivity.getAllNetworkInfo();
   if (info != null)
    for (int i = 0; i < info.length; i++)
     if (info[i].getState() == NetworkInfo.State.CONNECTED) {
      return true;
     }

  }
  return false;
 }

 public void showAlertDialog(String title, String message, Boolean status) {
  AlertDialog alertDialog = new AlertDialog.Builder(this).create();

  alertDialog.setTitle(title);

  alertDialog.setMessage(message);

  alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int which) {
   }
  });

  alertDialog.show();
 }
}

Hope this post is helpful for you...


Shared Preference in Android

In this tutorial we learn about how to use Shared Preference in android.


Simple Demo example of shared prefrence.
In the below example main activity xml look like this.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       >
        <requestFocus />
    </EditText>
    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        
         />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />

    <Button
        android:id="@+id/showdata"
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Data" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />
     <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>


JAVA file for save data in shared preference.

private Button save,show;
 private EditText edt1,edt2;
 private TextView txt1,txt2;
 private String str1,str2;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);

  save  =  (Button) findViewById(R.id.button1);
  show  =  (Button) findViewById(R.id.showdata);
  edt1 = (EditText) findViewById(R.id.editText1);
  edt2 = (EditText) findViewById(R.id.editText2);
  txt1 = (TextView) findViewById(R.id.textView1);
  txt2 = (TextView) findViewById(R.id.textView2);
  
  save.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    
    str1 = edt1.getText().toString();
    str2 = edt2.getText().toString();
    
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
       SharedPreferences.Editor editor = sharedPreferences.edit();
       editor.putString("EDT1", str1);
       editor.putString("EDT2", str2);
       editor.commit();
   }
  });
  
  show.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {

    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
       String strSavedEDT1 = sharedPreferences.getString("EDT1", "");
       String strSavedEDT2 = sharedPreferences.getString("EDT2", "");
       txt1.setText(strSavedEDT1);
       txt2.setText(strSavedEDT2);
   }
  });
  
 } 
In above example on save button click value save to shared preference.

Tuesday, November 20, 2012

Simple Progress Dailog in android using Thread

In this tutorial we learn how to impliment progress dailog in android.

And also after complite progress bar handel the UI element using other Thread using Handler.


See below with example.

In this example my main activity XML is look like this.

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

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Loading Dailog" />

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

JAVA file for this example is like this.

 private Button start;
 private ProgressDialog dailog;
 private TextView txt;
 Handler handler;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.abcd);

  start = (Button) findViewById(R.id.start);
  txt = (TextView) findViewById(R.id.txt);
  start.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    dailog = ProgressDialog.show(abcd.this, "Progress dailog sample ", "Loading please wait....", true);
    new Thread() {
     public void run() {
      try {
       // just doing some long operation
       sleep(5000);
      
      }
      catch (Exception e) {
      }
      handler.sendEmptyMessage(0);
      dailog.dismiss();
     }
    }.start();
   }
  });
  
   handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        txt.setText("Done");

    }
   };
 }
Enjoy.........


Hide title bar in android


This simple tutorial is regarding to hide the title bar in android.

This is simple but very useful many time when we want to hide title bar in our android application.


requestWindowFeature(Window.FEATURE_NO_TITLE);

Put this line of code above setContentView otherwise it's give exception.

Try to use below code snippet for hiding title bar in your application.

@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.activity_main);
 }

Saturday, November 10, 2012

Play sound from Internet



In this tutorial we learn that how play sound file from internet in android.
Your activity_main.xml file is like below.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play Sound" />

</LinearLayout>

String url = "http://....YOUR_URL_HERE....";
In the above line code pass url of sound file where sound file is available on internet.

Your MainActivity.java file is like this.

public class MainActivity extends Activity {
  
 private Button button;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button) findViewById(R.id.button1);
  // add button listener
  button.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View arg0) {
   String url = "http://........"; // your URL here
   MediaPlayer mediaPlayer = new MediaPlayer();
   mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   try {
    mediaPlayer.setDataSource(url);
   }
   catch (Exception  e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   mediaPlayer.prepareAsync();
   
   mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
           @Override
           public void onPrepared(MediaPlayer mp) {
               
               mp.start();
           }
       });
       mediaPlayer.setOnErrorListener(new OnErrorListener() {
           @Override
           public boolean onError(MediaPlayer mp, int what, int extra) {
               // You can show error message to user
               return false;
           }
       });
   }
  });
 }
}


Click below link for more update about android

Custom Alert Dialog in Android

In this tutorial we learn that how to create custom alert dialog in android with our own layout file.
Steps to create custom alert dialog in android.
1)Create new android Project.

2)Change your activity_main.xml with below code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Dailog" />

</LinearLayout>
3)Create new layout for your dailog in res/layout folder in your project here I create customdailog.xml see below.

<?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:background="#abcd12"  
   android:orientation="vertical" >  
    <TextView  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_margin="10dp"  
     android:text="Hello this is Custom Dailog"  
     android:textColor="#000" >  
   </TextView>  
   
    <LinearLayout 
        android:layout_width="fill_parent"  
   android:layout_height="fill_parent"  
   android:weightSum="2"
   android:orientation="horizontal">  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal"  
     android:layout_weight="1"
     android:clickable="true" android:id="@+id/yes_btn"  
     android:text="YES" />  
     
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_gravity="center_horizontal" 
      android:layout_weight="1" 
     android:clickable="true" android:id="@+id/no_btn"  
     android:text="NO" />  
     
   </LinearLayout> 
  </LinearLayout> 

 4)Change your MainActivity with below code.

public class MainActivity extends Activity {
  
 final Context context = this;
 private Button button;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button) findViewById(R.id.button1);
  // add button listener
  button.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View arg0) {
   CustomDialog custom = new CustomDialog(context);  
    custom.show();  
   }
  });
 }
}

5)Create new CustomDailog.java and paste below code in that file.

public class CustomDialog extends Dialog implements android.view.View.OnClickListener {
 
 Context context;
 
 public CustomDialog(Context context) {
  super(context);
  this.context = context;
 }

 Button btn_yes, btn_no;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.customdailog);
  setTitle("This is my Custom Dialog");
  btn_yes = (Button) findViewById(R.id.yes_btn);
  btn_no = (Button) findViewById(R.id.no_btn);
  btn_yes.setOnClickListener(this);
  btn_no.setOnClickListener(this);
 }

 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  case R.id.yes_btn:
   //Do your positive button code here
   //Here I create toast message for button
   Toast.makeText(context, "Yes button click", Toast.LENGTH_SHORT).show();
   break;

  case R.id.no_btn:
   
   //Do your Negative button code here
   //Here I create toast message for button and dismiss the dailog
   Toast.makeText(context, "No button click", Toast.LENGTH_SHORT).show();
   dismiss();
   break;

  default:
   break;
  }
 }
}

Alert Dailog in Android



In this tutorial, we show you how to display an alert dailog in Android.
Layout for file for show alert dailog button.


Xml code is below

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Dailog" />

</LinearLayout>


For display alert dailog on button click JAVA code is diaplay below
In this tutorial on positive button click I start new activity.



public class MainActivity extends Activity {
  
 final Context context = this;
 private Button button;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button) findViewById(R.id.button1);
  // add button listener
  button.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View arg0) {
   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
    context);
   // set title
   alertDialogBuilder.setTitle("Your Title");
   // set dialog message
   alertDialogBuilder
    .setMessage("Alert Dailog!")
    .setCancelable(false)
    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog,int id) {
      // if this button is clicked, 
      // DO YOUR CODE HERE

      //Here I start new activity
      Intent i = new Intent(MainActivity.this, abcd.class);
      startActivity(i);
     }
      })
    .setNegativeButton("No",new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog,int id) {
      // if this button is clicked, just close
      // the dialog box and do nothing
      dialog.cancel();
     }
    });
    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    // show it
    alertDialog.show();
   }
  });
 }
}

Friday, November 9, 2012

Launch Activity with no History

For remove HISTORY of activity from stack


Call finish in your activity right after starting the next activity. Another approach is to add this attribute to your activity in AndroidManifest.xml: android:noHistory="true"
<activity android:name=".YOUR_ACTIVITY" android:noHistory="true"/>
This attribute instructs Android to remove YOUR_ACTIVITY from the history stack once its navigated away from.



For remove History of New launching Activity Using Java Code

Set intent flag FLAG_ACTIVITY_NO_HISTORY before start your activity.
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
The new activity is not kept in the history stack. As soon as the user navigates away from it, the activity is finished


Long click of Button in Android

In this Below example you can set button click event and on long press button event.

Use  can set two different event on button.

  • on button click
  • on button long click.
see below code for this.
public class MainActivity extends Activity {
 /** Called when the activity is first created. */

 private Button btn;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  
  btn = (Button) findViewById(R.id.button1);
  
  btn.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(MainActivity.this,"Button click", Toast.LENGTH_SHORT).show();
   }
  });
  
  btn.setOnLongClickListener(new OnLongClickListener() {
   
   @Override
   public boolean onLongClick(View v) {
    // TODO Auto-generated method stub
    
    Toast.makeText(MainActivity.this,"Button long click", Toast.LENGTH_SHORT).show();
    return true;
   }
  });
 }
}

Thursday, November 8, 2012

Counter in Android

Hello All,

Below is example of creating counter in android application.

Create layout for counter.
Here is activity_main.xml is for my counter layout.


<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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textSize="80dp"
        android:textColor="@android:color/white"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


Java code for Activity is
MainActivity.java


public class MainActivity extends Activity {
 final MyCount counter = new MyCount(10000, 1000);

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  MyCount counter = new MyCount(10000, 1000);// instantiate counter
  counter.start();
 }

 public class MyCount extends CountDownTimer {
  public MyCount(long millisInFuture, long countDownInterval) {
   super(millisInFuture, countDownInterval);
  }

  @Override
  public void onFinish() {
   TextView counter = (TextView) findViewById(R.id.textView1);
   counter.setText("0");
   
   //Do Your code Here after counter finish.
  }

  @Override
  public void onTick(long millisUntilFinished) {
   TextView counter = (TextView) findViewById(R.id.textView1);
   counter.setText(String.valueOf(millisUntilFinished / 1000));

  }
 }
}


Enjoy.....

Open Android Application at StartUp of Mobile.

To Start your application on startup of device.

First we have to create a BroadcastReceiver which will be started when boot completes as


public class MyService extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if(action.equalsIgnoreCase("android.intent.action.BOOT_COMPLETED"))
        {
            Intent myIntent=new Intent(context,package.YourActivity.class);
            myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(myIntent);
        }
}   

onRecieve will be first called when the BroadcastReceiver MyService starts.

Next make an entry of this receiver in AndroidManifest.xml



<receiver android:name=".MyService"
        android:enabled="true" >

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                 <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
</receiver>


Here in intent filter we have declared the action as android.intent.action.BOOT_COMPLETED ,
so that this receiver and intent with action android.intent.action.BOOT_COMPLETED

Now this receiver will be intimated when boot completes

Wednesday, November 7, 2012

Show or Hide soft keyboard on opening a dialog or activity in android

For showing the soft keyboard on entering into the activity or to the dailog we can use this coding.


InputMethodManager show = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
show.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);





and for hiding the keyboard






InputMethodManager hide = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
hide.hideSoftInputFromWindow(**YOUR_VIEW**.getWindowToken(),0);

If you want virtual Keyboard on start of activity. Try below code.

 Your Virtyual key board open on starting of activity.



       

 **YOUR_VIEW**.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager keyboard = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); 
            }
        },200);

Monday, November 5, 2012

Launching other application using code in Android


Here is how to open applications using code

See below example.

Suppose your packagename = com.abc.xyz
Activity name = MainActivity
Than your code is like below example.

final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.abc.xyz", "com.abc.xyz.MainActivity");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( intent);

Detail Description:



To open other people's application, you need to make sure that in their manifest file, the author specify the class to have the android.intent.action.MAIN intent-filter added to them.
final Intent intent = new Intent(Intent.ACTION_MAIN, null);

We then add category that this new intent will be launching something



intent.addCategory(Intent.CATEGORY_LAUNCHER);
Then we get identify the application we need to open by using ComponentName, final ComponentName cn = new ComponentName("PACKAGE_NAME", "ACTIVITY_NAME"); After we identify the component we want, we set it to our intent



intent.setComponent(cn);
We then tell the intent that open opening this one make it as a new task



intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Then finally start our intent



startActivity( intent);

Friday, November 2, 2012

WebView postUrl postData

For post data to web-view using Android.

Use method postUrl  in your java code. Refer below code for post data using web-view.

import org.apache.http.util.EncodingUtils;
public class Example extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
String url = "http://www.example.com";
String postData = username=my_username&password=my_password";
webview.postUrl(url",EncodingUtils.getBytes(postData, "BASE64"));
}  
}