Ad

Thursday, March 21, 2013

Android get lat and long from address



You can use the Google Geocoder service in the Google Maps API to convert from your location name to a latitude and longitude. So you need some code like

The idea is simple. Make a request to Google Map server and it will return an JSON or XML. Then, parse the JSON to get Lat and Long.

 I have used Google Maps API Here.


    // JSON Node names
    private static final String TAG_RESULTS = "results";
    private static final String TAG_GEOMETRY = "geometry";
    private static final String TAG_VIEWPORT = "viewport";
    private static final String TAG_NORTHEAST = "northeast";
    private static final String TAG_LAT = "lat";
    private static final String TAG_LNG = "lng";
    // contacts JSONArray
    JSONArray results = null;

Android get lat and long from address

// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        address = "Rajkot, Gujarat, India";

        address = address.replaceAll(" ", "%20");
        url = "http://maps.googleapis.com/maps/api/geocode/json?address="
                + address + "&sensor=true";

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of results
            results = json.getJSONArray(TAG_RESULTS);

            Toast.makeText(getApplication(),
                    "Number of results : " + results.length(),
                    Toast.LENGTH_LONG).show();

            for (int i = 0; i < results.length(); i++) {
                JSONObject r = results.getJSONObject(i);

                // geometry and location is again JSON Object
                JSONObject geometry = r.getJSONObject(TAG_GEOMETRY);

                JSONObject viewport = geometry.getJSONObject(TAG_VIEWPORT);

                JSONObject northest = viewport.getJSONObject(TAG_NORTHEAST);

                String lat = northest.getString(TAG_LAT);
                String lng = northest.getString(TAG_LNG);

                tvlat.setText(lat);
                tvlng.setText(lng);
            }

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


JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}


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



Wednesday, March 13, 2013

Android Interview Questions and Answer

1. Define Android?
Android is software stack for mobile devices that has middleware, operating system and specific key applications. The application must be implemented in its own process and Dalvik Virtual Machine interface. DVM device is used to effectively run several virtual machines. The byte code of java language is executed by DVM that is converted to .dex format files.

2. Define Activity?
Activity is nothing but application’s single screen that assists java code.

3. Define intent?
Intent is a class that depicts what caller has to do. Intent is send to intent resolver of Android by the caller which finds appropriate activity for intent. For example: intent is opening PDF doc and the perfect activity for intent is apps of Adobe Reader.

4. Define resource?
Resource is nothing but user defined XML, JSON or bitmap that is inserted in application build process which is later loaded from code.

5. Does Android assist profile of Bluetooth serial port?
Yes



 
6. Is it possible to start an application on powerup?
 
Yes


7. Define APK format?
APK file is compacted AndroidManifest.xml file that has .apk extension. Resource files, Application code and many other files are present in this format and are compressed to single file which has .apk extension.

8. Explain translation in Android?
The data of one language can be changed to other language by Google translator by making use of XMPP for data transmission. You can type English message and choose the language that is easily understood by your country people to reach message to them.

9. On which virtual machine Android runs?
Dalvik virtual machine

10. What is the latest version in android?
Android 4.2(
Jelly Bean)

12. Give the new Android platform for mobile phones?
Android 4.0 and the name given to this version is Ice-cream Sandwich. The versions that came before this are given below:
• 3. X.X Honeycomb
• 2.3. X Gingerbread
• 2.2 Froyo
• 2.0/2.1 Éclair
• 1.6 Donut
• 1.5 Cupcake

13. Give the languages that are supported by Android operating system for developing applications?
It supports all the languages that are written using java code.


14. In what ways data can be stored in Android?
• Internal storage
• Network connection
• Shared preferences
• Sqlite database
• External storage

15. What are user interface types?
• Notifications
• Views


16. Give notification types in Android?
• Dialog notification
• Status bar notification
• Tost notification

Tuesday, March 12, 2013

Android Phone call history/log programmatically


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

    <TextView
        android:id="@+id/call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    private static final int MISSED_CALL_TYPE = 0;
    private TextView txtcall;

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

        txtcall = (TextView) findViewById(R.id.call);

        StringBuffer sb = new StringBuffer();
        Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
                null, null, null);
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        sb.append("Call Details :");
        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;
            int dircode = Integer.parseInt(callType);
            switch (dircode) {

            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                dir = "INCOMING";
                break;

            case CallLog.Calls.MISSED_TYPE:
                dir = "MISSED";
                break;
            }
            sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                    + dir + " \nCall Date:--- " + callDayTime
                    + " \nCall duration in sec :--- " + callDuration);
            sb.append("\n----------------------------------");
        }
        managedCursor.close();
        txtcall.setText(sb);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

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