Tuesday 24 December 2013

Bar Code Example in Android

Step 1 : 

Download Zxing Library for barcode and Add it to your project.


Step 2 : 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" >

    <Button
        android:id="@+id/scan_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="54dp"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="42dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Step 3 :  MainActivity.java

package com.rajeshvijayakumar.barcode;

public class MainActivity extends Activity implements OnClickListener {

    private ZXingLibConfig zxingLibConfig;
    private Button mScanBarCodeButton;
    private TextView mSummaryView;
    private String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScanBarCodeButton = (Button) findViewById(R.id.scan_button);
        mSummaryView = (TextView) findViewById(R.id.textView1);
        mScanBarCodeButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
        case R.id.scan_button:
            IntentIntegrator.initiateScan(MainActivity.this, zxingLibConfig);
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case IntentIntegrator.REQUEST_CODE:
            IntentResult scanResult = IntentIntegrator.parseActivityResult(
                    requestCode, resultCode, data);
            if (scanResult != null) {
                result = scanResult.getContents();// scanned result
                mSummaryView.setText("Scanned Barcode : "+ result);
                } else {
                    // DO Something
                }
            break;
        default:
        }
    }
}

 Step 4: Manifest.xml

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

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.rajeshvijayakumar.barcode.MainActivity"
            android:screenOrientation="landscape"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="jim.h.common.android.lib.zxing.CaptureActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden" />
    </application>

</manifest>

Expected Output :




GitHub: https://github.com/rajeshmcashc10/rajeshvijayakumar-android/tree/master/barcode-example






Thursday 19 December 2013

Simple Time Widget Example in Android

wc_home_widget.xml

<RelativeLayout android:id="@+id/widget_layout" 
       xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:background="#08458c" >

    <TextView
        android:id="@+id/widget_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="5dp"
        android:text="12:00 PM"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/day_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/widget_textView"
        android:layout_below="@+id/widget_textView"
        android:layout_marginTop="16dp"
        android:text="Day"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/date_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/day_textView"
        android:layout_alignBottom="@+id/day_textView"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/day_textView"
        android:text="currentDate"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>


TimeWidget.java

package com.rajeshvijayakumar.widget;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RemoteViews;
import android.widget.Toast;

public class TimeWidget extends AppWidgetProvider implements OnClickListener {

    private Date mCurrentTime;
    private int mYear;
    private PendingIntent pendingIntent;
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();

        RemoteViews remoteViews1 = new RemoteViews(context.getPackageName (), R.layout.wc_home_widget);
//        Intent intent = new Intent(context, AddLocationActivity.class);
//        pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000);
   
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }
   
    private class MyTime extends TimerTask {
       
        RemoteViews remoteViews;
        AppWidgetManager appWidgetManager;
        ComponentName thisWidget;
        DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());
               
        public MyTime(Context context, AppWidgetManager appWidgetManager) {
            this.appWidgetManager = appWidgetManager;
           
            remoteViews = new RemoteViews(context.getPackageName(), R.layout.wc_home_widget);
            remoteViews.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
            thisWidget = new ComponentName(context, TimeWidget.class);
           
        }
       
        @Override
        public void run() {
            mCurrentTime = new Date();
            remoteViews.setTextViewText(R.id.widget_textView, "" + format.format(mCurrentTime));
            remoteViews.setTextViewText(R.id.day_textView, ""+DateTimeUtils.getDayName(mCurrentTime.getDay()));
            remoteViews.setTextViewText(R.id.date_textView, ""+mCurrentTime.getDate()+" "+DateTimeUtils.getMonthName(mCurrentTime.getMonth()));
           
            //  MMM
               
            appWidgetManager.updateAppWidget(thisWidget, remoteViews);
        }
    }
   
    @Override
    public void onReceive(Context context, Intent intent) {
       
        final String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
            final int appWidgetId = intent.getExtras().getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                this.onDeleted(context, new int[] { appWidgetId });
            }
        } else {
            super.onReceive(context, intent);
        }
    }
   
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        Toast.makeText(context, "onDelete", Toast.LENGTH_SHORT).show();
        super.onDeleted(context, appWidgetIds);
    }

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

}

DateTimeUtils.java

package com.rajeshvijayakumar.widget;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class DateTimeUtils {
    private static Calendar cal;

    public static void setTimeZoneForApp(String timezoneId) {
        cal = new GregorianCalendar(TimeZone.getTimeZone(timezoneId));
    }

    public static Calendar getTimeZoneForApp() {
        return cal;
    }

    public static String getCountryTime(String timeZoneId, boolean countryTime) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneId));
       
        int minutes = cal.get(Calendar.MINUTE); // 0..59
        int seconds = cal.get(Calendar.SECOND); // 0..59
        String min12 = (minutes < 10) ? "0" + minutes : "" + minutes;
        String sec12 = (seconds < 10) ? "0" + seconds : "" + seconds;
        boolean am = cal.get(Calendar.AM_PM) == Calendar.AM;
        String amorpm = (am == true) ? "AM" : "PM";
        String hour = "";
        if (countryTime == true) {
            int hour12 = cal.get(Calendar.HOUR); // 0..11
            int hr12 = (hour12 == 0) ? 12 : hour12;
            hour = hr12 + ":" + min12.trim()+ " " + amorpm;
        } else {
            cal.setTimeZone(TimeZone.getTimeZone("GMT"));
            int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
            String hr24 = (hour24 < 0) ? "0" + hour24 : "" + hour24;
            hour = hr24 + ":" + min12;
        }
        return hour;
    }

    public static String getCurrentDate(String format,
            boolean displayCurrentDate) {
        if (displayCurrentDate == true) {
            Calendar c = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat(format);
            String formatted = df.format(c.getTime());
            return formatted;
        } else {
            return "";
        }
    }

    public static String getCountryDate(String timeZoneId,
            boolean displayCountryDate) {

        if (displayCountryDate == true) {
            Calendar cal = new GregorianCalendar(
                    TimeZone.getTimeZone(timeZoneId));
            int date = cal.get(Calendar.DATE);
            int month = cal.get(Calendar.MONTH);
            String monthName = getMonthName(month);
            int year = cal.get(Calendar.YEAR);
            return +date + "-" + monthName + "-" + year;
        } else {
            return "";
        }
    }

    public static String getDayName(int dayNo) {
        String dayName = "";
        switch (dayNo) {
        case 0:
            dayName = "Sun";
            break;
        case 1:
            dayName = "Mon";
            break;
        case 2:
            dayName = "Tue";
            break;
        case 3:
            dayName = "Wed";
            break;
        case 4:
            dayName = "Thu";
            break;
        case 5:
            dayName = "Fri";
            break;
        case 6:
            dayName = "Sat";
            break;

        }
        return dayName;

    }

    public static String getMonthName(int month) {
        String monthName = "";
        switch (month) {
        case 0:
            monthName = "Jan";
            break;
        case 1:
            monthName = "Feb";
            break;
        case 2:
            monthName = "Mar";
            break;
        case 3:
            monthName = "Apr";
            break;
        case 4:
            monthName = "May";
            break;
        case 5:
            monthName = "Jun";
            break;
        case 6:
            monthName = "Jul";
            break;
        case 7:
            monthName = "Aug";
            break;
        case 8:
            monthName = "Sep";
            break;
        case 9:
            monthName = "Oct";
            break;
        case 10:
            monthName = "Nov";
            break;
        case 11:
            monthName = "Dec";
            break;
        }
        return monthName;
    }

}

Manifest.xml file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rajeshvijayakumar.widget"
    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"
        android:theme="@style/AppTheme" >
        <receiver
            android:name=".TimeWidget"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/hello_widget_provider" />
        </receiver>
    </application>

</manifest>

Ouput :




GitHub :    https://github.com/rajeshmcashc10/rajeshvijayakumar-android/tree/master/widgetdemo


Sunday 11 August 2013

StartActivityForResult with Dialog Activity Example in Android

In activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="95dp"
        android:layout_marginTop="62dp"
        android:textSize="19sp"
        android:text="**********" />

    <Button
        android:id="@+id/set"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/name"
        android:layout_below="@+id/name"
        android:layout_marginTop="24dp"
        android:text="Set Name" />

</RelativeLayout>


In dialog_box.xml

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

    <EditText
        android:id="@+id/name_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/ok"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name_edit_text"
        android:layout_marginTop="50dp"
        android:layout_toLeftOf="@+id/cancel"
        android:text="Ok" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/ok"
        android:layout_alignBottom="@+id/ok"
        android:layout_alignParentRight="true"
        android:layout_marginRight="14dp"
        android:text="Cancel" />

</RelativeLayout>


MainActivity.java

package com.rajeshvijayakumar.safr;

public class MainActivity extends Activity implements OnClickListener {

    private TextView mNameTextView;
    private Button mSetButton;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNameTextView = (TextView) findViewById(R.id.name);
        mSetButton = (Button) findViewById(R.id.set);
        mSetButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.set:
            Intent intent = new Intent(this, NameDialogActivity.class);
            startActivityForResult(intent, 1);
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
        if(resultCode == RESULT_OK && data.getExtras().containsKey("name")) {
            String name = data.getExtras().getString("name");
            mNameTextView.setText(name);
        }
    }   
}


NameDialogActivity.java

package com.rajeshvijayakumar.safr;

public class NameDialogActivity extends Activity implements OnClickListener {

    private EditText mNameEditText;
    private Button mOk;
    private Button mCancel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_box);
        mNameEditText = (EditText) findViewById(R.id.name_edit_text);
        mOk = (Button) findViewById(R.id.ok);
        mCancel = (Button) findViewById(R.id.cancel);
        mOk.setOnClickListener(this);
        mCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        Intent intent = getIntent();
        switch (v.getId()) {
        case R.id.ok:
            String name = mNameEditText.getText().toString();
            intent.putExtra("name", name);
            setResult(RESULT_OK, intent);
            break;
        case R.id.cancel:
            setResult(RESULT_CANCELED, intent);
            break;
        }
        finish();
    }
}


In manifest.xml add theme as @android:style/Theme.Dialog for NameDialogActivity

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.rajeshvijayakumar.safr.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>
        <activity
            android:name=".NameDialogActivity"
            android:theme="@android:style/Theme.Dialog" />
    </application>

</manifest>


Output :