Wednesday, 24 September 2014

Google Maps v2 in android

So before we start developing maps we need to download google play sevices from SDK manger. You can open SDK manager either from Eclipse or from android sdk folder.
Go to Eclipse --> Windows --> Android SDK Manager and check whether you have already downloaded Google Play Services or not under Extras section. If not select play services and install the package.



Importing Google Play Services into your project
. In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace

1. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib
2. Importantly while importing check Copy projects into workspace option as shown in the below image.



Getting the Google Maps API key

Same as in maps v1 we need to generate SHA-1 fingerprint using java keytool. Open your cmd and execute the following command to generate SHA-1 fingerprint.

On Windows
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
My debug.keystore is in C:\Users\user\.android\.android\debug.keystore



Copy your SHA Key because you will need it in furthe steps.

Select Projects on left side and then create project.  Give your project name that you have created in you IDE. Dont change anything in project id and click create.

Now click APIs & Auth and select APIs and turn on Google Maps Api v2.
Now select Credentials and click on Create new Key there select Android key and  Enter your SHA 1 and your  Package Name separated by semicolon ; and click on create.
And note down the API key which required later in our project.


Creating new Project

After completing required configuration, It’s time to start our project.
1. In Eclipse create a new project by going to File ⇒ New ⇒ Android Application Project and fill required details. I kept my project name as GoogleMapsv2 and package name as   com.example.googlemapsv2
2. Now we need to use Google Play Services project as a library to use project. So right click on project and select properties. In the properties window on left side select Android. On the right you can see Add button under library section. Click it and select google play services project which we imported previously.
Now Open Your Android Manifest.xml




<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlemapsv2"
    android:versionCode="1"
    android:versionName="1.0" >
    <permission
      android:name="com.example.googlemapsv2.permission.MAPS_RECEIVE"
      android:protectionLevel="signature" />
<uses-permission android:name="com.example.googlemapsv2.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="11"

        android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

   <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"
     >
        <activity
            android:name="com.example.googlemapsv2.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>
<!-- Google Api Key -->
<meta-data
   android:name="com.google.android.maps.v2.API_KEY"
   android:value="Your Api Key" />
<!-- Dont Forget to mention the below code -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
    </application>


</manifest>

 New google maps are implemented using MapFragments which is a sub class of Fragments class. Open your main activity layout file activity_main.xml file and add following code. I used RelativeLayout as a parent element. You can remove it and use MapFragment directly.

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

   <fragment
      android:id="@+id/map"
      android:name="com.google.android.gms.maps.MapFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>


</RelativeLayout>

Add the following code in your Main Activity java MainActivity.java class
MainActivity.java 
package com.example.googlemapsv2
import com.google.android.gms.maps.CameraUpdate;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.MapFragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

  // Google Map

  private GoogleMap googleMap;


  // GPS Location
  

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_map);
try {
    //Loading map
      initilizeMap();

 } catch (Exception e) {
      e.printStackTrace();
    }
 }
 private void initilizeMap() {
    if (googleMap == null) {
      googleMap = ((MapFragment) getFragmentManager().findFragmentById(
          R.id.map)).getMap();
if (googleMap == null) {

        Toast.makeText(getApplicationContext(),
            "Sorry! unable to create maps", Toast.LENGTH_SHORT)
            .show();
          
      }
    }
  }


  @Override
  protected void onResume() {
    super.onResume();
    initilizeMap();
  }
}
Now Run your project in your device because emulator dosent support maps..

If you feel like any difficulties then post your comment..



Monday, 22 September 2014

How to use navigation drawer in webview

By- Nitesh Kumar Mishra
In most of the android applications like Facebook, Google plus , Youtube, amazon kindle , true caller .. etc you have seen a side menu which appears on click of an icon on top left corner or by dragging on to the screen from left to right , so here in this tutorial we shall see how to create the sliding menu for you android application .





Now go to File-New -Android Application Project and give name as Navigation Drawer..

MainActivity.java 


package com.example.navigationdrawer;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends Activity {

String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;

// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;

private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private List<Row> rowItems;
private CustomAdapter adapter;

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

mTitle = mDrawerTitle = getTitle();

menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);

rowItems = new ArrayList<Row>();

for (int i = 0; i < menutitles.length; i++) {
Row items = new Row(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}

menuIcons.recycle();

adapter = new CustomAdapter(getApplicationContext(), rowItems);

mDrawerList.setAdapter(adapter);

mDrawerList.setOnItemClickListener(new SlideitemListener());

// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}

public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);

if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);

}
}

class SlideitemListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}

}

private void updateDisplay(int position) {

String url = rowItems.get(position).getPageUrl();

Fragment fragment = new WebActivity();

Bundle bundle = new Bundle();
bundle.putString("url", url);

fragment.setArguments(bundle);

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();

setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);

}

@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}

/***
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}

/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}


}

CustomAdapter.java

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {

Context context;
List<Row> rowItem;

CustomAdapter(Context context, List<Row> rowItem) {
this.context = context;
this.rowItem = rowItem;
}

private class ViewHolder {
ImageView icon;
TextView title;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;
convertView = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.title = (TextView) convertView.findViewById(R.id.title);

Row row_pos = rowItem.get(position);
// setting the image resource and title
holder.icon.setImageResource(row_pos.getIcon());
holder.title.setText(row_pos.getTitle());
convertView.setTag(holder);

}
return convertView;

}

@Override
public int getCount() {
return rowItem.size();
}

@Override
public Object getItem(int position) {
return rowItem.get(position);
}

@Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}


}

Row.java


public class Row {
private String title;
private int icon;
private String pageUrl;

public Row(String title, int icon, String pageUrl) {
this.title = title;
this.icon = icon;
this.pageUrl = pageUrl;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public int getIcon() {
return icon;
}

public void setIcon(int icon) {
this.icon = icon;
}

public String getPageUrl() {
return pageUrl;
}

public void setPageUrl(String pageUrl) {
this.pageUrl = pageUrl;
}


}

WebActivity.java

import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebActivity extends Fragment {

ProgressDialog mProgress;
WebView webview;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web, container,
false);

Bundle bundle = getArguments();

String url = bundle.getString("url");

webview = (WebView) rootView.findViewById(R.id.webview1);

WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);

mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);

webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

view.loadUrl(url);
return true;
}

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});

return rootView;
}
}

Now in your xml files first go to 
res-values-string.xml and made following changes

string.xml



<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Navigation Drawer</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
<string name="imgdesc">imgdesc</string>
    <!-- Title -->
    <string-array name="titles">
        <item>SysWAY Technologies</item>
     
 <item>Facebook</item>
        <item>Twitter</item>
        <item>Google Plus</item>
        <item>Yahoo</item>
        <item>LinkedIn</item>
        <item>Blogger</item>
        <item>Wordpress</item>
    </string-array>
    <!-- Page Url -->
    <string-array name="pageurl">
        <item>http://www.swtinfo..com</item>
        <item>http://www.facebook.com</item>
        <item>https://twitter.com</item>
        <item>https://plus.google.com</item>
        <item>http://www.yahoo.com</item>
        <item>http://www.linkedin.com</item>
        <item>http://www.blogger.com</item>
        <item>http://www.wordpress.com</item>
    </string-array>
    <!-- Icons -->
    <array name="icons">
        <item>@drawable/facebook</item>
        <item>@drawable/facebook</item>
        <item>@drawable/twitter</item>
        <item>@drawable/googleplus</item>
        <item>@drawable/yahoo</item>
        <item>@drawable/linkedin</item>
        <item>@drawable/blogger</item>
        <item>@drawable/wordpress</item>
    </array>

</resources>

activity_main.xml


<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!-- The main content view -->

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>
    <!-- The navigation drawer list -->

    <ListView
        android:id="@+id/slider_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#ffffff"
        android:choiceMode="singleChoice"
        android:divider="#dddddd"
        android:dividerHeight="1dp" />

</android.support.v4.widget.DrawerLayout>

listitem.xml

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

    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:contentDescription="@string/imgdesc" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="7dp"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:textColor="#000000"
        android:textSize="20sp" />

</RelativeLayout>

web.xml

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

    <WebView
        android:id="@+id/webview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true" />

</RelativeLayout>

In your manifest dont forget to use internet permission

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


If you like this post then pls comment so that i could write more on android topics..