Sunday, 24 August 2014

Android navigation drawer tutorial | Android navigation drawer with activities | Android Sliding Navigation Drawer – Example

Hello Droid Guys
     Today,  I am going to share the tutorial of  "Android sliding navigation drawer". You also find many tutorial on Google which helps you to show navigation drawer but most of them are using fragment to do that. Here, are the few good tutorial which I follows:
Android Navigation Drawer
Navigation drawer activity

1. https://developer.android.com/design/patterns/navigation-drawer.html
2. http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

Here, I am going show sliding menu using activity. We can also achieve
the functionality of  Navigation drawer with activities.

This Android tutorial describes How to implement a navigation drawer using  Support Library the DrawerLayout API.

1. Create Drawer Layout :
            To create a navigation drawer, We first declare user interface with a
DrawerLayout as the root view of layout.

Inside the Drawer Layout, add one view that contains the main content for the
screen (your primary layout when the drawer is hidden) and another view that
contains the contents of the navigationdrawer. In this example, I am using a DrawerLayout
with two child. One a Relative layout with webView(the main content), and other
with a ListView for the navigation drawer. The webview is my activity content view.

<?xml version="1.0" encoding="utf-8"?>
<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" >
    <!--
          main content
     -->

    <RelativeLayout

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:background="#ffffff" >

        <WebView

            android:id="@+id/webview"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:background="#ffffff" />

    </RelativeLayout>

    <!--
        navigation list item
    -->
    <FrameLayout

        android:id="@+id/content_frame"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />

    <ListView

        android:id="@+id/left_drawer"

        android:layout_width="240dp"

        android:layout_height="match_parent"

        android:layout_gravity="left"

        android:background="#2A323D"

        android:cacheColorHint="#00000000"

        android:choiceMode="singleChoice" />



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


2. Initialize the Drawer List :
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);

mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
		GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new MenuDrawerListAdapter(this, menuItemTitles,
			Config.drawerMenuItemsIconIds));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());


3. Handle Navigation List click event :

/* The click listener for ListView in the navigation drawer */
public class DrawerItemClickListener implements
	ListView.OnItemClickListener {
	@Override
	public void onItemClick(AdapterView parent, View view, int position,
		long id) {
		switch (position) {
		case 0: {
		Intent main = new Intent(getApplicationContext(),
				MainActivity.class);
		startActivity(main);
		finish();
		break;
        	}
		case 1: {
		Intent list = new Intent(getApplicationContext(),
				ListActivity.class);
		startActivity(list);
		finish();
		break;
		}
			
		default:
		break;
         }
	}
}

Download Code : Navigation Drawer Demo

Hope this will help someone.
Enjoy Coding...   :)

Sunday, 10 August 2014

Android Download Source code | Android Sample Project

Hello Friends,
  This is my small contribution , Now I am sharing the source code of all my android
  post or android tutorial at one place.


Android Tutorial Download Code
Android Custom Calendar Download Code
Android LinkedIn Integration Download Code
Android Crop Image in circular shape like gmail and facebook Download Code
Android facebook like left to right slide navigation Download Code
Android facebook and skype like animated splash screen Download Code
Google map V2 sample with draw polygon or draw geometry and save polygon Download Code
Android video Player Download Code
Android navigation drawer tutorial Download Code
Android Custom Horizontal progress bar |"N" level Horizontl Progress Bar Download Code

Sunday, 20 July 2014

Android Splash Screen Example with Animation | Animated Splash Screen android

Hello Friends,
        Today, I am going to share the tutorial of android splash screen with animation.
With help of this tutorial you can easily implement the facebook like splash screen
or skype like splash screen.
                           
Android animated splash screen

1. Create an Android Project "SplashScreen"
2. Create an folder "anim" inside the res folder
3. Create two file inside the "anim" folder
      a. alpha.xml
   
         <?xml version="1.0" encoding="utf-8"?>

              <alpha
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:fromAlpha="0.0"
              android:toAlpha="1.0"
              android:duration="3000" />

     b. translate.xml
<?xml version="1.0" encoding="utf-8"?>

         <set

              xmlns:android="http://schemas.android.com/apk/res/android">
             <translate
                 xmlns:android="http://schemas.android.com/apk/res/android"
                 android:fromXDelta="0%"
                 android:toXDelta="0%"
                 android:fromYDelta="900%"
                 android:toYDelta="0%"
                 android:duration="2000"
                 android:zAdjustment="top" />
         </set>

4. inside your oncreate() called this method
 
public class SpalshScreenActivity extends Activity {

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StartAnimations();

    }
     ................
     ................

  }

      private void StartAnimations() {
    	Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
		anim.reset();
		LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
		l.clearAnimation();
		l.startAnimation(anim);

		anim = AnimationUtils.loadAnimation(this, R.anim.translate);
		anim.reset();
		ImageView iv = (ImageView) findViewById(R.id.logo);
		iv.clearAnimation();
		iv.startAnimation(anim);

		anim = AnimationUtils.loadAnimation(this, R.anim.translate);
		anim.reset();
		LinearLayout l2 = (LinearLayout) findViewById(R.id.linear2);
		l2.setVisibility(View.VISIBLE);
		l2.clearAnimation();
		l2.startAnimation(anim);
    }


Download the code : Android animate splash sreen

Hope this will help someone
Enjoy Coding.... :)

ActiveAndroid Tutorial | ActiveAndroid: Android ORM base database |Getting Started with ActiveAndroid - Part1

ActiveAndrid :                                                                               
Active Android


ActiveAndroid is an ORM (object relational mapper) . Which allows you to save(insert)
and retrieve(read) SQLite database records without even writing a single SQL statement.
Each database record is wrapped neatly into a class with methods like save().
It is same a Java Hibernate. It also based on annotation like: @Column(name="Column")  for creating column and Table(name = "Table")  for creating table .

Getting started : 
A.Now here we are going to start integrating ActiveAndroid in your project.
    1. Download the ActiveAndroid library
    2. Now generate the ActiveAndroid.jar by executing ant in root folder
    3. If you are unable to generate the jar file then download it from here

 Now, we have ActiveAndroid.jar file.  Now, we can add it inside the "libs" folder of
Android Project.    

B. Configuring Android Project with ActiveAndroid :
    1. Open the AndroidManifest.xml file located at the root directory of your Android project.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.developer.solutions"
    android:versionCode="1"
    android:versionName="1.0" >
        <application
           android:name="com.activeandroid.app.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>
        
         <meta-data android:name="AA_DB_NAME" android:value="Student.db" />
         <meta-data android:name="AA_DB_VERSION" android:value="1" />
        </application>
</manifest>


Note:  In your manifest.xml, if you are not using any Custom Application class then the application name points to the ActiveAndroid application class as we are doing above. But if you are using any Application levele custom class then your Custom Application class must extend com.activeandroid.app.Application instead of android.app.Application.

public class MyApplication extends com.activeandroid.app.Application { ...


And initialize and dispose ActiveAndroid in the Application class.

public class MyApplication extends com.activeandroid.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ActiveAndroid.initialize(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ActiveAndroid.dispose();
    }
}

Note : If you want to create your db in a specific location inside your Sd Card then change below line in manifest.xml

<meta-data android:name="AA_DB_NAME" android:value="/sdcard/Student.db" />

<meta-data android:name="AA_DB_VERSION" android:value="1" />

Here, we are creating our database file inside the sd card root folder.
So that we can easily import it in Sqlite Browser .

Tuesday, 8 July 2014

Android Google Glass Configuration | Glass Development Kit | Android Google Glass Setup | Android Google Glass Development -Part1

Hello Friend ,
    This is my first blog on Android Google Glass . Lats month Google launches
some awesome feature like:                                                          
         1. Android L Developer Preview
         2. Android Wear SDK
         3. Android TV Preview SDK
         4. Google glass


Today, I am going to share my small tutorial on Google glass which helps you in 
in Configuring the Google glass development environment in Eclipse.

Glass Development Kit :  First you need GDK
The Glass Development Kit (GDK) is an add-on to the Android SDK that lets you build Glassware that runs directly on Glass. 

Steps to setup Google Glass Development :
    1.Get the Android 4.4.2 (API 19) SDK and Glass Development Kit Preview 
       add-on from the Android SDK Manager. see the image 


   2. On Glass, turn on USB debugging (Settings > Device Info > Turn on debug).
   3. Import some GDK samples with the File > New Project > Android Sample Project menu.
   4. When you're ready to create a project for your own Glassware, use these settings:
- Minimum and Target SDK Versions: 19 (There is only one Glass version, 
           so minimum and target SDK are the same.)
- Compile with: Glass Development Kit Developer Preview
- Theme: None (ADT and Android Studio usually assign a theme automatically,
           even if you specify no theme, so remove the android:theme property from your manifest after
           creating a project.)

For more Detail Check this link
                                  https://developers.google.com/glass/develop/gdk/quick-start


2. Android Google Glass Development -Part2 - (coming soon)


Hope, this will helps someone.
Enjoy Coding..... :)

Sunday, 15 June 2014

Android send emails | Android send emails w/t built-in mailing app | Android send emails from the background

Hello Friends,
                Today, I am sharing another important tutorial. While doing development
some times we came across to this requirement, "Sending emails to users" without
using any built-in mailing app(like: Gmail,Yahoo etc). In that time we normally depends
on web-service, we write a service in PHP or JAVA or .Net and the communicate b/w them.

But, know now no need to depends on web-service we can send the mail directly through
our java code.

This tutorial going to covers following features :

1. Sending email without using any built-in mailing app
2. Sending emails without User Intervention
3. Sending  emails to multiple users
4. Sending emails with attachment
5. Sending emails silently without any mail composer


Here are my code:

1. Download java mil.jar, activation.jar and additionnal.jar from below link :
        http://code.google.com/p/javamail-android/downloads/list          

2. Add this jar files in your project libs folder

3. MainActivity.java

package com.androiddeveloper.solutions.sendemail;

import java.io.File;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

/**
 * @author: Mukesh Y
 * @link: http://www.androiddevelopersolutions.com/
 */
public class MainActivity extends Activity {

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

  ImageButton addImage = (ImageButton) findViewById(R.id.action_send_email);
  addImage.setOnClickListener(new View.OnClickListener() {
   public void onClick(View view) {
    new BackGroundAsyncTask().execute();
   }
  });

 }

 public class BackGroundAsyncTask extends AsyncTask {

  ProgressDialog prog_synprocess = new ProgressDialog(MainActivity.this);

  String statusMessage = "";

  @Override
  protected void onPostExecute(String status) {
   prog_synprocess.hide();
   Toast.makeText(MainActivity.this, status, Toast.LENGTH_LONG).show();

  }

  @Override
  protected void onPreExecute() {
   prog_synprocess.setCancelable(false);
   prog_synprocess.setProgressStyle(ProgressDialog.STYLE_SPINNER);
   prog_synprocess.setMessage("Sending...");
   prog_synprocess.show();
  }

  @Override
  protected String doInBackground(String... arg0) {

   try {
    statusMessage = sendLogFile();
   } catch (Exception e) {
    Log.e("Error", e.getMessage());
    statusMessage = "Error in updation";
   }
   return statusMessage;

  }
 }

 private String sendLogFile() {
  String statusMessage = "";
  Mail m = new Mail("dataworld.dw@gmail.com", "testtest");

  String[] toArr = { "mukesh421985@gmail.com" };
  m.setTo(toArr);
  m.setFrom("dataworld.dw@gmail.com");
  String email_subject = "Testing Send mail";
  m.setSubject(email_subject);
  m.setBody("PFA");

  try {
   String pathToMyAttachedFile = Environment
     .getExternalStorageDirectory()
     + File.separator
     + "Project.log";
   File file = new File(pathToMyAttachedFile);
   if (!file.exists() || !file.canRead()) {
    statusMessage = "File not found";
    return statusMessage;
   } else {
    m.addAttachment(file.getAbsolutePath());
   }
   if (m.send()) {
    statusMessage = "Email was sent successfully.";
   } else {
    statusMessage = "Email was not sent.";
   }
  } catch (Exception e) {
   // Toast.makeText(MailApp.this,
   // "There was a problem sending the email.",
   // Toast.LENGTH_LONG).show();
   Log.e("Send Mail", e.getMessage());
   statusMessage = "There was a problem sending the email.";
  }

  return statusMessage;
 }

}

2. Mail.java 

package com.androiddeveloper.solutions.sendemail;

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * @author: Mukesh Y
 * @link: http://www.androiddevelopersolutions.com/
 */
public class Mail extends javax.mail.Authenticator {
 private String userName;
 private String password;

 private String[] to;
 private String from;

 private String portNumber;
 private String socketPortNumber;

 private String host;

 private String emailSubject;
 private String emailBody;

 private boolean auth;

 private boolean debuggable;

 private Multipart multipart;

 public Mail() {
  // default smtp server
  host = "smtp.gmail.com";
  
  // default smtp port
  portNumber = "465"; 
  // default socketfactory port
  socketPortNumber = "465";
  
  // username
  userName = ""; 
  password = ""; 
  
  // email sent from
  from = ""; 
  
  // email subject
  emailSubject = "";
  
  // email body
  emailBody = ""; 

  // debug mode on or off - default off
  debuggable = false; 
  
  // smtp authentication - default on
  auth = true; 

  multipart = new MimeMultipart();

  // There is something wrong with MailCap, javamail can not find a
  // handler for the multipart/mixed part, so this bit needs to be added.
  MailcapCommandMap mc = (MailcapCommandMap) CommandMap
    .getDefaultCommandMap();
  mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  CommandMap.setDefaultCommandMap(mc);
 }

 public Mail(String user, String pass) {
  this();

  userName = user;
  password = pass;
 }

 public boolean send() throws Exception {
  Properties props = _setProperties();

  if (!userName.equals("") && !password.equals("") && to.length > 0
    && !from.equals("") && !emailSubject.equals("")
    && !emailBody.equals("")) {
   Session session = Session.getInstance(props, this);

   MimeMessage msg = new MimeMessage(session);

   msg.setFrom(new InternetAddress(from));

   InternetAddress[] addressTo = new InternetAddress[to.length];
   for (int i = 0; i < to.length; i++) {
    addressTo[i] = new InternetAddress(to[i]);
   }
   msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

   msg.setSubject(emailSubject);
   msg.setSentDate(new Date());

   // setup message body
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setText(emailBody);
   multipart.addBodyPart(messageBodyPart);

   // Put parts in message
   msg.setContent(multipart);

   // send email
   Transport.send(msg);

   return true;
  } else {
   return false;
  }
 }

 public void addAttachment(String filename) throws Exception {
  BodyPart messageBodyPart = new MimeBodyPart();
  FileDataSource source = new FileDataSource(filename);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(filename);

  multipart.addBodyPart(messageBodyPart);
 }

 @Override
 public PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(userName, password);
 }

 private Properties _setProperties() {
  Properties props = new Properties();

  props.put("mail.smtp.host", host);

  if (debuggable) {
   props.put("mail.debug", "true");
  }

  if (auth) {
   props.put("mail.smtp.auth", "true");
  }

  props.put("mail.smtp.port", portNumber);
  props.put("mail.smtp.socketFactory.port", socketPortNumber);
  props.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.socketFactory.fallback", "false");

  return props;
 }

 // the getters and setters
 public String getBody() {
  return emailBody;
 }

 public void setBody(String _body) {
  this.emailBody = _body;
 }

 // more of the getters and setters …..
 public void setTo(String[] toArr) {
  this.to = toArr;
 }

 public void setFrom(String string) {
  this.from = string;
 }

 public void setSubject(String string) {
  this.emailSubject = string;
 }
}


Hope this will helps some one.
Enjoy coding... cheers :)

Friday, 13 June 2014

ListView setOnItemClickListener not working by adding button | ListView setOnItemClickListener issue

Hello Friends,
                    Today, I found another issue with Android  ListView.OnItemClickListner.
Actually I have a list view with items image and text and when I am clicking on it then ListView.OnItemClickListner called and all working fine. But when I added a
button or toggle button(android switch) in existing one then in this case the ListView.OnItemClickListner stop working.

This are the step to reproduce:

1) I have a ListView with an Image and textview.
2) I set ListView.OnItemClickListner. When I run my project It's show my ListView.
3) When I click on Listview It's working fine.
4) Then I added one more item in my item.xml file i.e:added    a button
5) Then When I click on Listview It's not working.
6) Then I removed the added Button from the item.xml and run  my project again when
     I click ListView It' work
7) What wrong ?


Then I figure out the problem by adding the following two line of code in my Button view.

android:focusable="false"
android:focusableInTouchMode="false"

Hope this will helpfull for some one. Enjoy Coding....... Cheers :)

Sunday, 8 June 2014

Android accessing html control inside Java class| Getting html field value inside android activity class

Hello Friends,
                This is my another android tutorial. In this android demo I am going to
cover following parts:

1. Showing Android Login form in web view or loading html file in web view.
2. Getting the control  of log in button click,user name and password value inside
    our java class.
3. Checking the field validation inside  our java code.
4. Calling web service method based on valid user name and password.





Source Code:

1. Login.html :  This is my html file in which there is two edittext and a login button.
                           When I m clicking on login Button  I am checking the value of both
this text field inside my java class and if it is valid   then I am calling my login service
url.


<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
  function showAndroidToast() {
   var name = document.getElementById("loginName").value;
   var password = document.getElementById("password").value;
   Android.showMyToast(name,password);
  }
   </script>

</head>
<body>
 <section class="container">
  <div class="login">
   <h1>Login to Android Developer Solutions</h1>
   <form>
    <p>
     <input type="text" name="login" id="loginName" value=""
      placeholder="Username or Email">
    </p>
    <p>
     <input type="password" name="password" id="password" value=""
      placeholder="Password">
    </p>
    <p class="remember_me">
     <label> <input type="checkbox" name="remember_me"
      id="remember_me"> Remember me
     </label>
    </p>
    <p class="submit">
     <input type="submit" name="commit" value="Login"
      onClick="showAndroidToast()">
    </p>
   </form>
  </div>

  <div class="login-help">
   <p>
    Forgot your password? <a href="index.html">Click here to reset
     it</a>.
   </p>
  </div>
 </section>

 <section class="about">
  <p class="about-author">
   &copy; 2013&ndash;2014 <a
    href="http://www.androiddevelopersolutions.com/" target="_blank">Android
    Developer Solution</a><br> By <a
    href="http://www.androiddevelopersolutions.com/" target="_blank">Mukesh
    Y</a>
 </section>

</body>
</html>


2. MainActivity.java

package com.mukesh.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

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

  WebView webView = (WebView) findViewById(R.id.webview);

  WebSettings webSettings = webView.getSettings();
  webSettings.setJavaScriptEnabled(true);
  webView.addJavascriptInterface(new WebAppInterface(this), "Android");
  webView.loadUrl("file:///android_asset/index.html");
 }

}


Download Code : WebView Demo

Enjoy Codiing....
Cheers :)

Wednesday, 4 June 2014

Android Google Map V2 | Android Draw Polygon

Hello Friends,
                               This is my small tutorial on google map v2. This blogs covers
following point:

1. Start Drawing on Google Map | Draw geometry on Google map
2. Clear drawing | Clear polygon
3. Close Polygon
4. Save Geometry

Screen 1:  Click on start drawing button and starting drawing geometry or polygon
                 or polyline.


 Screen2: Click on close polygon button which close the polygon.




Here is my code:

1. MainActivity.java  


/*
 * Copyright (C) 2014 Mukesh Y authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package info.androiddeveloper.googlemapsv2;

import java.util.ArrayList;

import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.GeoPoint;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;

/**
 * @author Mukesh Y
 */
public class MainActivity extends Activity implements OnMapClickListener {

 // Google Map
 private GoogleMap googleMap;
 ArrayList latLang = new ArrayList();
 ArrayList listPoints = new ArrayList();
 boolean isGeometryClosed = false;
 Polygon polygon;
 Context context = MainActivity.this;
 boolean isStartGeometry = false;

 @SuppressLint("NewApi")
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  try {
   initilizeMap();
   ActionBar actionBar = this.getActionBar();
   actionBar.setDisplayHomeAsUpEnabled(true);
   actionBar.setDisplayShowCustomEnabled(true);
   actionBar.setDisplayShowTitleEnabled(true);
   actionBar.setIcon(R.drawable.ic_launcher);
  } catch (Exception e) {
  }
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater menuInflater = getMenuInflater();
  menuInflater.inflate(R.menu.map_menu, menu);
  return super.onCreateOptionsMenu(menu);
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

  switch (item.getItemId()) {
  case R.id.action_normal:
   googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
   return true;

  case R.id.action_hybrid:
   googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
   return true;

  case R.id.action_satellite:
   googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
   return true;
  
  default:
   return super.onOptionsItemSelected(item);
  }
 }

 /**
  * function to load map. If map is not created it will create it for you
  * */
 private void initilizeMap() {
  if (googleMap == null) {

   googleMap = ((MapFragment) getFragmentManager().findFragmentById(
     R.id.map)).getMap();

   // check if map is created successfully or not
   if (googleMap == null) {
    Toast.makeText(this, "Sorry! unable to create maps",
      Toast.LENGTH_SHORT).show();
    return;
   }

   googleMap.getUiSettings().setMyLocationButtonEnabled(true);
   // set my location
   googleMap.setMyLocationEnabled(true);
   googleMap.getUiSettings().setCompassEnabled(false);
   googleMap.getUiSettings().setRotateGesturesEnabled(false);
   // set zooming controll
   googleMap.getUiSettings().setZoomControlsEnabled(true);
   googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
   googleMap.setOnMapClickListener(this);
  }

 }

 public void Draw_Map() {
  PolygonOptions rectOptions = new PolygonOptions();
  rectOptions.addAll(latLang);
  rectOptions.strokeColor(Color.BLUE);
  rectOptions.fillColor(Color.CYAN);
  rectOptions.strokeWidth(7);
  polygon = googleMap.addPolygon(rectOptions);
 }

 @Override
 protected void onResume() {
  super.onResume();

 }

 /**
  * Close the Polygon / join last point to first point
  * 
  * @param view
  */
 public void closePolygon(View view) {
  if (latLang.size() > 0) {
   Draw_Map();
   isGeometryClosed = true;
   isStartGeometry = false;
  }
 }

 /**
  * Close the Polygon / join last point to first point
  * 
  * @param view
  */
 public void startDrawing(View view) {
  isStartGeometry = true;
 }

 @Override
 public void onMapClick(LatLng latlan) {
  if (!isGeometryClosed && isStartGeometry) {
   latLang.add(latlan);
   GeoPoint point = new GeoPoint(latlan.latitude, latlan.longitude);
   listPoints.add((IGeoPoint) point);
   MarkerOptions marker = new MarkerOptions().position(latlan);
   googleMap.addMarker(marker);
   if (latLang.size() > 1) {
    PolylineOptions polyLine = new PolylineOptions().color(
      Color.BLUE).width((float) 7.0);
    polyLine.add(latlan);
    LatLng previousPoint = latLang.get(latLang.size() - 2);
    polyLine.add(previousPoint);
    googleMap.addPolyline(polyLine);
   }
  }
 }

 /**
  * Clear the all draw lines
  * 
  * @param view
  *            Current view of activity
  */
 public void clearCanvas(View view) {

  try {
   AlertDialog.Builder alertdalogBuilder = new AlertDialog.Builder(
     context);

   alertdalogBuilder.setTitle("Clear");
   alertdalogBuilder
     .setMessage(
       "Do you really want to clear the geometry? This action can't be undone!")
     .setCancelable(false)
     .setPositiveButton("Yes",
       new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
          int id) {
         // polygon.remove();
         googleMap.clear();
         latLang = new ArrayList();
         listPoints = new ArrayList();
         isGeometryClosed = false;
        }
       })
     .setNegativeButton("No",
       new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
          int which) {
         dialog.cancel();
        }
       });

   // Create Alert Dialog
   AlertDialog alertdialog = alertdalogBuilder.create();
   // show the alert dialog
   alertdialog.show();

  } catch (Exception e) {
  }

 }

 /**
  * Method for Save Property
  * 
  * @param view
  */
 public void savePolygon(View view) {
  try {
   if (isGeometryClosed) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
      context);
    alertDialogBuilder.setTitle("Save");
    alertDialogBuilder
      .setMessage(
        "Do you really want to save? This action can't be undone!")
      .setCancelable(false)
      .setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,
           int id) {
          // if this button is clicked, close
          // current activity
          // Prop.this.finish();
          savePolygonAfterAlert();
         }
        })
      .setNegativeButton("No",
        new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,
           int id) {
          // if this button is clicked, just close
          // the dialog box and do nothing
          dialog.cancel();
         }
        });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
   } else {
    showDialog(context, "Alert", "Close geometry before saving");
   }
  } catch (Exception e) {

  }

 }

 /**
  * Save the Polygon made by user
  * 
  * @param view
  */

 public void savePolygonAfterAlert() {
  // save geometry of polygon
 }

 /**
  * Method to show the Dialog box
  * 
  * @param ctx
  * @param title
  * @param msg
  */
 public void showDialog(Context ctx, String title, String msg) {
  AlertDialog.Builder dialog = new AlertDialog.Builder(ctx);
  dialog.setTitle(title).setMessage(msg).setCancelable(true);
  dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
   }
  });
  AlertDialog alertDialog = dialog.create();
  alertDialog.show();
 }
}

Download Complete Code : GoogleMapV2

Enjoy Coding .....   cheers :)

Saturday, 31 May 2014

Track your android device | Android device manager | Protect Personal Information and Data

Hello Friends,
              Today, I am sharing my another tutorial with the help of which we can easily
Track our android phone . This is one of the best feature in android.

Feature :
- We can track the location of our phone
- With the help of this we can easily track our lost|stolen phone
- We can easily erase the data of our phone
- We can make call or ring on our phone using device manager
- Protect Personal Information and Data

You just need to Setup or Register your phone with Android Device Manager.
Here are the steps:

1. Plugged your phone with your system via usb cable.
2. Go to Android Device Manager  It ask you log in with you your G mail Account.
3. Then Android Device Manger setup Screen comes, Click on Accept . Refere below
    screen shot:


4. Then Its shows you your phone current location or Last updated location(f it lost|stolen)
    on map with date and time.

5. There will be two button a) Ring and b) Set up Lock & Erase.
    When you click on Ring button It make a call on your phone and where ever is your
     phone, It start ringing with full volume for 5 minutes.





5) b. The most and Important i.e Set up Lock & Erase, to use this feature  click on
         the icon, it will ask you for send an setup notification on your phone.


The above step sends an Security Activation Policy notification of Android
device manager to your phone. After clicking on "Activate" its show you two
options 1.Remotely Locate this device 2. Allow remote locate and erase
select both option. Refer the below screen shot:



Note: step 5(b) is important , so don't forgot to do the setup.

For  more information refer this link 

Enjoy... :)


Monday, 19 May 2014

Android Error: Unable to add window — token null is not for an application

Hello Friends,
                 most of us facing the issue of  Unable to add window — token null
while calling alert dialog from our service class.

As, I am using activity class not the fragment so I am using getApplicationContext()
(as from service we face context issue so instead of using "this" am using
application context) for creating "AlertDialog.Builder" but still facing the issue
while calling dialog.show.

android.view.WindowManager$BadTokenException:
  Unable to add window -- token null is not for an application
    at android.view.ViewRoot.setView(ViewRoot.java:509)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
    at android.app.Dialog.show(Dialog.java:241)

Here is my code:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
     getApplicationContext());
//ok and cancel button code
...........
...........
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Then after searching a lot I found the solution, I made following few changes in my
code and Its worked for me.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
     getApplicationContext());
//ok and cancel button code
...........
...........
AlertDialog alertDialog = alertDialogBuilder.create();
/*
* Window token null exception, when trying to show alert dialog from
* service class.use alertDialog.getWindow() for getting window and
* add permission in manifest
*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.
    TYPE_SYSTEM_ALERT);
alertDialog.show();

Also need to add following permission in your manifest file

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


Hope this will helps some one.
Enjoy coding... cheers :)

Android Block App | Android blacklist few application

Hello Friends,
               Today, I am sharing my another tutorial. Actually I want to blacklist
some application from my android application.So, that whenever user try to open
facebook,whatsapp,youtube and any other app, my app prevent them and it
ask user to enter the admin for accessing that app.

I go through many tutorial and android forum and found that they are doing by
making phone as "rooted device" or by installiing some 3rd party application
for eg:AppLock.

But, I don't want any 3rd party app and also don't want to make my device as rooted.
As this app is not for my personal use and making device as rooted is not good idea,
because, its have lots of side effects.

After doing lots of R&D I found an way to achieve this. I used android service which
running in background and monitoring the launcher app.


Here is my code:

1.ServiceDemoActivity.java

package com.android.services;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ServiceDemoActivity extends Activity {

 TextView notification;
 Button stop;
 Context ctx = ServiceDemoActivity.this;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  notification = (TextView) findViewById(R.id.notification);
  if (Helper.CheckIfServiceIsRunning(ctx)) {
   notification.setText("Continuation of last started service");
  } else {
   notification.setText("Service started now only");
   startService(new Intent(this, MyService.class));
  }

  stop = (Button) findViewById(R.id.stop);

  stop.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    if (Helper.CheckIfServiceIsRunning(ctx)) {
     ctx.stopService(new Intent(ctx, MyService.class));
     notification
       .setText("Service stopped - to start the          service go out and come inside the application");
        LocalBroadcastManager.getInstance(ctx).unregisterReceiver(
       broadcastReceiver);
    }
   }
  });
 }

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
  // blockApp();
  System.out.print("-------testing----------");
  Toast.makeText(getApplicationContext(), "Installing any app",
     Toast.LENGTH_LONG).show();
  }
 };

 @Override
 public void onResume() {
  super.onResume();
  LocalBroadcastManager.getInstance(this)
    .registerReceiver(broadcastReceiver,
      new IntentFilter(MyService.BROADCAST_ACTION));
 }

 @Override
 public void onPause() {
  super.onPause();
  // unregisterReceiver(broadcastReceiver);
 }

}

2.Helper.java
package com.android.services;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class Helper extends Application {

 public Helper() {
  // TODO Auto-generated constructor stub
 }

 private static Context context;

 public void onCreate() {
  super.onCreate();
  Helper.context = getApplicationContext();
 }

public static void showMessage(Context ctx, String msg) {
 Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
 toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 580);
  toast.show();

}
public static BroadcastReceiver locationBroadcastReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
  Log.d("======Service is called", "true");
 }
};

public static boolean CheckIfServiceIsRunning(Context ctx) {
 // If the service is running in background
 ActivityManager manager = (ActivityManager) ctx
   .getSystemService(ACTIVITY_SERVICE);
 for (RunningServiceInfo service : manager
   .getRunningServices(Integer.MAX_VALUE)) {
  if ("com.android.services.MyService".equals(service.service
    .getClassName())) {
   return true;
  }
 }
return false;
}

public static void stop(Context ctx) {
 try {
  if (CheckIfServiceIsRunning(ctx)) {
   ctx.stopService(new Intent(ctx, MyService.class));
   // unregisterReceiver(locationBroadcastReceiver);
   LocalBroadcastManager.getInstance(ctx).unregisterReceiver     Helper.locationBroadcastReceiver);
  }
 } catch (Exception ex) {
 }
}
}


4. AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.services"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <activity
            android:name="com.android.services.ServiceDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       <service
            android:name="com.android.services.MyService"
            android:enabled="true" />
       <receiver
            android:name="com.android.services.Receiver"
            android:enabled="true" >
       </receiver>
    </application>
</manifest>


Download code from here
Hope this will helps some one.
Enjoy coding....
cheers :)

Wednesday, 14 May 2014

Android blink textview in different colors

Hello Friends,

ValueAnimator colorAnim = ObjectAnimator.ofInt(textView, "textColor", 0xffFF8080, 0xff8080FF);
colorAnim.setDuration(500);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();


For blinking textview background color replace below code
ValueAnimator colorAnim = ObjectAnimator.ofInt(textView, "backgroundColor", 0xffFF8080, 0xff8080FF);

Sunday, 30 March 2014

Android action bar item test case using Robotium

Hello friends,
                  This is my small tutorial on Android test driven development using Robotium
Today, I am going to share the code which helps you in writing the testcase for
action bar menu item selection.

Here is the complete video  for your reference:

Here is my code:

1. MainActivityTest.java


/*
 * Copyright (C) 2014 Mukesh Y authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.actionbar;

import android.R.integer;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.actionbarsherlock.view.SubMenu;

/**
 * @author Mukesh Y
 */
public class MainActivity extends SherlockActivity implements
  OnMenuItemClickListener {

 private SubMenu mSortItem;
 private MenuItem mMapItem;
 private int MAP_ID = 101;
 private int SORT_ID = 102;

 CharSequence selected = "Light";
 TextView mTextView;

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

  mTextView = (TextView)findViewById(R.id.theme);
  ActionBar ab = getSupportActionBar();
  ab.setBackgroundDrawable(getApplicationContext().getResources()
    .getDrawable(R.drawable.bg_titlebar_tile));
  ab.setDisplayShowTitleEnabled(true);
  mTextView.setText(selected);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {

  mSortItem = menu.addSubMenu(0,SORT_ID,0,selected);
  mSortItem.setIcon(R.drawable.ic_menu_sort);
  
  mSortItem.getItem().setShowAsAction(
    MenuItem.SHOW_AS_ACTION_IF_ROOM
      | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
  mMapItem = menu.add(0, MAP_ID, 0, "map");
  mMapItem.setIcon(R.drawable.google_maps_icon_pressed)
    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

  getMenuState("Light");
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  
  if (item.getItemId()==mMapItem.getItemId()) {
   Intent mapIntent = new Intent(this, Map.class);
   startActivity(mapIntent);
  } else {

  }
  return true;
 }

 @Override
 public boolean onMenuItemClick(MenuItem item) {
  mSortItem.clear();
  getMenuState(item.getTitle());
  return false;
 }

 public void getMenuState(CharSequence selected) {
  mTextView.setText(selected);
  if (selected.equals("Default")) {
   mSortItem.add(0, R.style.Theme_Sherlock, 0, "Default")
     .setIcon(android.R.drawable.checkbox_on_background)
     .setOnMenuItemClickListener(this);
   mSortItem.add(0, R.style.Theme_Sherlock_Light, 0, "Light")
     .setIcon(android.R.drawable.checkbox_off_background)
     .setOnMenuItemClickListener(this);
   mSortItem.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0, "Light (Dark Action Bar)")
     .setIcon(android.R.drawable.checkbox_off_background)
     .setOnMenuItemClickListener(this);
   
   setTheme(R.style.Theme_Sherlock);
  } else if (selected.equals("Light")) {
   mSortItem.add(0, R.style.Theme_Sherlock, 0, "Default")
     .setIcon(android.R.drawable.checkbox_off_background)
     .setOnMenuItemClickListener(this);
   mSortItem.add(0, R.style.Theme_Sherlock_Light, 0, "Light")
     .setIcon(android.R.drawable.checkbox_on_background)
     .setOnMenuItemClickListener(this);
   mSortItem.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0, "Light (Dark Action Bar)")
     .setIcon(android.R.drawable.checkbox_off_background)
     .setOnMenuItemClickListener(this);
   setTheme(R.style.Theme_Sherlock_Light);
  } else {
   mSortItem.add("Default")
     .setIcon(android.R.drawable.checkbox_off_background)
     .setOnMenuItemClickListener(this);
   mSortItem.add(0, R.style.Theme_Sherlock_Light, 0, "Light")
     .setIcon(android.R.drawable.checkbox_off_background)
     .setOnMenuItemClickListener(this);
   mSortItem.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0, "Light (Dark Action Bar)")
     .setIcon(android.R.drawable.checkbox_on_background)
     .setOnMenuItemClickListener(this);
   setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
  }

 }
}


2. AllTests.java
/*
 * Copyright (C) 2014 Mukesh Y authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.robotium.actionbartest;

import junit.framework.TestSuite;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;

/**
 * @author Mukesh Y
 */
public class AllTests extends  ActivityInstrumentationTestCase2 {
 
 

 public AllTests(Class activityClass) {
  super(activityClass);
 }

 public static TestSuite suite() {
  TestSuite t = new TestSuite();
  t.addTestSuite(MainActivityTest.class);
  t.addTestSuite(MapActivityTest.class);
  
  return t; 
 }
 
 @Override
 public void setUp() throws Exception {
  
 }
 
 
 @Override
 public void tearDown() throws Exception {
 }

}


Download Code From Here
Enjoy Coding...  :)

Tuesday, 25 March 2014

Android Google TV Setup | Android Google TV Development -Part 1


Hello Friends,
                 Hello android Guys as we as we Google launches three new
future last moth
Android | Google awesome features :
1. Android L Developer Preview
2. Android Wear SDK
3. Android TV Preview SDK
4. Google glass

                 Here, I am going to share my first android blog on Google TV.This blog  helps you in making Android Google TV app.
The Google TV developers released a Google TV add-on for the Android SDK which helps android developer in creating the Android Google TV Application easily.

Steps:

1.Installing the Add-On for Google TV :
        a) Open the Sdk manager
        b) Expand Api level-13 or Android 3.2 and  check, there will be
             "Google TV Addon"
        c) select it and click on install. See below image for help
        d) Also Install the "Intel Atom x86 System Image" which is 
             available in under Android 2.3.3 and Android 3.2.
 


2. Creating the  "Google TV Emulator " for running and testing the app:
      1, Open AVD manager
      2.  Select "Device Definitions" tab from top
      3.  Create an "New Device"

     Note : 
            -For 1080p use a resolution of 1920×1080 and a density of xhdpi.
            -For 720p use a resolution of 1080×720 with a density of tvdpi.       

   

        4. Now Create Google TV Emulator :
           


           Note: You may also face the following issue while creating the Google TV AVD
               1.   Install the Intel x86 System Image
               2.   Hax is not working and emulator runs in emulation mode

   
    Refer link : https://developers.google.com/tv/android/docs/gtv_addon


    Hope, this will helps some one.
    Enjoy Coding..  Cheers...   :)

Thursday, 20 March 2014

Creating and Storing Log File on device in Android


Hello Friends,
        Today, I am sharing another android tutorial which helps you in Creating
and Storing Log File in your android phone.


1. MainActivity.java
package com.example.logfileimplementation;

import java.io.File;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 public static final String SDCARD = String.valueOf(Environment
   .getExternalStorageDirectory());
 TextView mTextView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
  deleteLog();
  setContentView(R.layout.activity_main);
  createAppDirectories();
  mTextView = (TextView) findViewById(R.id.action_settings);
  mTextView.setText("Android crash Reporter");
  } catch(Exception ex) {
   Utilities.writeIntoLog(Log.getStackTraceString(ex));
  }
 }

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

 // Creating App Directory For Log File
 private void createAppDirectories() {
  System.out.println("hiii");
  File dir1 = new File(Utilities.APP_DIR);
  if (!dir1.exists()) {
   dir1.mkdir();
  }
 }

 // Deleting App Directory which is used for Log File
 private void deleteLog() {

  File log = new File(Utilities.LOG_FILE_PATH);
  if (log.exists()) {
   log.delete();
  }
 }
}

2. Utilities.java
package com.example.logfileimplementation;

import java.io.BufferedWriter;
import java.io.FileWriter;


public class Utilities {
 public static String APP_DIR = MainActivity.SDCARD+"/Logfile";
 public static String LOG_FILE_PATH = APP_DIR+"/ myapp_log.txt";  
 
 
 
 public static void writeIntoLog(String data) 
 {
   
  FileWriter fw = null;    
  try {
   
   fw = new FileWriter(LOG_FILE_PATH , true);
   BufferedWriter buffer = new BufferedWriter(fw);   
   buffer.append(data+"\n");
    
   buffer.close();

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

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

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >



    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />

  

</RelativeLayout>
4. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.logfileimplementation"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

</manifest>
Hope this will help you.
Enjoy Coding. Cheers.... :)

Tuesday, 18 March 2014

"Collect preferences failed" eclipse ADT error | You may have an "No repository found error"


Hello Droid Guys,
                           After updating the sdk manager to latest sdk i.e version 22.6.
           


I am start getting following error: 
[2014-03-18 13:12:03 - Framework Resource Parser] Collect preferences failed, class java/lang/AutoCloseable not found in D:\Android-Eclipse\Eclipse and ADT\android-sdk\platforms\android-19\android.jar

Then I found the solution by updating the Eclipse ADT plugin.
1. go Help | Install New Sofware
2. select "Android Developer Tools Update Site - http://dl-ssl.google.com/android/eclipse/"
3. press "Select All"
4. press "Finish"

Note : While doing above steps I faced other issue i.e:
    You may have an "No repository found error" while installing the tools.

Then I do following tweak I removed the http://dl-ssl.google.com/android/eclipse/ site and then re-added it, then everything downloaded fine.

Hope, this will helps some one.
Enjoy Coding :)


Thursday, 13 March 2014

Android Robotium Test -run robotium tests in a specific order

Hello Friends,
                         This is very common scenario when you are running any testsuits. It
by default runs in alphabetical order. I too faces the same problem while writing the
test case using Robotium.

In my case I want to execute the testcase in following order :
MainLoginScreenTest -> EmailSignUpScreenTest -> EmailLoginScreenTest

But it actually runs in alphabetical order like,
 EmailLoginScreenTest -> EmailSignUpScreenTest - > MainLoginScreenTest

Then I follow this link and find the way to come out from this problem. Here is
my code.

1. AllTests.java
package com.android.test;
import junit.framework.TestSuite;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;

public class AllTests extends 
        ActivityInstrumentationTestCase2<Activity>{
 
 public AllTests(Class activityClass) {
  super(activityClass);
 }

 public static TestSuite suite() {
  TestSuite t = new TestSuite();
  t.addTestSuite(MainLoginScreenTest.class);
  t.addTestSuite(EmailSignUpScreenTest.class);
  t.addTestSuite(EmailLoginScreenTest.class);
  
  return t; 
 }
 
 @Override
 public void setUp() throws Exception {
  
 }
 
 
 @Override
 public void tearDown() throws Exception {
 }

}


2.MainLoginScreenTest.java

package com.android.test;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.ImageButton;

import com.android.Login.EmailSignUpScreen;
import com.android.Login.MainLoginScreen;
import com.android.android.R;
import com.robotium.solo.Solo;

public class MainLoginScreenTest extends
          ActivityInstrumentationTestCase2<MainLoginScreen> {
 
 private Solo solo;
 private Activity activity;
 
 public MainLoginScreenTest() {
  super(MainLoginScreen.class);
  // TODO Auto-generated constructor stub
 }
 
 @Override
 public void setUp() throws Exception {
  //setUp() is run before a test case is started. 
  //This is where the solo object is created.
  this.activity = this.getActivity();
  this.solo = new Solo(getInstrumentation(), this.activity);
 }
 
 
 @Override
 public void tearDown() throws Exception {
       solo.finishOpenedActivities();
 }

 public void testDisplay() throws Exception {
   solo.waitForActivity(MainLoginScreen.class);
   ImageButton emailLogin = (ImageButton) this.solo.getView(R.id.btn_email_login);
   assertEquals(emailLogin.getId(), R.id.btn_email_login);
   this.solo.clickOnImageButton(1);
   this.solo.waitForActivity(EmailSignUpScreen.class, 1000);
   assertEquals(EmailSignUpScreen.class, solo.getCurrentActivity().getClass());
   //this.solo.goBack();
 }
}


3.EmailSignUpScreenTest.java

package com.android.test;

import junit.framework.Test;
import junit.framework.TestSuite;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.MediumTest;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.android.Login.EmailLoginScreen;
import com.android.Login.EmailSignUpScreen;
import com.android.android.R;
import com.robotium.solo.Solo;

public class EmailSignUpScreenTest extends 
           ActivityInstrumentationTestCase2<EmailSignupScreen>{

 private Solo solo;
 private Activity activity;
 
 public EmailSignUpScreenTest() {
  super(EmailSignUpScreen.class);
 }
 public EmailSignUpScreenTest(String name) {
  super(EmailSignUpScreen.class);
  setName(name);
 }
 
 public static final Test suite(  ) {
   TestSuite suite = new TestSuite();
   suite.addTest(new TestSuite(EmailSignUpScreen.class));
   suite.addTest(new TestSuite(EmailLoginScreen.class));
   return suite;
   }

 @Override
 public void setUp() throws Exception {
  //setUp() is run before a test case is started. 
  //This is where the solo object is created.
  this.activity = this.getActivity();
  this.solo = new Solo(getInstrumentation(), this.activity);
 }
 
 @Override
 public void tearDown() throws Exception {
       solo.finishOpenedActivities();
 }

 public void testDisplay() throws Exception {
  String fName = "Sam";
  String lName = "Joshi";
  String email = "sam@gmail.com";
  String password = "abc123";
  String dob = "03-11-2014";
  String zipcod = "201301";
    
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_first_name), fName);
  //this.solo.enterText((EditText) this.activity.findViewById(R.id.edt_last_name), lName);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_email), email);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_password), password);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_confirm_password), password);
  this.solo.enterText((EditText) this.activity.findViewById(R.id.edt_birth_date), dob);
  RadioButton rb = (RadioButton) solo.getView(R.id.rb_female);
  solo.clickOnView(rb);
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_zip_code), zipcod);
  //Click on the button named "Sign up".
  this.solo.clickOnButton("Sign Up");
  //this.solo.w
  //Check to see if the given text is displayed.
  //assertTrue(this.solo.searchText(text));
 }
 
 @MediumTest
 public void testStartEmailLoginScreen() throws Exception {     
   this.solo.waitForActivity(EmailSignUpScreen.class); 
   TextView tvSignIn = (TextView) this.activity.findViewById(R.id.sign_in_label);
   String text = tvSignIn.getText().toString();
   this.solo.waitForText(text);
   this.solo.clickOnText(text);
   this.solo.waitForActivity(EmailLoginScreen.class, 1000);
   assertTrue(solo.waitForActivity(EmailLoginScreen.class));
 }
}

4.EmailLoginScreenTest.java
package com.android.test;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.EditText;

import com.android.Login.EmailLoginScreen;
import com.android.android.R;
import com.robotium.solo.Solo;

public class EmailLoginScreenTest extends
        ActivityInstrumentationTestCase2<EmailLoginScreen>{

 private Solo solo;
 private Activity activity;
 
 public EmailLoginScreenTest() {
  super(EmailLoginScreen.class);
 }

 @Override
 public void setUp() throws Exception {
  //setUp() is run before a test case is started. 
  //This is where the solo object is created.
  this.activity = this.getActivity();
  this.solo = new Solo(getInstrumentation(), this.activity);
 }
 
 
 @Override
 public void tearDown() throws Exception {
       solo.finishOpenedActivities();
 }

 public void testDisplay() throws Exception {
  String email = "mukesh@gmail.com";
  String password = "abc123";
  
  
  this.solo.typeText((EditText) this.activity.findViewById(R.id.edt_login_email), email);
  //this.solo.enterText((EditText) this.activity.findViewById(R.id.edt_login_password), password);
  //Click on the button named "Sign up".
  this.solo.clickOnButton("Login");
  this.solo.waitForActivity(EmailLoginScreen.class, 2000);
  //Check to see if the given text is displayed.
  //assertTrue(this.solo.searchText(text));
 }
}


Note: Right click on AllTests.java and choose Run As-> Android Junit test ->
               select AllTests>java file.

Hope this post is helpful for some one.
Enjoy Coding......  :)

Friday, 7 March 2014

java.lang.RuntimeException: Stub! in Robolectric


Hello Droid Friends,
                              Have you facing following error while running a test case using
Roboelectric and Junit-4.

java.lang.RuntimeException: Stub!
at android.content.Context.<init>(Context.java:4)
at android.content.ContextWrapper.<init>(ContextWrapper.java:5)
at android.view.ContextThemeWrapper.<init>(ContextThemeWrapper.java:5)
at android.app.Activity.<init>(Activity.java:6)
at com.actionbarsherlock.app.SherlockActivity.<init>(SherlockActivity.java:21)
at com.opttown.OptTown.DrawerBaseActivity.<init>(DrawerBaseActivity.java:34)
at com.opttown.Places.MyPlaces.<init>(MyPlaces.java:63)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.fest.reflect.constructor.Invoker.newInstance(Invoker.java:77)
at org.robolectric.util.ActivityController.<init>(ActivityController.java:47)
at org.robolectric.Robolectric.buildActivity(Robolectric.java:1409)
at com.opttown.test.MyPlacesTest.setUp(MyPlacesTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)


Most of stub!  exceptions are because the tests are not annotated with the correct TestRunner. For example in my case I forgot to add:
@RunWith(RobolectricTestRunner.class)

After adding the above annotation the above issue will be fixed.


import static org.junit.Assert.assertNotNull;
import static org.robolectric.Robolectric.shadowOf;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity;

import android.content.Context;

import com.android.Places.MyPlaces;

@RunWith(RobolectricTestRunner.class)
public class MyPlacesTest {
 
 private MyPlaces activity;
 Context ctx;
 ShadowActivity shadowActivity;
 
 @Before
 public void setUp() throws Exception {
  activity = Robolectric.buildActivity(MyPlaces.class)
                .create()
                .get();
  shadowActivity = shadowOf(activity);
  ctx = activity;
 }
 
 /**
   * @testdox: for activity instance test 
   * given: 
   * when:  app launch
   * then: checking the instance of activity
   */
  @Test
  @Config(reportSdk = 10)
  public void testActivityInstance() {
   assertNotNull(shadowActivity.getApplicationContext());
   Assert.assertEquals("Result",activity.getApplicationContext(),sh                       adowActivity.getApplicationContext());
  }



Hope this will help you during writing the test case for your android project.



Enjoy Coding... :) 

You may also Read this:
1. Roboelectric setup with eclipse
2. R
oboelectric AndroidManifest.xml not found error
3. Roboelectric tutorial
4. Asserting Toast message using Robolectric
.

 

Copyright @ 2013 Android Developer Blog.