Tag Archives: Android Tutorial

Android Global Variables/Application Context Variable

In this example we are going to learn to define variables in application context and we can use this variables as a Global variable. We can set values in this variables  and get values on any activity / broadcast recieiver / service in application context(environment).

The challenge is how to save values across several Activities and all parts of your application context. We can achieve this by creating static variable but it is not a good way as it will causes memory leaks. The solution for this in Android is to associate your variable with the Application context.

Every Application has a context, and Android guarantees that Application context will exist as a instance across your application.

The way to do this is to create a class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. We can get object of our class on any activity / broadcast reciever / service in application context(environment) by Context.getApplicationContext() method.

Now lets create a project to understand variables under Application Context:-

Create a class named AuthenticationDetails.java and extent it with ‘Application’ our custom class should be subclass of android.app.Application class. We will use this class as global class for your Application environment(Conext).

AuthenticationDetails.java

package com.coreprogrammers.model;

import android.app.Application;

public class AuthenticationDetails extends Application
{
	private String id;
	private String name;
	private String company;
	private String username;
	private String password;
	private String s3_key;
	private String s3_secret;
	private String api_key;
	private String license;
	private String timezone;
	private String tied_to;
	private String app;
	private String paypal;
	private String cron;
	private String cron_ares;
	private String send_rate;
	private String language;
	private String cron_csv;
	private String login_in;

	public void setid(String strid) 
	{
		this.id = strid;
	}

	public String getid() 
	{
		return id;
	}

	public void setname(String strname) 
	{
		this.name = strname;
	}

	public String getname() 
	{
		return name;
	}

	public void setcompany(String strcompany) 
	{
		this.company = strcompany;
	}

	public String getcompany() 
	{
		return company;
	}

	public void setusername(String strusername) 
	{
		this.username = strusername;
	}

	public String getusername() 
	{
		return username;
	}

	public void setpassword(String strpassword) 
	{
		this.password = strpassword;
	}

	public String getpassword() 
	{
		return password;
	}

	public void sets3_key(String strs3_key) 
	{
		this.s3_key = strs3_key;
	}

	public String gets3_key() 
	{
		return s3_key;
	}

	public void sets3_secret(String strs3_secret) 
	{
		this.s3_secret = strs3_secret;
	}

	public String gets3_secret() 
	{
		return s3_secret;
	}

	public void setapi_key(String strapi_key) 
	{
		this.api_key = strapi_key;
	}

	public String getapi_key() 
	{
		return api_key;
	}

	public void setlicense(String strlicense) 
	{
		this.license = strlicense;
	}

	public String getlicense() 
	{
		return license;
	}

	public void settimezone(String strtimezone) 
	{
		this.timezone = strtimezone;
	}

	public String gettimezone() 
	{
		return timezone;
	}

	public void settied_to(String strtied_to) 
	{
		this.tied_to = strtied_to;
	}

	public String gettied_to() 
	{
		return tied_to;
	}

	public void setapp(String strapp) 
	{
		this.app = strapp;
	}

	public String getapp() 
	{
		return app;
	}

	public void setpaypal(String strpaypal) 
	{
		this.paypal = strpaypal;
	}

	public String getpaypal() 
	{
		return paypal;
	}

	public void setcron(String strcron) 
	{
		this.cron = strcron;
	}

	public String getcron() 
	{
		return cron;
	}

	public void setcron_ares(String strcron_ares) 
	{
		this.cron_ares = strcron_ares;
	}

	public String getcron_ares() 
	{
		return cron_ares;
	}

	public void setsend_rate(String strsend_rate) 
	{
		this.send_rate = strsend_rate;
	}

	public String getsend_rate() 
	{
		return send_rate;
	}

	public void setlanguage(String strlanguage) 
	{
		this.language = strlanguage;
	}

	public String getlanguage() 
	{
		return language;
	}

	public void setcron_csv(String strcron_csv) 
	{
		this.cron_csv = strcron_csv;
	}

	public String getcron_csv() 
	{
		return cron_csv;
	}

	public void setlogin_in(String strlogin_in) 
	{
		this.login_in = strlogin_in;
	}

	public String getlogin_in() 
	{
		return login_in;
	}	
}

 

Now We are going to create  AndroidManifest.xml.

In AndroidManifest file we will Assign AuthenticationDetails.java in application tag, see this line in application tag android:name=”com.coreprogrammers.model.AuthenticationDetails” . After assign we can get AuthenticationDetails.java instance on any activity / broadcast reciever / service in application context.

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

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

    <application
        android:name="com.coreprogrammers.model.AuthenticationDetails"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coreprogrammers.model.FirstScreen"
            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="com.coreprogrammers.model.SecondScreen" ></activity>  
        <activity android:name="com.coreprogrammers.model.ThirdScreen" ></activity>
    </application>

</manifest>

Now we will show how to use the global variables across three activities

1) FirstScreen.java

getApplicationContext() method of Context will give AuthenticationDetails.java instance and set id/name values and maintain state of AuthenticationDetails.java instance.

package com.coreprogrammers.model;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;

public class FirstScreen extends Activity 
{

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

        final Button secondBtn = (Button) findViewById(R.id.second);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        //Set name and id in global/application context
        _objAuthenticationDetails.setname("Coreprogrammers");
        _objAuthenticationDetails.setid("Rocks");

        secondBtn.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
                Intent i = new Intent(getBaseContext(), SecondScreen.class);
                startActivity(i);
            }
        }); 
    }   
}

 

2) SecondScreen.java

We have to Call getApplicationContext() method of Context and get AuthenticationDetails.java instance , By AuthenticationDetails.java instance we can get set values for name/id variables.

package com.coreprogrammers.model;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreen extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondscreen); 

        TextView showGlobal = (TextView) findViewById(R.id.showGlobal);
        final Button thirdBtn = (Button) findViewById(R.id.third);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        // Get name and id from global/application context
        final String name  = _objAuthenticationDetails.getname();
        final String id = _objAuthenticationDetails.getid();

        String showString = "Name= : "+ name + "ID : "+ id;

        // Show name/email values in TextView
        showGlobal.setText(showString);

        thirdBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v) 
            {
                Intent i = new Intent(getBaseContext(), ThirdScreen.class);
                startActivity(i);
            }
        });

    } 

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
    }
}

 

3) ThirdScreen.java

Now we will call getApplicationContext() method of Context and get AuthenticationDetails.java instance , By AuthenticationDetails.java instance we can get and set values for name/id variables.

package com.coreprogrammers.model;

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

public class ThirdScreen extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thirdscreen); 

        TextView showGlobal = (TextView) findViewById(R.id.showGlobal);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        // Get name and email from global/application context
        final String name  = _objAuthenticationDetails.getname();
        final String id = _objAuthenticationDetails.getid();

        String showString = "Name= "+ name +" "+ "ID= "+ id;

        // Show name/id values in TextView
        showGlobal.setText(showString);

    } 
}

Happy Programming :-)

 

Android Fragments Part-3 (Adding a user interface)

A fragment is usually used as part of an activity’s user interface and contributes its own layout to the activity.

To provide a layout for a fragment, we must implement the onCreateView() callback method, which the Android system calls when it’s time for the fragment to draw its layout. Our implementation of this method must return a View  that is the root of our fragment’s layout.

Note: If the fragment is a subclass of ListFragment, the default implementation returns a ListView from onCreateView(), so we don’t need to implement it.

To return a layout from onCreateView(), we can inflate it from a layout resource defined in XML. To help you do so, onCreateView() provides a LayoutInflater object.

For example, here’s a subclass of Fragment that loads a layout from the fragment_example.xml file:-

public static class FragmentExample extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_example, container, false);
    }
}

How to Create a layout

In the sample above,R.layout.fragment_example is a reference to a layout resource named fragment_example.xml saved in the application resources.

Explanation:-

The container parameter passed to onCreateView() is the parent ViewGroup (from the activity’s layout) in which your fragment layout will be inserted. The savedInstanceState parameter is a Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed .

The inflate() method takes three arguments:

  • The resource ID of the layout you want to inflate.
  • The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it’s going.
  • A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation. (In this case, this is false because the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout.)

Now we’ve seen how to create a fragment that provides a layout. Next, we now need to add the fragment to our activity. We will learn to add the fragment to the activity in our next Tutorial  Android Fragments Part-4

Android Fragments Part-1

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities).

A fragment must always be embedded in an activity and the fragment’s lifecycle is directly affected by the host activity’s lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that’s managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.

When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.

This document describes how to build your application to use fragments, including how fragments can maintain their state when added to the activity’s back stack, share events with the activity and other fragments in the activity, contribute to the activity’s action bar, and more.

 

Fragment Design

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet’s screen is much larger than that of a handset, there’s more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity’s appearance at runtime and preserve those changes in a back stack that’s managed by the activity.

For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity, side by side, and each fragment has its own set of lifecycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity, as illustrated in the tablet layout in figure 1.

You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when more than one cannot fit within the same activity.

fragments    This Figure shows an example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.

Fragment Life-Cycle

fragment_lifecycle

The life-cycle of a fragment is connected to the life-cycle of its hosting activity.

To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you’re converting an existing Android application to use fragments, you might simply move code from your activity’s callback methods into the respective callback methods of your fragment.

Usually, you should implement at least the following lifecycle methods:

onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.
onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

Most applications should implement at least these three methods for every fragment, but there are several other callback methods you should also use to handle various stages of the fragment lifecycle. We will discuss more about Fragments in our Next(Android Fragments Part-2) Tutorial.

 

Happy Programming :-)

 

 

Android Rating Bar Example

In this tutorial we can use “android.widget.RatingBar” to display rating bar component in stars icon. The user is able to touch, drag or click on the stars to set the rating value easily.

In this tutorial, we show you how to use XML to display a rating bar, few textviews and a button. When user click on the rating bar’s star, the selected rating value will be displayed in the textview. And, if user clicks on the button, the selected rating value will be displayed as a floating message (toast message).

Note:  This project is developed in Eclipse 3.7.2, and tested with Android 2.3.3.

1. Rating Bar

Open “res/layout/main.xml” file, add a rating bar component, few textviews and a button.

res/layout/main.xml :-

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

    <TextView android:id="@+id/lblRateMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rate Me"
        android:textAppearance="?android:attr/textAppearanceMedium" />  

    <RatingBar android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="4"
        android:stepSize="1.0"
        android:rating="1.0" />

    <Button android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

    <LinearLayout android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView android:id="@+id/lblResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Result : "
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView android:id="@+id/txtRatingValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceSmall" />

    </LinearLayout>

</LinearLayout>

 

2. Java Code

Inside activity “onCreate()” method, attach a listener on rating bar, fire when rating value is changed. Another listener on button, fire when button is clicked. Read the code’s comment, it should be self-explanatory.

RatingBarExampleActivity.Java

package com.CoreProgrammers.RatingBarExample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class RatingBarExampleActivity extends Activity {

	private RatingBar ratingBar;
	private TextView txtRatingValue;
	private Button btnSubmit;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        addListenerOnRatingBar();
		addListenerOnButton();

    }

    public void addListenerOnRatingBar() {

		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		txtRatingValue = (TextView) findViewById(R.id.txtRatingValue);

		//if rating is changed,
		//display the current rating value in the result (textview) automatically
		ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {

				txtRatingValue.setText(String.valueOf(rating));

			}
		});
	}

    public void addListenerOnButton() {

		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		btnSubmit = (Button) findViewById(R.id.btnSubmit);

		//if click on me, then display the current rating value.
		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Toast.makeText(RatingBarExampleActivity.this,
						String.valueOf(ratingBar.getRating()),
						Toast.LENGTH_SHORT).show();

			}

		});

	}
}

 

package com.CoreProgrammers.RatingBarExample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class RatingBarExampleActivity extends Activity {

	private RatingBar ratingBar;
	private TextView txtRatingValue;
	private Button btnSubmit;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        addListenerOnRatingBar();
		addListenerOnButton();

    }

    public void addListenerOnRatingBar() {

		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		txtRatingValue = (TextView) findViewById(R.id.txtRatingValue);

		//if rating is changed,
		//display the current rating value in the result (textview) automatically
		ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {

				txtRatingValue.setText(String.valueOf(rating));

			}
		});
	}

    public void addListenerOnButton() {

		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		btnSubmit = (Button) findViewById(R.id.btnSubmit);

		//if click on me, then display the current rating value.
		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Toast.makeText(RatingBarExampleActivity.this,
						String.valueOf(ratingBar.getRating()),
						Toast.LENGTH_SHORT).show();

			}

		});

	}
}

 

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".RatingBarExampleActivity"
            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>

 

3. Running Demo

Run the application.

1. Result, 1st star is selected by default. 

Screen Shot 2014-03-31 at 10.31.54 PM

 

 

2. Touch on the 4th star, rating value is changed, display the current selected value in the result (textview).

Screen Shot 2014-03-31 at 10.32.32 PM

 

3. Now click on the submit button, the current selected value is displayed as floating message.

Screen Shot 2014-03-31 at 10.34.01 PM

 

 

Happy Programming :-)

 

 

 

 

Android Debug Bridge (adb) – Tutorial

Using the adb tools with Android

This tutorial describes how to use the adb tool to access your Android device or Android virtual device (AVD).

1. Android Debugging Bridge – adb

We can access our Android device via the adb command on the command line.  An Android virtual device can be freely accessed, a normal Android phone needs to get rooted, For Example: you need to remove the protection to do everything on this device.

The adb tools is located in the [android-sdks]/platform-tools directory. You should add this directory to your path to have direct access to this command.

The adb allows you to send commands to your Android device, pull and push files to it, gives shell access to the Android device and allows you to read information from your device, for example the current memory usage. The following chapter describe the usage of the corresponding commands.

If you have several devices running you can issue commands to run on one individual device.

Command For Listing all devices :-
adb devices

Result Will Be Like:-

List of devices attached
emulator-5554 attached
emulator-5555 attached
Issue a command to a specific device
adb -s emulator-5554 shell

2. Shell access via adb

We can get shell access to your Android device via the following command.

adb shell

 This will connect you to your device and give you Linux command line access to the underlying file system, e.g. ls, rm, , cd, mkdir, etc. The application data is stored in the directory “/data/data/package_of_your_app”.

3. Copy files from and to your device

We can copy a file from and to the device via the following commands.

 

// assume the task file exists on your Android device
adb pull /sdcard/task ~/test
// now copy it back
adb push ~/test/task /sdcard/task2

 

 4. Install an .apk file from command prompt

We can use the code below to install application from command line

adb install MyExample.apk

this apk is installed in the internal memory of current opened emulator.

 

For installing  apk  in the sd-card of current opened emulator, Following syntax should be used:-

adb install -s example.apk

 

We can install an apk to a specific device/emulator by entering the device/emulator identifier before the keyword ‘install’ and then the path to the apk. Note that the -s switch, if any, after the ‘install’ keyword signifies installing to the sd card. Example: 

adb -s emulator-5554 install myapp.apk

 Also we can put it anywhere on our system, just specify the path as part of your command line: 

C:\android-sdk\platform-tools> adb -s emulator-5554 install C:\Users\Me\Desktop\myapp.apk

 

5. Uninstall an application via adb

We can uninstall an android application via the shell. Switch the data/app directory (cd /data/app) and simply delete your android application.

We can also uninstall an app via adb with the package name.

adb uninstall <packagename>

For Example:-
adb uninstall com.google.zxing.client.android

Another way of Delete / Remove Android Applications deployed on Emulator

First, make sure the emulator is running. Then follow below steps:

1. Go to the tools directory in command prompt – c:\>android\tools
2. Type adb shell
3. #cd /data/app (this takes you to the folder where all apk files are installed)
4. #ls (It will display all the .apk installed in your emulator)
5. #rm ***.apk (which you want to remove, all apk files)
6.#exit (exits from the adb shell)

 

How to add home widget feature in android app

In This Tutorial we will going to learn How to add home widget feature in android app:-

Home screen widgets are a great feature of android operating system. By adding widgets to your application, you provide extra satisfaction to the user because the user need not launch the application and can access app features directly from the home screen of his device.

First of all we will create “demo_widget_provider.xml” file in res->xml Folder which will be the Widget Provider –

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" 
    android:initialLayout="@layout/widget_demo" 
    android:minHeight="146dp" 
    android:minWidth="146dp"
    android:updatePeriodMillis="1000000" 
    >
</appwidget-provider>

Now Following is the XML Layout File for the demo- widget_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5sp"
    android:background="@android:drawable/alert_dark_frame" >

    <ImageView
        android:id="@+id/widget_image"
        android:layout_width="110sp"
        android:layout_height="110sp"
        android:layout_gravity="center"
        android:src="@drawable/me" />

    <Button
        android:id="@+id/widget_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Change it!" />

</LinearLayout>

 

Java Code:-

MyWidgetIntentReceiver.java

import com.example.homewidgetexample.R;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class MyWidgetIntentReceiver extends BroadcastReceiver {

	public static int clickCount = 0;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(intent.getAction().equals("pl.looksok.intent.action.CHANGE_PICTURE")){
			updateWidgetPictureAndButtonListener(context);
		}

	}

	private void updateWidgetPictureAndButtonListener(Context context) {
		// TODO Auto-generated method stub
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo);
		remoteViews.setImageViewResource(R.id.widget_image, getImageToSet());

		remoteViews.setOnClickPendingIntent(R.id.widget_button, MyWidgetProvider.buildButtonPendingIntent(context));
		MyWidgetProvider.pushWidgetUpdate(context, remoteViews);

	}

	private int getImageToSet() {
		// TODO Auto-generated method stub
		clickCount ++;
		return clickCount % 2 == 0 ? R.drawable.me : R.drawable.wordpress_icon;
	}

}

 

MyWidgetProvider.java

import com.example.homewidgetexample.R;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class MyWidgetProvider extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// TODO Auto-generated method stub
		// super.onUpdate(context, appWidgetManager, appWidgetIds);
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_demo);
		remoteViews.setOnClickPendingIntent(R.id.widget_button,
				buildButtonPendingIntent(context));
		pushWidgetUpdate(context, remoteViews);

	}

	public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
		// TODO Auto-generated method stub
		ComponentName myWidget = new ComponentName(context,
				MyWidgetProvider.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		manager.updateAppWidget(myWidget, remoteViews);

	}

	public static PendingIntent buildButtonPendingIntent(Context context) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setAction("pl.looksok.intent.action.CHANGE_PIECTURE");

		return PendingIntent.getBroadcast(context, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);
	}

}

 

Androidmanifest.xml file

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name="MyWidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/demo_widget_provider" />
        </receiver>
        <receiver
            android:name="MyWidgetIntentReceiver"
            android:label="widgetBroadcastReceiver" >
            <intent-filter>
                <action android:name="pl.looksok.intent.action.CHANGE_PICTURE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/demo_widget_provider" />
        </receiver>
    </application>

</manifest>

 

Android Drag and Drop

Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. The framework includes following three important components to support drag & drop functionality:

  • Drag event class:
  • Drag listeners:
  • Helper methods and classes:

The Drag/Drop Process

There are basically four steps or states in the drag and drop process:

  • Started: This event occurs when you start dragging an item in a layout, your application callsstartDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.

    To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.

  • Continuing: The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object’s appearance in response to the event or can react by highlighting its View.The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.
  • Dropped: The user releases the dragged item within the bounding box of a View. The system sends the View object’s listener a drag event with action type ACTION_DROP.
  • Ended: Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.

The DragEvent Class

The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process.

CONSTANTS

Following are all constants integers available as a part of DragEvent class.

S.N. Constants & Description
1 ACTION_DRAG_STARTED
Signals the start of a drag and drop operation.
2 ACTION_DRAG_ENTERED
Signals to a View that the drag point has entered the bounding box of the View.
3 ACTION_DRAG_LOCATION
Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object’s bounding box.
4 ACTION_DRAG_EXITED
Signals that the user has moved the drag shadow outside the bounding box of the View.
5 ACTION_DROP
Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.
6 ACTION_DRAG_ENDED
Signals to a View that the drag and drop operation has concluded.

METHODS

Following are few important and most frequently used methods available as a part of DragEvent class.

S.N. Constants & Description
1 int getAction()
Inspect the action value of this event..
2 ClipData getClipData()
Returns the ClipData object sent to the system as part of the call to startDrag().
3 ClipDescription getClipDescription()
Returns the ClipDescription object contained in the ClipData.
4 boolean getResult()
Returns an indication of the result of the drag and drop operation.
5 float getX()
Gets the X coordinate of the drag point.
6 float getY()
Gets the Y coordinate of the drag point.
7 String toString()
Returns a string representation of this DragEvent object.

Listening for Drag Event

If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true.

The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android.

Starting a Drag Event

You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipDataobject, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object.

Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that’s the same size as the View argument passed to it, with the touch point centered in the drag shadow.

Example

Following example shows the functionality of a simple Drag & Drop using aView.setOnLongClickListener() event listener along with View.OnDragEventListener().

Step Description
1 You will use Eclipse IDE to create an Android application and name it as DragNDropDemounder a package com.example.dragndropdemo. While creating this project, make sure youTarget SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the logo image used in the example.
3 Copy image logo.png in res/drawable-* folders. You can use images with different resolution in case you want to provide them for different devices.
4 Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.

Following is the content of the modified main activity filesrc/com.example.dragndropdemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.

 
package com.example.coreprogrammers.dragndrop;

import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.widget.*;

public class MainActivity extends Activity{
   ImageView ima;
   private static final String IMAGEVIEW_TAG = "Android Logo";
   String msg;

   private android.widget.RelativeLayout.LayoutParams layoutParams;

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

      ima = (ImageView)findViewById(R.id.iv_logo);
      // Sets the tag
      ima.setTag(IMAGEVIEW_TAG);

      ima.setOnLongClickListener(new View.OnLongClickListener() {
         @Override
         public boolean onLongClick(View v) {
            ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

            String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
            ClipData dragData = new ClipData(v.getTag().toString(), 
            mimeTypes, item);

            // Instantiates the drag shadow builder.
            View.DragShadowBuilder myShadow = new DragShadowBuilder(ima);

            // Starts the drag
            v.startDrag(dragData,  // the data to be dragged
            myShadow,  // the drag shadow builder
            null,      // no need to use local data
            0          // flags (not currently used, set to 0)
            );
            return true;
         }
      });

      // Create and set the drag event listener for the View
      ima.setOnDragListener( new OnDragListener(){
         @Override
         public boolean onDrag(View v,  DragEvent event){
         switch(event.getAction())                   
         {
            case DragEvent.ACTION_DRAG_STARTED:
               layoutParams = (RelativeLayout.LayoutParams) 
               v.getLayoutParams();
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
               // Do nothing
               break;
            case DragEvent.ACTION_DRAG_ENTERED:
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
               int x_cord = (int) event.getX();
               int y_cord = (int) event.getY();  
               break;
            case DragEvent.ACTION_DRAG_EXITED :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               layoutParams.leftMargin = x_cord;
               layoutParams.topMargin = y_cord;
               v.setLayoutParams(layoutParams);
               break;
            case DragEvent.ACTION_DRAG_LOCATION  :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
               x_cord = (int) event.getX();
               y_cord = (int) event.getY();
               break;
            case DragEvent.ACTION_DRAG_ENDED   :
               Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
               // Do nothing
               break;
            case DragEvent.ACTION_DROP:
               Log.d(msg, "ACTION_DROP event");
               // Do nothing
               break;
            default: break;
            }
            return true;
         }
      });
   }
}

Following will be the content of res/layout/activity_main.xml file:-

 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
		android:id="@+id/iv_logo" 
    	android:layout_width="wrap_content" 
    	android:layout_height="wrap_content"
    	android:src="@drawable/logo"
    	android:contentDescription="@string/drag_drop"  />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants:-

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

    <string name="app_name">DragNDropDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="drag_drop">Click on the image to drag and drop</string>

</resources>

Following is the default content of AndroidManifest.xml:-

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

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

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

Let’s try to run your DragNDropDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project’s activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

android_drag_and_drop

Now do long click on the displayed android logo and you will see that logo image moves a little after 1 seconds long click from its place, its the time when you should start dragging the image. You can drag it around the screen and drop it at a new location.

android_drag_and_drop2

HAPPY PROGRAMMING :-)

Skip to toolbar