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..