26 August 2015

Add phonegap (cordova) Applaud plugin for android to eclipse adt

You do not have to write commands to make your phonegap (cordova) application, you can use this plugin to directly create your phonegap application with a single click.

What we will do?
-> We will install Applaud plugin in eclipse so that you can create your phonegap application with just a click.

What we need?
  • Eclipse with ADT
  • Internet connection
  • Emulator of API 12 or above
Step 1 : Start your Eclipse. Go to Help->Install New Software from the menu-bar.
help installnewsoftware

Step 2 : Click on Add. Give Name as MDS Applaud and Location as shown below.
http://svn.codespot.com/a/eclipselabs.org/mobile-web-development-with-phonegap/tags/r1.2.9/download

Then click OK.
Applaud name and location

Step 3 : Tick on MDS Applaud and press Next.
mds next

Step 4 : Click Next
next

Step 5 : Click on "I Agree.." and click Finish.
agree finish

Step 6 : Check the progress in the Progress Bar. Then Restart Eclipse.
install progress
After restarting eclipse you will see the plugin on the toolbar.
applaud plugin

Stay Tuned with Made In Android

Published By:
Yatin Kode
on 26.8.15

12 August 2015

Track SeekBar Progress in Android

What we will do ?
-> We will build a Seekbar in our application. A Toast will be used to get the value of the seekbar.

What we will need ?
  • SeekBar in activity_main.xml
  • MainActivity.java
Step 1 : Create a new application. Go to File->New->Android Application Project.
File New Android Project

Step 2 : Give a name to your application (SeekBarDemo) and package name (com.mia.seekbardemo).Click Next continuously.
seekbardemo mia
Click Finish.
finish

Step 3 : Drag SeekBar from Palette->Form Widgets in activity_main layout.
drag seekbar from palette
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="com.mia.seekbardemo.MainActivity" >


    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
        />
</RelativeLayout>

Step 4 : Open MainActivity.java from src->com.mia.seeekbardemo in Project Explorer and copy-paste the code shown below.

MainActivity.java
package com.mia.seekbardemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final SeekBar seek = (SeekBar) findViewById(R.id.seekBar1);
        
        seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
         
         int change = 0;
   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    change=progress;  
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub 
   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    Toast.makeText(MainActivity.this, Integer.toString(change), Toast.LENGTH_SHORT).show();
   }    
        });        
        }
    }

Step 5 : Run the application.
seekbar output

Explanation of the code :

Explanation from MainActivity.java :
  • We make a variable of class SeekBar named seek using findViewById() method which connects it to the widget in activity_main.xml with id as seekBar1.
final SeekBar seek = (SeekBar) findViewById(R.id.seekBar1);
seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {      
         int change = 0;
  • Inside onProgressChanged() we give the value of progress variable defined by default in the method parameters to our variable change.
public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    change=progress;  
   }
  • Inside method onStopTrackingTouch() we define what should be done after touch action is carried out. We display a Toast with the value of change or progress which varies from 0 to 100 by default.
public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    Toast.makeText(MainActivity.this, Integer.toString(change), Toast.LENGTH_SHORT).show();
   }   
Github download
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 12.8.15

4 August 2015

Making Intents in Listview

We will learn to navigate to a new page by clicking on list item. I will consider a Custom List from the one of the previous post.

What we will do?
-> We will make a list with some items. When we click on a list-item we will traverse to a specific page.

What we will need?
  • activity_jaguar.xml (newly added)
  • MainActivity.java (changes required)
  • Jaguar.java (newly added)
  • AndroidManifest.xml (changes required)
Note : we will edit the project from one of the previous post of Custom List.

Step 1 : Add a android xml file in res->layout folder and name it as activity_jaguar.xml. Right Click on layout->New->Android XML Layout.

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Jaguar's business was founded as the Swallow Sidecar Company in 1922, originally making motorcycle sidecars before developing bodies for passenger cars." />

</LinearLayout>

Step 2 : Add a class under src->com.mia.customlistdemo folder by  name it as Jaguar.java. Right Click on com.mia.customlistdemo under src->New->Class

Jaguar.java
package com.mia.customlistdemo;

import android.app.Activity;
import android.os.Bundle;

public class Jaguar extends Activity{
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_jaguar);
 }
}
The Project Skeleton is shown as below:

Step 3 : Go to MainActivity.java from the previous post. Remove the toast at the end lines and replace it with Intents. Right now I will connect only the second list item(Jaguar) with one page (Jaguar.java), the other list items will return a toast as before.
The modified MainActivity.java is shown below
package com.mia.customlistdemo;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
  
   //ArrayList thats going to hold the search results
          ArrayList<HashMap<String, Object>> searchResults;

   //ArrayList that will hold the original Data
          ArrayList<HashMap<String, Object>> originalValues;
   LayoutInflater inflater;
 @Override
   public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
   
  setContentView(R.layout.activity_main);
  final EditText searchBox=(EditText) findViewById(R.id.searchBox);
  ListView playersListView=(ListView) findViewById(android.R.id.list);
  
  //get the LayoutInflater for inflating the customomView
  //this will be used in the custom adapter
  inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  
  //these arrays are just the data that 
  //I'll be using to populate the ArrayList
  //You can use our own methods to get the data
  String names[]={"FIESTA","XJ","BOXSTER"}; 
  
  String teams[]={"Ford","Jaguar","Porsche"};
  Integer[] photos={R.drawable.picford,R.drawable.picjaguar,R.drawable.picporsche};
         originalValues=new ArrayList<HashMap<String,Object>>();
         
         //temporary HashMap for populating the 
  //Items in the ListView
  HashMap<String , Object> temp;
  
  //total number of rows in the ListView
  int noOfPlayers=names.length;
  
  //now populate the ArrayList players
  for(int i=0;i<noOfPlayers;i++)
  {
   temp=new HashMap<String, Object>();
  
   temp.put("name", names[i]);
   temp.put("team", teams[i]);    
   temp.put("photo", photos[i]);
  
   //add the row to the ArrayList
   originalValues.add(temp);        
  }
  //searchResults=OriginalValues initially
  searchResults=new ArrayList<HashMap<String,Object>>(originalValues);
  
  //create the adapter
  //first param-the context
  //second param-the id of the layout file 
  //you will be using to fill a row
  //third param-the set of values that
  //will populate the ListView
  final CustomAdapter adapter=new CustomAdapter(this, R.layout.activity_item,searchResults); 
  
  //finally,set the adapter to the default ListView
  playersListView.setAdapter(adapter);
  searchBox.addTextChangedListener(new TextWatcher() {
  
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    //get the text in the EditText
    String searchString=searchBox.getText().toString();
    int textLength=searchString.length();
    searchResults.clear();
  
           for(int i=0;i<originalValues.size();i++)
    {
   String playerName=originalValues.get(i).get("name").toString();
          if(textLength<=playerName.length()){
   //compare the String in EditText with Names in the ArrayList
     if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
     searchResults.add(originalValues.get(i));
   }}
    adapter.notifyDataSetChanged();
  }
  
  public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {}
    
  public void afterTextChanged(Editable s) {}
   });
  }
  
  //define your custom adapter
  private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>>
  {
   public CustomAdapter(Context context, int textViewResourceId,
     ArrayList<HashMap<String, Object>> Strings) {
  
    //let android do the initializing :)
    super(context, textViewResourceId, Strings);
   }
  
   //class for caching the views in a row  
   private class ViewHolder
   {
    ImageView photo;
    TextView name,team;
   }
  
   ViewHolder viewHolder;
  
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
  
    if(convertView==null)
    {
     convertView=inflater.inflate(R.layout.activity_item, null);
     viewHolder=new ViewHolder();
  
      //cache the views
      viewHolder.photo=(ImageView) convertView.findViewById(R.id.photo);
      viewHolder.name=(TextView) convertView.findViewById(R.id.name);
      viewHolder.team=(TextView) convertView.findViewById(R.id.team);
  
       //link the cached views to the convertview
       convertView.setTag(viewHolder);
    }
    else
     viewHolder=(ViewHolder) convertView.getTag();
    int photoId=(Integer) searchResults.get(position).get("photo");
  
    //set the data to be displayed
    viewHolder.photo.setImageDrawable(getResources().getDrawable(photoId));
    viewHolder.name.setText(searchResults.get(position).get("name").toString());
    viewHolder.team.setText(searchResults.get(position).get("team").toString());
    //return the view to be displayed
    return convertView;
   }
  }
  protected void onListItemClick(ListView l, View v, int position, long id) {
   // TODO Auto-generated method stub
   super.onListItemClick(l, v, position, id);
   String str = searchResults.get(position).get("name").toString();
   try{
    if(str=="XJ"){
     Class jClass = Class.forName("com.mia.customlistdemo.Jaguar");
     Intent jIntent = new Intent(this, jClass);
     startActivity(jIntent);
     }
    if(str=="FIESTA"){
     Toast.makeText(getApplicationContext(), "FIESTA\nFORD", Toast.LENGTH_SHORT).show();
    }
    if(str=="BOXSTER"){
     Toast.makeText(getApplicationContext(), "BOXSTER\nPORSCHE", Toast.LENGTH_SHORT).show();
    }
   }
    catch(Exception e){
     e.printStackTrace();
    }
   
}
}
MainActivity.java



Step 4 : Open AndroidManifest.xml and add activity of Jaguar class as shown below.

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

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity
            android:name=".Jaguar"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

Step 5 : Run the Project.

Explanation of the code :

Explanation from MainActivity.java :
  • At line 162 we have made a variable jClass of type Class and stored location of Jaguar Class there.
  • Then we made use of Intent to reference this(MainActivity) class with Jaguar class.
Explanation from AndroidManifest.xml :
  • We have just added a new Activity of Jaguar class.

Stay Tuned with Made In Android

Published By:
Yatin Kode
on 4.8.15

25 July 2015

Make your own Android Notification

What we will do?
-> We will make an app with a button. When the button is pressed we will get a notification.

What we will need?
  • activity_main.xml
  • MainActivity.java
Step 1 : Create a new android application. Click on File->New->Android Application Project.
file new android app

Step 2 : Give the name as NotificationDemo and package name as com.mia.notificationdemo. Click Next continuously.
NotificationDemo mia
Click Finish.
click finish

Step 2 : Add a button in activity_main.xml and change its name to any name(Notification).
drag button
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification"
      android:id="@+id/button"
      android:layout_marginTop="77dp"
      android:layout_below="@+id/editText3"
      android:layout_alignRight="@+id/textView"
      android:layout_alignEnd="@+id/textView" />

</RelativeLayout>

Step 3 : The code for MainActivity.java is shown below.

MainActivity.java
package com.mia.notificationdemo;


import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

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

Button b1=(Button)findViewById(R.id.button);
   
     b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         
           NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
           Notification notify=new Notification(R.drawable.ic_launcher,"Title",System.currentTimeMillis());
           PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
           notify.setLatestEventInfo(getApplicationContext(),"Subject","Body",pending);
           notif.notify(0, notify);
        }
     });
}
}

Step 4 : Run the application.
notification output 1
notofication output 2

Explanation of the code :

Explanation from MainActivity.java :
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  • Then we define the Notification object notify with icon,title and time of the notification. The title is not actually displayed in the notification. It is just used as a unique name to the notification.
Notification notify=new Notification(R.drawable.ic_launcher,"Title",System.currentTimeMillis());
  • Then we use object of type PendingIntent named pending. PendingIntent is used when we launch another Intent(of the notification) after an action in our main Intent(Intent of MainActivity class).
PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
  • The method getActivity() here creates a new Intent(for notification).
  • After that we use setLatestEventInfo() method to set the information in the latest notification. Here, in this example, the time is only changed and other parameters like head, body remains same.
notify.setLatestEventInfo(getApplicationContext(),"Subject","Body",pending);
  • At last we display the notification by calling the notify() method.
notif.notify(0, notify);

Github download
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 25.7.15

17 July 2015

Make a Gesture based android application

What we will do?
-> We will make an application which will close the app as we draw a big 'C' on the screen.

What we will need?
  • Emulator of android v1.3 or above with sdcard
  • gesture app in the emulator(present by default)
  • MainActivity.java (java class)
  • activity_main.xml (xml layout)
Step 1 : Create a new android application. Click on File ->New->Android Application Project.
file new android application

Step 2 : Give a name to your application as GestureDemo and package name as com.mia.gesturedemo. Then click Next continuously.
GestureDemo mia
Click Finish
finish

Step 3 : Code for activity_main.xml is given below.

 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.gesture.GestureOverlayView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:eventsInterceptionEnabled="true"
android:gestureStrokeType="multiple"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make a 'C' to close" />
</android.gesture.GestureOverlayView>

Step 4 : Make a new folder named raw in res folder. Right-click on res->New->Folder.
res new folder raw

Step 5 : Open Android Virtual device Manager. Make a new Emulator or edit the previous emulator include sd card and give a size to it(any size). Click on OK.Then click Start.
new emulator with sd card

Step 6 : After you have started the emulator, click on Gestures Builder App.
Gestures Builder

Step 7 : Click on Add Gesture. Give a name to the gesture (close) and draw the gesture roughly (C) below it as shown in the screenshot.
add gesture


Step 8 : Click Done and you will see the name with the gesture as shown below.You can add other types of gestures too. Do not close the emulator.
gesture added

Step 9 : From the eclipse on the top right corner you will see the DDMS option, click on it. If not found, click on Open Perspective button on the left of Java,

9.a) There you will find DDMS.
9.b) Click on the emulator on left hand side.
9.c) Then click on File Explorer Tab as shown below.
9.d) You will find the gestures file in storage->sdcard->LOST_DIR folder. Click on it.
9.e) Now click on disk like icon on the top besides System Information(circled in red).
DDMS File Explorer storage

Step 10 : Go to the path of raw folder of your project. Then click Save.
path of raw folder

Step 11 : Refresh your project and you will see gestures file in raw folder in the Project Explorer.
gestures in raw folder

Step 12 : Add the below code in MainActivity.java.

MainActivity.java
package com.mia.gesturedemo;

import java.util.ArrayList;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.os.Bundle;

public class MainActivity extends Activity implements OnGesturePerformedListener {
GestureLibrary mLibrary;
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
  if (!mLibrary.load()) {
    finish();
   }
  GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
  gestures.addOnGesturePerformedListener(this);
}

public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
  ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
  if (predictions.size() > 0 && predictions.get(0).score > 1.0) {
    String result = predictions.get(0).name;
    if ("close".equalsIgnoreCase(result)) {
      finish();
    }
  }
}
}

Step 13 : Run your application.


Explanation of the code :

Explanation from MainActivity.java :
  • First we load the gestures made by the Gesture Builder application in mLibrary variable of type GestureLibrary. By putting an if condition we check if the gesture file exists or not. If it does not exist we will stop the application by using close() method.
mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);
   if (!mLibrary.load()) {
     finish();
   }
  • Now we make gestures variable of type GestureOverlayView which is used to make the screen ready for gestures. We will call gestures by using addOnGesturePerformedListener() method.
GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this);
  • Now the method onGesturePerformed() is used to perform operation on particular gesture. The ArrayList predictions hold the name of the gestures and gesture itself defined in gesture file.
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
  ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
  • Now we compare String "close" to name of element in predictions. If it is equal then we close the application using close().
if ("close".equalsIgnoreCase(result)) {
      finish();
   }
  • You can add other gestures by defining new gestures in Gesture Builder app and adding them in MainActivity class as else if condition below close option.
Github download
Stay tuned with Made In Android

Published By:
Yatin Kode
on 17.7.15

7 July 2015

Upload Android Source Code to Github (continued....)

Continued from previous post

Step 12 : The Red exclamation (!) will be removed. Right-click on Project choose Team->Commit.
team commit

Step 13 : Write initial commit as message. Select All and click Commit and Push.
select all, commit and push

Step 14 : Copy the url of Github repository created in Step 4 in the URL box. Enter UserName and Password of GitHub Account and click Next.
Copy the url of Github repository created in Step 4 in the URL box. Enter UserName and Password of GitHub Account and click Next.

Step 15 : Click on Add All Branches Spec and click Next.
Add all Branches Spec ,Next

Step 16 : Verify Repository Name and click Finish. Wait till uploading process takes place.
click Finish

Step 17 : Click OK.
OK

Step 18 : Refresh the webpage shown in Step 4. You will see your project as below.
refresh browser
Stay Tuned with Made In Android

Published By:
Yatin Kode
on 7.7.15

Previous Page Next Page Home
Top