Sunday, 7 September 2014

List Fragment Example in Android

activity_main.xml

<LinearLayout 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:orientation="horizontal" >

    <fragment
        android:id="@+id/fragment"
        android:layout_width="360dp"
        android:layout_height="match_parent"
        class="org.rajeshvijayakumar.fragments.MenuFragment" />

    <View android:id="@+id/dummy_view"
        android:layout_width="2dp"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray" />
    <RelativeLayout
        android:id="@+id/fragment2"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />

</LinearLayout>


list_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pref_frag_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list" />
</RelativeLayout>


text_fragment.xml

<?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:gravity="center"
    android:background="@android:color/white"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="21sp"
        android:textColor="@android:color/holo_purple"
        android:layout_gravity="center"
        android:id="@+id/name_text_view"/>
</LinearLayout>


MainActivity.java

package org.rajeshvijayakumar.fragments;

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);
    }
}

MenuFragment.java

package org.rajeshvijayakumar.fragments;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MenuFragment extends ListFragment {
    String[] names = new String[] { "Rajesh", "Mahesh", "Mrithula", "Sonika",
            "Ramachander", "Sriram", "Omji", "Raji" };
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, container, false);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, names);
        setListAdapter(adapter);
        return view;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = new TextFragment();
       
        Bundle bundle = new Bundle();
        bundle.putString("names", names[position]);
        fragment.setArguments(bundle);
        fragmentTransaction.add(R.id.fragment2, fragment, "Fragment");
        fragmentTransaction.commit();
        getListView().setSelector(android.R.color.holo_blue_dark);
    }
}


TextFragment.java


package org.rajeshvijayakumar.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends Fragment {
    TextView text,vers;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.text_fragment, container, false);
        text= (TextView) view.findViewById(R.id.name_text_view);
        Bundle bundle = getArguments();
        String name = bundle.getString("names");
        text.setText(name);
               
        return view;
    }
}


AndroidMainfest.xml

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

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

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

</manifest>

Output :





Source in Github Repo.......













Tuesday, 19 August 2014

Address based Location Search in Android

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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/find_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="@string/find" />

    <EditText
        android:id="@+id/search_edittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/find_button"
        android:hint="@string/hint"
        android:inputType="text" />

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/search_edittext"
        class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

MainActivity.java


package com.rajeshvijayakumar.mapaddr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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;

public class MainActivity extends FragmentActivity {

    private Button mFindButton;
    private GoogleMap mMap;
    private EditText mSearchEditText;

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

        mFindButton = (Button) findViewById(R.id.find_button);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = mapFragment.getMap();
        mSearchEditText = (EditText) findViewById(R.id.search_edittext);
        mFindButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String location = mSearchEditText.getText().toString();
                if (location == null || location.equals("")) {
                    Toast.makeText(getBaseContext(), "No Place is entered",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                String url = "https://maps.googleapis.com/maps/api/geocode/json?";
                try {
                    location = URLEncoder.encode(location, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String address = "address=" + location;
                String sensor = "sensor=false";
                url = url + address + "&" + sensor;
                DownloadTask downloadTask = new DownloadTask();
                downloadTask.execute(url);

            }
        });

    }

    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }

        return data;

    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {

        String data = null;

        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            ParserTask parserTask = new ParserTask();
            parserTask.execute(result);
        }

    }

    class ParserTask extends
            AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        @Override
        protected List<HashMap<String, String>> doInBackground(
                String... jsonData) {

            List<HashMap<String, String>> places = null;
            GeoParser parser = new GeoParser();

            try {
                jObject = new JSONObject(jsonData[0]);
                places = parser.parseData(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {

            mMap.clear();
            for (int i = 0; i < list.size(); i++) {
                MarkerOptions markerOptions = new MarkerOptions();
                HashMap<String, String> hmPlace = list.get(i);
                double lat = Double.parseDouble(hmPlace.get("lat"));
                double lng = Double.parseDouble(hmPlace.get("lng"));
                String name = hmPlace.get("formatted_address");
                LatLng latLng = new LatLng(lat, lng);
                markerOptions.position(latLng);
                markerOptions.title(name);
                mMap.addMarker(markerOptions);
                if (i == 0)
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    }
}


GeoParser.java


package com.rajeshvijayakumar.mapaddr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GeoParser {

    public List<HashMap<String, String>> parseData(JSONObject jObject) {

        JSONArray jPlaces = null;
        try {
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return getPlaces(jPlaces);
    }

    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> place = null;

        for (int i = 0; i < placesCount; i++) {
            try {
                place = getPlaces((JSONObject) jPlaces.get(i));
                placesList.add(place);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return placesList;
    }

    private HashMap<String, String> getPlaces(JSONObject jPlace) {

        HashMap<String, String> place = new HashMap<String, String>();
        String formatted_address = "-NA-";
        String lat = "";
        String lng = "";

        try {
            // Extracting formatted address, if available
            if (!jPlace.isNull("formatted_address")) {
                formatted_address = jPlace.getString("formatted_address");
            }

            lat = jPlace.getJSONObject("geometry").getJSONObject("location")
                    .getString("lat");
            lng = jPlace.getJSONObject("geometry").getJSONObject("location")
                    .getString("lng");

            place.put("formatted_address", formatted_address);
            place.put("lat", lat);
            place.put("lng", lng);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return place;
    }
}


Manifest.xml

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

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

    <permission
        android:name="com.rajeshvijayakumar.mapaddr.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.rajeshvijayakumar.mapaddr.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.rajeshvijayakumar.mapaddr.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.maps.v2.API_KEY"
            android:value="YOUR_ANDROID_API_KEY_FROM_CONSOLE" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>


Output :


Source Code: Github Coming soon

Friday, 21 February 2014

HighLighting the Selected List Item using SingleTon Pattern in Android

 Instant Adapter Library Add to your Eclipse Project

 https://github.com/ragunathjawahar/instant-adapter

activity_main.xml


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

    <ListView
        android:id="@+id/demo_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"  />

</RelativeLayout>


list_item.xml

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:src="@drawable/ic_launcher" />

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

</RelativeLayout>


Contact.java

package com.example.insta;

public class Contact {

    private int drawableResId;
    private String contactName;

    public Contact(int drawableResId, String contactName) {
        this.drawableResId = drawableResId;
        this.contactName = contactName;
    }

    public int getDrawableResId() {
        return drawableResId;
    }

    public void setDrawableResId(int drawableResId) {
        this.drawableResId = drawableResId;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }
}

GlobalSingleTon.java

package com.example.insta;
public class GlobalSingleTon {

    private static int position = -1;
    private GlobalSingleTon globalSingleton = null;

    private GlobalSingleTon() {}

    public static synchronized GlobalSingleTon getInstance() {  

         if(globalSingleton == null) {
                     globalSingleton =  new GlobalSingleTon();
         }
         return globalSingleton;
    }

    public static int getPosition() {
        return position;
    }

    public static void setPosition(int position) {
        GlobalSingleTon.position = position;
    }   
}

MainActivity.java


package com.example.insta;

import com.mobsandgeeks.adapters.InstantAdapter;
import com.mobsandgeeks.adapters.ViewHandler;

import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements ViewHandler<Contact> {

    private ListView mContactListView;

    private List<Contact> mContactList;

    private InstantAdapter<Contact> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContactListView = (ListView)findViewById(R.id.demo_list);
        mContactList = new ArrayList<Contact>();
        mContactList.add(new Contact(R.drawable.ic_launcher, "Rajesh"));
        mContactList.add(new Contact(R.drawable.ic_launcher, "Rajesh"));
        mContactList.add(new Contact(R.drawable.ic_launcher, "Rajesh"));
        mContactList.add(new Contact(R.drawable.ic_launcher, "Rajesh"));
        mContactList.add(new Contact(R.drawable.ic_launcher, "Rajesh"));

        mAdapter = new InstantAdapter<Contact>(this, R.layout.list_item, Contact.class,
                mContactList);
        mAdapter.setViewHandler(R.id.imageView1, this);
        mAdapter.setViewHandler(R.id.textView1, this);
        mAdapter.setViewHandler(R.id.par_relative, this);

        mContactListView.setAdapter(mAdapter);
    }

    @Override
    public void handleView(ListAdapter adapter, View parent, final View view, Contact contact,
            int position) {
        switch (view.getId()) {
            case R.id.imageView1:
                ((ImageView)view).setBackgroundResource(contact.getDrawableResId());
                break;
            case R.id.textView1:
                ((TextView)view).setText(contact.getContactName());
                break;
            case R.id.par_relative:
                final int pos = position;
                ((RelativeLayout)view).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        GlobalSingleTon.setPosition(pos);
                        mAdapter.notifyDataSetChanged();
                      
                    }
                });
        }
      
        if(position == GlobalSingleTon.getPosition()) {
            view.setBackgroundColor(Color.GREEN);
        } else {
            view.setBackgroundColor(Color.WHITE);
        }
    }
}


output :



Source Code :  Coming Soon..

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 :