Monday, 23 December 2013

Flash Light Example

Hi Friends,

Today i am going make a code for on/off Flash Light of your Android mobile follow the mention below code:

Example:



Code:

activity_main.xml

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

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="153dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:text="@string/toggal"
        android:textOff="@string/off"
        android:textOn="@string/on"
        android:textStyle="bold" />

</LinearLayout>


MainActivity.java


package in.androiddevelopmentanddiscussion.flashlightexample;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

ToggleButton btn;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;


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

// flash switch button
btn = (ToggleButton)findViewById(R.id.toggleButton1);

/*
* First check if device is supporting flashlight or not
*/
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}

btn.setOnClickListener(new OnClickListener() {
  
  @Override
  public void onClick(View v) {
   if (btn.isChecked()) {
    turnOnFlash();
   }
   else{
    turnOffFlash();
   }
   
  }
 });

// get the camera
getCamera();

}

// getting camera parameters
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}

/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();

params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;

// changing button/switch image
//toggleButtonImage();
}

}

/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();

params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;

// changing button/switch image
//toggleButtonImage();
}
}


/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.light_off);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.light_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {

           @Override
           public void onCompletion(MediaPlayer mp) {

               mp.release();
           }
       }); 
mp.start();
}


}


Manifest

Add below mention permission in your Manifest File


    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" />




Download full project from here




Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en

 

Sunday, 15 December 2013

Custom Title Bar Example

Hi Friends,

You have seen many apps which is having custom title bar with buttons or progress bar so, here i am going to explain you how to create a custom title bar in your application follow the mention below steps.

Example:







Code

res/value/styles.xml

<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

     <style name="WindowTitleBackground" >    
        <item name="android:background">@android:color/transparent</item>        
    </style>
    
    
</resources>


Create a themes.xml file in 
res/value/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyTheme" parent="android:Theme">
        <item name="android:windowTitleSize">60px</item>
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>          
        
    </style>
</resources>


Change you manifest file

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.androiddevelopmentanddiscussion.customtitlebarexample.MainActivity"
            android:label="@string/app_name" 
            android:theme="@style/MyTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Create custom title in res/layout/header.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/red" >

       <Button
           android:id="@+id/header_left_btn"
           android:layout_width="wrap_content"
           android:layout_height="50dp"
           android:layout_marginLeft="5dp"
           android:text=" Back"
           android:textColor="#000000" />
        
        <TextView
            android:id="@+id/header_text"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:singleLine="true"
            android:text="Header Text"
            android:textColor="#FFFFFF"
            android:textSize="20sp"
            android:textStyle="bold" />
            
        <Button
            android:id="@+id/header_right_btn"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginRight="5dp"
            android:text=" Share"
            android:textColor="#000000" />

</LinearLayout>


Create res/value/color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
<color name="transparent">#00000000</color>
<color name="black">#000000</color>
<color name="red">#FF0000</color>
   
</resources>

res/layout/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"
    android:background="@color/white"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

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

</RelativeLayout>


MainActivity.java

package in.androiddevelopmentanddiscussion.customtitlebarexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button back,share;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.header);
 
back = (Button)findViewById(R.id.header_left_btn);
share = (Button)findViewById(R.id.header_right_btn);
 
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "This is a Back Button", Toast.LENGTH_SHORT).show();
}
});
 
share.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "This is a Share Button", Toast.LENGTH_SHORT).show();
}
}); 
 
}
}


Download Full Project from here



Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en

 

Tuesday, 3 December 2013

JSON Parsing Example

About JSON

JSON stands for JavaScript Object Notation. It is a light-weight text-data interchange format. It is self - describing and easy to understand.

JSON uses JavaScript syntax for describing data objects, but it is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages


Example Code For JSON Parsing in Android:


activity_main.xml


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

</ScrollView>


MainActivity.java

package com.json.jsonparsingexample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
StrictMode.enableDefaults();
getData();
}

//Connection Creation to Server

public void getData()
{
String result = " ";
InputStream is = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("URL");
HttpResponse response = httpclient.execute(httpost);
if(response!=null)
{
System.out.println("Connection Created");
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
}
catch(Exception e)
{
Log.i("Error",e.toString());
tv.setText("Connection not Careated");
}
          //Converting Response to Stream
try
{
InputStreamReader isr = new InputStreamReader(is,"iso-8859-1");
BufferedReader reader = new BufferedReader(isr,8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine())!=null)
{
sb.append(line+"\n");
System.out.println(sb);
}
is.close();
result = sb.toString();
tv.setText(result);
}
catch(Exception ex)
{
Log.i("log_tag","Error converting result "+ex.toString());
tv.setText("Error converting result");
}
        //Parsing 


try{
String record = " ";
JSONArray jarray = new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
JSONObject jsonobj = jarray.getJSONObject(i);
record = record+"\n Name :"+jsonobj.getString("name")+"\n URL :"+jsonobj.getString("url");
tv.setText(record);
}
}
catch(JSONException exx)
{
Log.i("log_tag","Error parsing data "+exx.toString());
}
}

}



Manifest

Add internet permission in Manifest

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


That's it .....................

Enjoy Android App Development 

Saturday, 30 November 2013

Install APK Files in Emulator By cmd

Hi Friends,

Here i am going to explain you how to install APK file in Emulator by cmd. follow mention below steps.


  1. First of all run Emulator
  2. Locate adb.exe file in sdk which is normally present in C:\adt-bundle-windows-x86-20130717\sdk\platform-tools.
  3. Paste your APK file in platform-tools folder.
  4. Run Command Prompt (eg. Start -> Programs -> Accessories -> Command Prompt).
  5. Navigate to platform-tools folder in Command Prompt (eg. C:\adt-bundle-windows-x86-20130717\sdk\platform-tools>).
  6. Type adb install myapp.apk press Enter.

That's it, this will install your application in Emulator.

Enjoy Developing Android Apps ...................... 




Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en

 

Thursday, 28 November 2013

Create txt File And Store In SDCard

Hi Friends,

Here i am going to explain how to create a txt file and stored into in SD card of mobile phone, checkout the following codes:

Example:





Codes:

activity_main.xml

<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="Create txt file" />

</LinearLayout>


MainActivity.java

package in.androiddevelopmentanddiscussion.createtxtfileinsdcard;

import java.io.File;
import java.io.FileWriter;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {

Button create;
FileWriter fWriter;

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

create = (Button)findViewById(R.id.button1);

create.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

       try{
            fWriter = new FileWriter(Environment.getExternalStorageDirectory()+ File.separator + "File.txt");
            fWriter.write("Contents of the File");
            fWriter.flush();
            fWriter.close();
            Toast.makeText(MainActivity.this, "File Created in SD Card", Toast.LENGTH_SHORT).show();
        }catch(Exception e){
                 e.printStackTrace();
        }

}
});


}


}


Manifest

Add permissions 

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

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


Download full project from here



Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en

 

Wednesday, 27 November 2013

Fetching All Contacts Details From Phonebook

Hi Friends,

Today i am going to explain you how we can fetch all contacts information from phonebook in our application. Follow mention below steps :

Examples:




Code:

activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/whitecolor" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        
   <TextView
       android:id="@+id/textView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_alignParentRight="true"
       android:layout_alignParentTop="true"
       android:layout_margin="10dp"
       android:gravity="center"
       android:text="Contacts Information"
       android:textSize="20dp" />

   <TextView
       android:id="@+id/textView1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginLeft="10dp"
       android:layout_marginRight="10dp"
       android:layout_marginTop="18dp" />
        
    </LinearLayout>

</ScrollView>


MainActivity.java

package in.androiddevelopmentanddiscussion.getallcontactlist;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView outputText;
background bg;
ProgressDialog pg;
StringBuffer output;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText = (TextView) findViewById(R.id.textView1);

bg = new background();
bg.execute();
}

public void fetchContacts() {

String phoneNumber = null;
String email = null;

Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

Uri EmailCONTENT_URI =  ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;

output = new StringBuffer();

ContentResolver contentResolver = getContentResolver();

Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);

// Loop for every contact in the phone
if (cursor.getCount() > 0) {

while (cursor.moveToNext()) {

String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));

int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));

if (hasPhoneNumber > 0) {

output.append("\nName:" + name);

// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\nNumber:" + phoneNumber);

}

phoneCursor.close();

// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);

while (emailCursor.moveToNext()) {

email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

output.append("\nEmail:" + email);

}

emailCursor.close();
}
output.append("\n");

}


}
}


public void progress(){
pg = new ProgressDialog(MainActivity.this);
pg.setTitle("");
pg.setMessage("Please Wait.........");
pg.setCancelable(false);
        pg.setIndeterminate(true);
pg.show();
}


class background extends AsyncTask<Void, Void, Void>{

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
outputText.setText("Please wait........");
fetchContacts();
return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pg.dismiss();
outputText.setText(output);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress();

}

}


}


Manifest

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




Download full project from here



Check Android Apps on Google Play

https://play.google.com/store/apps/developer?id=Metro%20App%20Solution&hl=en