Android - Access Web Services Using the GET Method

Next »
Network (181/474)
« Previous

Access Web Services Using the GET Method

Description

To Access Web Services Using the GET Method involves the following steps:

  • download XML files
  • parse the contents

Example

The following code shows how to Access Web Services Using the GET Method.

Add the following statement to the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout xml file

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

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*w  w w . j a v  a  2s  .co m*/
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends Activity {
    ImageView img;

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    private String WordDefinition(String word) {
        InputStream in = null;
        String strDefinition = "";
        try {
            in = OpenHttpConnection("http://your server.com/query?word=" + word);
            Document doc = null;
            DocumentBuilderFactory dbf =
                    DocumentBuilderFactory.newInstance();
            DocumentBuilder db;
            try {
                db = dbf.newDocumentBuilder();
                doc = db.parse(in);
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            doc.getDocumentElement().normalize();

            //---retrieve all the <Definition> elements---
            NodeList definitionElements =
                    doc.getElementsByTagName("Definition");

            //---iterate through each <Definition> elements---
            for (int i = 0; i < definitionElements.getLength(); i++) {
                Node itemNode = definitionElements.item(i);
                if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
                    //---convert the Definition node into an Element---
                    Element definitionElement = (Element) itemNode;

                }
            }
        } catch (IOException e1) {
            Log.d("NetworkingActivity", e1.getLocalizedMessage());
        }
        //---return the definitions of the word---
        return strDefinition;
    }

    private class AccessWebServiceTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return WordDefinition(urls[0]);
        }

        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
        }
    }

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

        //---access a Web Service using GET---
        new AccessWebServiceTask().execute("apple");
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Activity life cycle

Activity (56/474)
« Previous

Activity life cycle

Description

The Activity base class defines a series of events that govern the life cycle of an activity.

The life cycle of an Android application is strictly managed by the system.

Android runs each application in a separate process, each of which hosts its own virtual machine.

The Activity class defines the following events:

  • onCreate() is called when the activity is first created
  • onStart() is called when the activity becomes visible to the user
  • onResume() is called when the activity starts interacting with the user
  • onPause() is called when the current activity is being paused and the previous activity is being resumed
  • onStop() is called when the activity is no longer visible to the user
  • onDestroy() is called before the activity is destroyed by the system
  • onRestart() is called when the activity has been stopped and is restarting again

You do not need to react to all of these methods.

Example

package com.java2s.app;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
//w  w  w  . jav a2  s .  c  o  m
public class MainActivity extends Activity {
    String tag = "java2s.com";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(tag, "In the onCreate() event");
    }

    public void onStart()
    {
        super.onStart();
        Log.d(tag, "In the onStart() event");
    }

    public void onRestart()
    {
        super.onRestart();
        Log.d(tag, "In the onRestart() event");
    }

    public void onResume()
    {
        super.onResume();
        Log.d(tag, "In the onResume() event");
    }

    public void onPause()
    {
        super.onPause();
        Log.d(tag, "In the onPause() event");
    }

    public void onStop()
    {
        super.onStop();
        Log.d(tag, "In the onStop() event");
    }

    public void onDestroy()
    {
        super.onDestroy();
        Log.d(tag, "In the onDestroy() event");
    }
}
Activity life cycle

Note

When an activity is created for the first time, the onCreate() method is called.

We can use onCreate() method to create the UI elements.

An activity is destroyed when you click the Back button. You need to write additional code in your activity to preserve its state when it is destroyed.

The onPause() method is called when an activity is sent to the background, as well as when it is killed when the user presses the Back button.

When an activity is started, the onStart() and onResume() methods are always called, regardless of whether the activity is restored from the background or newly created.

We should use the onCreate() method to create and instantiate the objects that you will be using in your application.

We should use the onResume() method to start any services or code that needs to run while your activity is in the foreground.

We should use the onPause() method to stop any services or code that does not need to run when your activity is not in the foreground.

We should use the onDestroy() method to free up resources before your activity is destroyed.

If an application has only one activity and the activity is killed, the application will still be running in memory.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Activity User Event

Activity (72/474)
« Previous

Activity User Event

Description

Users interact with your UI at two levels:

  • the activity level and
  • the view level.

At the activity level, the Activity class exposes methods that you can override.

Some common methods that you can override in your activities include the following:

  • onKeyDown - Called when a key was pressed and not handled by any of the views contained within the activity
  • onKeyUp - Called when a key was released and not handled by any of the views contained within the activity
  • onMenuItemSelected - Called when a panel's menu item has been selected by the user
  • onMenuOpened - Called when a panel's menu is opened by the user

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Adapt To Display Orientation

Activity (59/474)
« Previous

Adapt To Display Orientation

Description

Android supports two screen orientations: portrait and landscape.

By default, when you change the display orientation of your Android device, the current activity that is displayed automatically redraws its content in the new orientation.

onCreate() method of the activity is fired whenever there is a change in display orientation.

When you change the orientation of your Android device, your current activity is actually destroyed and then recreated.

In general, you can employ two techniques to handle changes in screen orientation:

  • Anchor views to the four edges of the screen. When the screen orientation changes, the views can anchor neatly to the edges.
  • Resize and reposition each and every view according to the current screen orientation.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add Action Items to the Action Bar

Action Bar (230/474)
« Previous

Add Action Items to the Action Bar

Description

You can display additional items on the Action Bar. These additional items are called action items. Action items are shortcuts to some of the commonly performed operations in your application.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/* w  ww .  ja va 2  s.c  om*/

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice(item);
    }

    private void CreateMenu(Menu menu)
    {
        MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
        {
            mnu1.setIcon(R.drawable.ic_launcher);
            mnu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
        {
            mnu2.setIcon(R.drawable.ic_launcher);
            mnu2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
        {
            mnu3.setIcon(R.drawable.ic_launcher);
            mnu3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
        MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
        {
            mnu4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
        MenuItem mnu5 = menu.add(0, 4, 4, "Item 5");
        {
            mnu5.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
    }

    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId()) {
            case 0:
                Toast.makeText(this, "You clicked on Item 1",
                        Toast.LENGTH_LONG).show();
                return true;
            case 1:
                Toast.makeText(this, "You clicked on Item 2",
                        Toast.LENGTH_LONG).show();
                return true;
            case 2:
                Toast.makeText(this, "You clicked on Item 3",
                        Toast.LENGTH_LONG).show();
                return true;
            case 3:
                Toast.makeText(this, "You clicked on Item 4",
                        Toast.LENGTH_LONG).show();
                return true;
            case 4:
                Toast.makeText(this, "You clicked on Item 5",
                        Toast.LENGTH_LONG).show();
                return true;
        }
        return false;
    }

}
Add Action Items to the Action Bar

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add animation to ListActivity

Activity (78/474)
« Previous

Add animation to ListActivity

Description

The following code shows how to Add animation to ListActivity.

Example

res/anim/list_animation.xml

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

    <alpha
        android:duration="50"
        android:fromAlpha="0"
        android:toAlpha="1" />

    <translate
        android:duration="100"
        android:fromYDelta="-100%"
        android:toYDelta="0%" />

</set>

Java code

//  ww w .j  a v a  2  s. co m
import android.app.ListActivity;
import android.os.Bundle;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getListView().setLayoutAnimation(
        new LayoutAnimationController(AnimationUtils.loadAnimation(
            this, R.anim.list_animation), 0.5f));

    setListAdapter(new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, Countries.COUNTRIES));
  }

  public static final String[] COUNTRIES = new String[] {
      "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
      "Vietnam", "Wallis and Futuna", "Western Sahara", "Yemen",
      "Yugoslavia", "Zambia", "Zimbabwe" };
}
Add animation to ListActivity

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add CheckBox to AlertDialog

Dialog (278/474)
« Previous

Add CheckBox to AlertDialog

Description

We can set a list of checkboxes for users to choose via the setMultiChoiceItems() method.

For setMultiChoiceItems() method, you passed in two arrays:

  • one for the list of items to display
  • another to contain the value of each item, to indicate if they are checked.

Example

When an item is checked, you use the Toast class to display a message indicating the item that was checked.

The following code has the layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
/*from w  w  w.jav a2  s . co  m*/
    <Button
        android:id="@+id/btn_dialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click to display a dialog"
        android:onClick="onClick" />

</LinearLayout>

Java code

package com.java2s.app;
//from  w w  w. ja  v a2s.co  m
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    CharSequence[] items = {"XML", "Java", "CSS"};
    boolean[] itemsChecked = new boolean[items.length];

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

    public void onClick(View v) {

        Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("This is a dialog with some simple text...");
        builder.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Toast.makeText(getBaseContext(),
                                "OK clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Toast.makeText(getBaseContext(),
                                "Cancel clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        builder.setMultiChoiceItems(items, itemsChecked,
                new DialogInterface.OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int which, boolean isChecked) {
                        Toast.makeText(getBaseContext(),
                                items[which] + (isChecked ? " checked!" : " unchecked!"),
                                Toast.LENGTH_SHORT).show();
                    }
                }
        );
        builder.create().show();

    }
}
Add CheckBox to AlertDialog

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add controls to RadioGroup

RadioButton (409/474)
« Previous

Add controls to RadioGroup

Description

You can manipulate the RadioGroup programmatically.

For example, you can obtain a reference to a radio group and add a radio button (or other type of control).

Example

Layout xml

/*from   w ww .  j a  v  a2s . co  m*/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RadioButton
        android:id="@+id/anotherRadBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Outside" />

    <RadioGroup
        android:id="@+id/radGrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/chRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chicken" />

        <RadioButton
            android:id="@+id/fishRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fish" />

        <RadioButton
            android:id="@+id/stkRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Steak" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My Favorite" />

    </RadioGroup>
</LinearLayout>

Adding a RadioButton to a RadioGroup in Code

package com.java2s.app;
//from w  w w. j  av  a2  s  .c o m
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
        RadioButton newRadioBtn = new RadioButton(this);
        newRadioBtn.setText("java2s.com");
        radGrp.addView(newRadioBtn);
    }

}
Add controls to RadioGroup

Note

Once a radio button is selected within a radio group, the user cannot uncheck it by clicking it again. The only way to clear all radio buttons in a radio group is to call the clearCheck() method on the RadioGroup programmatically.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add focus change listener to EditText

EditText (295/474)
« Previous

Add focus change listener to EditText

Description

The following code shows how to Add focus change listener to EditText.

Example

//create an anonymous inner class to act as an onfocus listener
EditText txt1 = (EditText)findViewById(R.id.txt1);
txt1.setOnFocusChangeListener(new View.OnFocusChangeListener()
{/*from w w w . java2 s. c o m*/
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        Toast.makeText (getBaseContext(),
           ((EditText) v).getId() + " has focus - " + hasFocus,
           Toast.LENGTH_LONG).show();
   }
);

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add fragment

Fragment (305/474)
« Previous

Add fragment

Description

The following code shows you the basic usage of fragments.

Example

In the res/layout folder, add a new file and name it fragment1.xml. Populate it with the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout/*from ww w  .ja v a 2 s.  c o  m*/
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #1"
        android:textColor="#000000"
        android:textSize="25sp" />
</LinearLayout>

Also in the res/layout folder, add another new file and name it fragment2.xml. Populate it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout//from  w  w w  .j  a  va2 s.  com
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFE00"
    >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #2"
        android:textColor="#000000"
        android:textSize="25sp" />
</LinearLayout>

In activity_main.xml, add the following code:

<?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="horizontal" >
/*from  w w  w . j av a  2  s . c o  m*/
    <fragment
        android:name="com.java2s.myapplication3.app.Fragment1"
        android:id="@+id/fragment1"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />
    <fragment
        android:name="com.java2s.myapplication3.app.Fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>

Under the com.java2s.Fragments package name, add two Java class files and name them Fragment1.java and Fragment2.java

Add the following code to Fragment1.java:

package com.java2s.myapplication3.app;
//w w w .ja  va2  s.  c  om
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

Add the following code to Fragment2.java:

package com.java2s.myapplication3.app;
/*from   w w w .  j  av a2  s  .co m*/
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

Note

A fragment behaves very much like an activity: it has

  • a Java class
  • it loads its UI from an XML file.

The XML file contains all the usual UI elements that you expect from an activity: TextView, EditText, Button, and so on.

The Java class for a fragment needs to extend the Fragment base class:

public class Fragment1 extends Fragment {
}

Besides the Fragment base class, a fragment can also extend a few other subclasses of the Fragment class, such as DialogFragment, ListFragment, and PreferenceFragment.

To draw the UI for a fragment, you override the onCreateView() method. This method needs to return a View object.

You can use a LayoutInflater object to inflate the UI from the specified XML file.

To add a fragment to an activity, you use the <fragment> element:

      <?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="horizontal" >
/*from w w w . ja  va2 s  .c om*/
          <fragment
              android:name="com.java2s.Fragments.Fragment1"
              android:id="@+id/fragment1"
              android:layout_weight="1"
              android:layout_width="0px"
              android:layout_height="match_parent" />
          <fragment
              android:name="com.java2s.Fragments.Fragment2"
              android:id="@+id/fragment2"
              android:layout_weight="1"
              android:layout_width="0px"
              android:layout_height="match_parent" />

      </LinearLayout>

Each fragment needs a unique identifier.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add fragment to back stack

Fragment (307/474)
« Previous

Add fragment to back stack

Description

When an activity goes into the background, the activity is placed in the back stack. This allows the activity to be resumed when the user presses the Back button.

Fragments are not automatically placed in the back stack when they go into the background.

Example

To place a fragment into the back stack, you need to explicitly call the addToBackStack() method during a fragment transaction.

//get the current display info
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(android.R.id.content, fragment1);
//add to the back stack/*from  w  w  w.j  a va2  s.  c o m*/
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add Fragments Dynamically

Fragment (306/474)
« Previous

Add Fragments Dynamically

Description

The following code shows how fragments can be added programmatically to an activity during runtime.

Example

Modify the activity_main.xml file as follows:

<?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="horizontal" >
</LinearLayout>/*from   w w  w  . j a v a 2 s.  c om*/

In the res/layout folder, add a new file and name it fragment1.xml. Populate it with the following:

         <?xml version="1.0" encoding="utf-8"?>
         <LinearLayout/*  ww w .ja v  a2 s.  c o m*/
             xmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="vertical"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:background="#00FF00"
             >
         <TextView
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="This is fragment #1"
             android:textColor="#000000"
             android:textSize="25sp" />
         </LinearLayout>

Also in the res/layout folder, add another new file and name it fragment2.xml. Populate it as follows:

         <?xml version="1.0" encoding="utf-8"?>
         <LinearLayout/*from ww w .j  ava 2s . c o m*/
             xmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="vertical"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:background="#FFFE00"
             >
         <TextView
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="This is fragment #2"
             android:textColor="#000000"
             android:textSize="25sp" />
         </LinearLayout>

Under the com.java2s.Fragments package name, add two Java class files and name them Fragment1.java and Fragment2.java

Add the following code to Fragment1.java:

package com.java2s.myapplication3.app;
//  w w w.  jav a  2  s.c  o  m
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

Add the following code to Fragment2.java:

package com.java2s.myapplication3.app;
/*from   w  ww.ja  v a2  s.  c o m*/
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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

Add the following code to the MainActivity.java file:

package com.java2s.myapplication3.app;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
/* w ww.  ja  v  a2 s.  c  o  m*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction =
                fragmentManager.beginTransaction();

        //get the current display info
        WindowManager wm = getWindowManager();
        Display d = wm.getDefaultDisplay();
        if (d.getWidth() > d.getHeight())
        {
            //landscape mode
            Fragment1 fragment1 = new Fragment1();
            // android.R.id.content refers to the content
            // view of the activity
            fragmentTransaction.replace(
                    android.R.id.content, fragment1);
        }
        else
        {
            //portrait mode
            Fragment2 fragment2 = new Fragment2();
            fragmentTransaction.replace(
                    android.R.id.content, fragment2);
        }
        fragmentTransaction.commit();
    }
}
Add Fragments Dynamically

Note

Run the application on the Android emulator. Observe changes when switch from portrait mode to landscape mode.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add items to Spinner

Spinner (416/474)
« Previous

Add items to Spinner

Description

The following code shows how to add items to Spinner.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <Spinner android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
  />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/*w w w .  j a  v  a 2  s .c  om*/
public class MainActivity extends Activity
  implements AdapterView.OnItemSelectedListener {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);

    Spinner spin=(Spinner)findViewById(R.id.spinner);
    spin.setOnItemSelectedListener(this);

    ArrayAdapter<String> aa=new ArrayAdapter<String>(this,
                              android.R.layout.simple_spinner_item,
                              items);
    aa.setDropDownViewResource(
      android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(aa);
  }

  public void onItemSelected(AdapterView<?> parent,View v, int position, long id) {
    selection.setText(items[position]);
  }

  public void onNothingSelected(AdapterView<?> parent) {
    selection.setText("");
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Add items to Spinner

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add menu to activity

Menu (389/474)
« Previous

Add menu to activity

Description

The following code shows how to add menu to activity.

Example

layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click on the option menu and play with the choices!"
    />
</LinearLayout>

Menu file:main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/close"
    android:title="Close"
    android:orderInCategory="3"
    android:icon="@drawable/ic_launcher" />
  <item android:id="@+id/no_icon"
    android:orderInCategory="2"
    android:title="Sans Icon" />
  <item android:id="@+id/disabled"
    android:orderInCategory="4"
    android:enabled="false"
    android:title="Disabled" />
  <group android:id="@+id/other_stuff"
    android:menuCategory="secondary"
    android:visible="false">
    <item android:id="@+id/later"
      android:orderInCategory="0"
      android:title="2nd-To-Last" />
    <item android:id="@+id/last"
      android:orderInCategory="1"
      android:title="Last" />
  </group>
  <item android:id="@+id/submenu"
    android:orderInCategory="3"
    android:title="A Submenu">
    <menu>
      <item android:id="@+id/non_ghost"
        android:title="Non-Ghost"
        android:visible="true"
        android:alphabeticShortcut="n" />
      <item android:id="@+id/ghost"
        android:title="A Ghost"
        android:visible="false"
        android:alphabeticShortcut="g" />
    </menu>
  </item>
</menu>

Java code

package com.java2s.myapplication3.app;
//from  w w  w.j  a v a 2 s . co m
import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends Activity {
    private final static Map<Integer,String> MESSAGES;
    private boolean otherStuffVisible=false;
    private Menu theMenu=null;

    static {
        MESSAGES=new HashMap<Integer,String>();
        MESSAGES.put(R.id.close, "close");
        MESSAGES.put(R.id.no_icon, "no icon");
        MESSAGES.put(R.id.later, "later");
        MESSAGES.put(R.id.last, "last");
        MESSAGES.put(R.id.non_ghost, "ghost");
        MESSAGES.put(R.id.ghost, "Boo!");
    };

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        theMenu=menu;

        new MenuInflater(getApplication()).inflate(R.menu.main, menu);

        return(super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==R.id.non_ghost) {
            otherStuffVisible=!otherStuffVisible;

            theMenu.setGroupVisible(R.id.other_stuff, otherStuffVisible);
        }

        String message=MESSAGES.get(item.getItemId());

        if (message!=null) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

            return(true);
        }

        return(super.onOptionsItemSelected(item));
    }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Add menu to activity

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add menu to ListView

ListView (378/474)
« Previous

Add menu to ListView

Description

The following code shows how to Add menu to ListView.

Example

Menu xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/menu_delete"
    android:icon="@android:drawable/ic_menu_delete"
    android:title="Delete Item"
  />
  <item
    android:id="@+id/menu_edit"
    android:icon="@android:drawable/ic_menu_edit"
    android:title="Edit Item"
  />
</menu>

Main activity Java code

package com.java2s.myapplication3.app;
/*from  w  w  w .  jav a  2 s. co m*/
import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity implements AbsListView.MultiChoiceModeListener {

    private static final String[] ITEMS =
            {"XML", "CSS", "HTML", "Java", "Javascript", "SQL"};

    private ListView mList;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mList = new ListView(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_1, ITEMS);
        mList.setAdapter(adapter);
        mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        mList.setMultiChoiceModeListener(this);

        setContentView(mList);
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        //You can do extra work here update the menu if the
        // ActionMode is ever invalidated
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        //This is called when the action mode has ben exited
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        SparseBooleanArray items = mList.getCheckedItemPositions();
        switch(item.getItemId()) {
            case R.id.menu_delete:
                //Perform delete actions
                break;
            case R.id.menu_edit:
                //Perform edit actions
                break;
            default:
                return false;
        }
        return true;
    }

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position,
                                          long id, boolean checked) {
        int count = mList.getCheckedItemCount();
        mode.setTitle(String.format("%d Selected", count));
    }
}
Add menu to ListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Add Tab to TabHost

Tab (419/474)
« Previous

Add Tab to TabHost

Description

The following code shows how to Add Tab to TabHost.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TabHost android:id="@+id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabWidget android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    />
    <FrameLayout android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:paddingTop="62px">
      <Button android:id="@+id/buttontab"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="A semi-random button"
      />
    </FrameLayout>
  </TabHost>
</LinearLayout>

Java code

/***//  www  .j  ava2 s  .c om
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.java2s.myapplication3.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.TabHost;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);

        final TabHost tabs=(TabHost)findViewById(R.id.tabhost);

        tabs.setup();

        TabHost.TabSpec spec=tabs.newTabSpec("buttontab");
        spec.setContent(R.id.buttontab);
        spec.setIndicator("Button");
        tabs.addTab(spec);

        tabs.setCurrentTab(0);

        Button btn=(Button)tabs.getCurrentView().findViewById(R.id.buttontab);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                TabHost.TabSpec spec=tabs.newTabSpec("tag1");

                spec.setContent(new TabHost.TabContentFactory() {
                    public View createTabContent(String tag) {
                        return(new AnalogClock(MainActivity.this));
                    }
                });
                spec.setIndicator("Clock");
                tabs.addTab(spec);
            }
        });
    }
}
Add Tab to TabHost

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Align parent in RelativeLayout

Layout (349/474)
« Previous

Align parent in RelativeLayout

Description

The following code shows how to Align parent in RelativeLayout.

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <AnalogClock android:id="@+id/analog"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true"
    />
  <DigitalClock android:id="@+id/digital"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/analog"
    />
</RelativeLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
//from w  w w .  j a v  a 2s.  c  o m
public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
  }
}
Align parent in RelativeLayout

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Anchor Views

Activity (60/474)
« Previous

Anchor Views

Description

Anchoring can be easily achieved by using RelativeLayout.

Example

Consider the following main.xml file, which contains five Button views embedded within the <RelativeLayout> element:

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Right"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true" />
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true" />
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Right"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />
    <Button
        android:id="@+id/button5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Middle"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Note

The following attributes found in the various Button views:

  • layout_alignParentLeft aligns the view to the left of the parent view
  • layout_alignParentRight aligns the view to the right of the parent view
  • layout_alignParentTop aligns the view to the top of the parent view
  • layout_alignParentBottom aligns the view to the bottom of the parent view
  • layout_centerVertical centers the view vertically within its parent view
  • layout_centerHorizontal centers the view horizontally within its parent view

When the screen orientation is changed, the four buttons are aligned to the four edges of the screen, and the center button is centered in the middle of the screen with its width fully stretched.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Action Bar

Basic

  • Add Action Items to the Action Bar
  • Customize the Action Items and Application Icon
  • Make application icon clickable on the Action Bar
  • Use Action Bar

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Activity

Introduction

  • Link activity with UI

Life cycle

  • Activity life cycle
  • Save data on pause and read back on resume for Activity
  • Save State Information during Changes in Configuration

Configuration

  • Adapt To Display Orientation
  • Anchor Views
  • Resize and Reposition
  • Control the Orientation of the Activity
  • Determine portrait mode or landscape mode
  • Log Screen Orientation Changes
  • Save State during orientation change
  • Setup view for orientation change
  • Change activity orientation
  • Handle AsyncTask interruption during configuration change
  • React to configuration changed event

Title

  • Hide Activity Title
  • Set activity to no title bar and full screen

Event

  • Activity User Event
  • Handle key down event from Activity

Theme

  • Create custom Theme

Thread

  • Block draw measure layout thread

Dialog

  • Start activity vs start activity for result
  • Turn Activity to Dialog

ListActivity

  • Add animation to ListActivity

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Animation

Basic

  • Create ScaleAnimation
  • Create XML based animation
  • Create custom animation
  • Use ObjectAnimator

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android applications artifacts

Description

Android applications have some artifacts that are required and some that are optional.

An Android application is primarily made up of three pieces:

  • application descriptor,
  • a collection of various resources, and
  • the application's source code.

Artifacts

  • AndroidManifest.xml
    Required:Yes
    The Android application descriptor file. This file defines the activities, content providers, services, and intent receivers of the application. You can also use this file to declaratively define permissions required by the application, as well as grant specific permissions to other applications.
  • src
    Required:Yes
    A folder containing all of the source code of the application.
  • assets
    Required:No
    An arbitrary collection of folders and files.
  • res
    Required:Yes
    A folder containing the resources of the application. This is the parent folder of drawable, anim, layout, menu, values, xml, and raw.
  • drawable
    Required:No
    A folder containing the images or image-descriptor files used by the application.
  • animator
    Required:No
    A folder containing the XML files that describe the animations used by the application.
  • layout
    Required:No
    A folder containing views of the application.
  • menu
    Required:No
    A folder containing XML files for menus in the application.
  • values
    Required:No
    A folder containing other resources used by the application. For example, okstrings, arrays, styles, and colors.
  • xml
    Required:No
    A folder containing additional XML files used by the application.
  • raw
    Required:No
    A folder containing additional data required by the application.

Note

Android supports only a linear list of files within the predefined folders under res.

For example, it does not support nested folders under the layout folder or the other folders under res. The files in raw are considered resources, and the files in assets are not.

So the files in raw are localized, accessible through resource IDs, and so on.

But the contents of the assets folder are considered general-purpose content to be used without resource constraints and support.

You can put an arbitrary hierarchy of folders and files in assets folder.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Basics

Android Basics

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
Home »
Android »
Android Basics

java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Button

Basic

  • Create a Button
  • Create Button with code only
  • Create button with rounded corner

Event

  • Button XML attribute click handler
  • Implement View.OnClickListener
  • Update Button text when clicking

ImageButton

  • Button with three state images
  • ImageButton with transparent background
  • Use ImageButton

ToggleButton

  • Use ToggleButton

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Calendar

Basic

  • Read Calendar information

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Camera

Basic

  • Take a picture and preview
  • Use SurfaceView to display camera preview

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Canvas

Basic

  • Create Image mask on Canvas
  • Draw Bitmap on Canvas
  • Draw Canvas With Alpha
  • Draw Canvas with Random Color
  • Draw Image loaded from URL on canvas
  • Draw Random Shapes on Canvas
  • Draw Shapes, Text and Bitmap
  • Draw text on Canvas
  • Make Canvas FullScreen
  • Redraw Canvas by calling invalidate method
  • View to display a true type font via Canvas

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android CheckBox

Basic

  • Change CheckBox text on select event
  • CheckBox state change event
  • Create CheckBox
  • Set up click handler in XML for CheckBox

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Clock Date Picker

Clock

  • Create AnalogClock
  • Create a DigitalClock

Picker

  • Create DatePickerDialog from onCreateDialog method
  • Create a DatePicker
  • Set TimePicker to 24 Hour View
  • Use DatePickerDialog
  • Create a TimePicker
  • Use TimePickerDialog

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Contact

Introduction

  • Pick an item from a data source
  • Read contact list
  • Read contact

Read

  • Gather Contact addresses from address table
  • Use Contact Content Provider
  • Gather Contact email data from email table
  • Gather Contact phone data from phone table

Edit

  • Edit Contacts
  • Query, delete, update, add Contacts

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Content Provider

Introduction

  • Get to know ContentProviders
  • Architecture of Content Providers
  • Content provider URL
  • Content provider MIME type
  • Content-provider vs Others

Create

  • Create Your Own Content Providers
  • Database backed Content provider
  • Create Content Provider to read from Asset folder
  • Extend DocumentsProvider to provide image

Operation

  • Filtering
  • Projections in Contact Content Provider
  • Sorting
  • Read Database backed content provider and fill ListView

Cursor

  • Print out the content provider result using the Cursor object

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Database

Introduction

  • Introduction to Android Dababase
  • Upgrade the Database

Helper

  • Create Database Helper Class
  • Create Database Helper

Utility

  • Check if a given string exists in the specified table and column
  • Check if any rows match the where clause
  • Create a class representing a row in a table with CRUD methods
  • Get an array of all int type data matching the conditions
  • Get an array of long type values matching the condition
  • Get maximum value in database for given condition
  • Get the id of the first row whose column matches conditions
  • Backup database to external storage
  • Load data from Database to ListView

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Dialog

Basic

  • Display a Dialog Window
  • Use PopupWindow

Alert

  • Add CheckBox to AlertDialog
  • Raise alert or toast from Button click event
  • Use AlertDialog to display text from EditText
  • Create AlertDialog from ArrayAdapter
  • Use AlertDialog.Builder to build an AlertDialog

Progress

  • Display a Progress Dialog
  • Display the Progress of an Operation

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android EditText

Basic

  • Set text to EditText
  • Create a Tip Calculator

Input

  • EditText AutoCorrect
  • EditText password
  • EditText phone numbers
  • EditText Capitalize
  • Multiple lines and single line
  • Set hint text for EditText
  • Set input method option with imeOptions

Event

  • Add focus change listener to EditText
  • Create TextWatcher for currency value

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Event

Basic

  • Dispatch event to a control
  • React to long-press listener
  • Use ShareActionProvider
  • implement TextWatcher interface from Activity class

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Fragment

Introduction

  • What are fragments
  • Add fragment
  • Add Fragments Dynamically
  • Add fragment to back stack
  • Interactions between Fragments
  • Use FragmentManager

Life cycle

  • Life Cycle of a Fragment methods
  • Life Cycle of a Fragment Example

Type

  • Use a ListFragment
  • Use a DialogFragment
  • Using a PreferenceFragment

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Gesture

Basic

  • Handle custom Gesture
  • Track user gesture velocity
  • Use ScaleGestureDetector

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android GridView

Introduction

  • What is GridView
  • ImageSwitcher
  • Use GridView to display array data

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Hardware

USB

  • Read USB device information

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Hello Android

Basics

  • What Is Android
  • Get to Know the Fundamental Components
  • Android applications artifacts
  • Get to know AndroidManifest
  • Set target SDK version
  • Set the minSdkVersion
  • Turn off soft input panel

Log

  • Log message
  • Wrap log class to create your own logger

Next »
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android ImageView

Setup

  • ImageView XML and Java Code
  • Create empty ImageView
  • ImageView size and scale
  • Set ImageView adjustViewBounds to true

Image

  • ImageView and BitmapFactory
  • ImageView and color
  • ImageView and drawable resource
  • Load Image from sdcard
  • Create Rounded Corner ImageView from View to show Image
  • Manipulate Image
  • Use PagerAdapter to display Image

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Intent

Introduction

  • What are Intents
  • Intent Composition
  • Pass Data Using an Intent Object
  • Resolve Intent Filter Collision
  • Return Results from an Intent
  • Use Intent Categories
  • Use Intent Filters

Action

  • Download from market
  • Intent to call a number
  • Intent to open Dialer
  • Intent to open browser
  • Intent to show a map
  • Open Activities Using Intents
  • Pick a picture
  • Send E-Mail
  • Send out email
  • Start Intent for web search
  • Take a picture
  • Download App from Market
  • Intent Web Search with keyword
  • Receive Alarm Intent
  • Use Intent Share a message with friends
  • Use Intent to Get Media content
  • Use Intent to do Speech Recognize
  • Use Intent to get content and pick video
  • Use Intent to launch another activity to play m4v file
  • Use Intent to pick contact People
  • Use Intent to start your service
  • Use Intent to send SMS message
  • Use Intent to send email with attachment
  • Use Intent to view PDF file

Pending Intent

  • Use PendingIntent to create Notification

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Layout

Basic

  • Units Of Measurement
  • Convert Dp To Px
  • screen densities
  • Create custom layout
  • layout_weight and layout_gravity
  • Provide layout for landscape
  • Set layout weight, gravity and background
  • Provide extra layout xml file for Tablet

LinearLayout

  • Create LinearLayout Programmatically
  • Create nested LinearLayout
  • Horizontal LinearLayout
  • Use LinearLayout to layout common controls
  • Use LinearLayout to layout widgets

RelativeLayout

  • What is RelativeLayout
  • Align parent in RelativeLayout
  • Use RelativeLayout

TableLayout

  • What is TableLayout
  • Put TableLayout into a LinearLayout
  • TableLayout with two TableRow
  • Create a TableLayout with only one row

FrameLayout

  • What is FrameLayout
  • Use FrameLayout inside TabHost
  • Create FrameLayout with TouchDelegate
  • Create FrameLayout with two TextView
  • Create custom view from FrameLayout

Scroll

  • Use ScrollView

Animation

  • Create Layout Changes Animation
  • Set one view to the right of another view
  • Use LayoutTransition
  • Use SlidingDrawer

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android ListView

Create

  • Create ListView in code
  • Change ListView Divider Height
  • Config ListView layout in XML
  • Enable filtering support on ListView

Row

  • ListView with custom Row
  • ListView with TextView as cell renderer
  • Attach TextView to empty ListView
  • Attach empty view for ListView for empty ListView adapter
  • Custom ListView item
  • Use Context menu to control ListView

Data

  • Extends ArrayAdapter to create Iconic Adapter for ListView
  • Load items in the strings xml File to ListView
  • Display all contacts in a ListView

Event

  • Check Which Items Are Selected in ListView
  • Listen to list item clicked event for ListView
  • Select multiple items in the ListView
  • Add menu to ListView

UI

  • Use ExpandableListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Location

Basic

  • Create region monitor service
  • Get information from LocationProvider
  • Get location with GPS
  • Get your location
  • Use location service

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Map

Basic

  • Create a MapView
  • Show your home location on Map

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Media

Capture

  • Capture an Image and save to external storage
  • Record audio
  • Save Media content
  • Speech recognize

Play

  • Play mp3 file from raw folder
  • Play mp3 file loaded from a URL
  • Play mp4 file in external storage
  • Play ogg file

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Menu

Basic

  • Add menu to activity
  • Context Menu
  • Context menu action handler
  • Create Menu in the code
  • Create PopupMenu to display just below TextView
  • Handle Options Item Selected Event
  • Options Menu

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Model

Basic

  • Use custom model in ArrayAdapter

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Network

Download

  • Connect to the web to download content
  • Download a series of images asynchronously
  • Download Binary Data from the web
  • Download Image from a URL
  • Download Image With Message Passing
  • Download Text Content
  • Use DownloadManager to download

Web Services

  • Access Web Services Using the GET Method
  • Consume Json Services

State

  • Check Network state

Bluetooth

  • Bluetooth Communication

Socket

  • Talk to a Socket Server

NFC

  • Use Near Field Communication

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Notification

Introduction

  • Create Restrictions Receiver
  • Display Notifications

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android OpenGL

Basic

  • Draw a Pyramid with Texture in OpenGL
  • Draw a Triangle using OpenGL
  • Set up GLSurfaceView for OpenGL
  • Pyramid

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Preference

Introduction

  • Save And Load User Preferences
  • Programmatically Retrieving and Modifying the Preferences Values
  • Create email preference dialog
  • Change the Default Name of the Preferences File
  • Get and set SharedPreferences
  • Update Preferences

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android ProgressBar

Basic

  • Change the look of the ProgressBar
  • Use Handler to send message to ProgressBar and update progress

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android RadioButton

Basic

  • Create a RadioButton

RadioGroup

  • RadioGroup with More Than Just RadioButtons
  • Add controls to RadioGroup
  • Use code to change the gravity layout for RadioGroup
  • Use code to control vertical or horizontal layout for RadioGroup

Event

  • implements RadioGroup.OnCheckedChangeListener
  • RadioGroup Checked Change Listener
  • Select a RadioButton

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Resources

Introduction

  • Key Android Resources List
  • Compiled and Uncompiled Android Resources
  • /res folder and subdirectories
  • Resources Directory Structure
  • Resource Reference Type
  • Resource Reference name and package
  • Resources and Configuration
  • Resource configuration qualifiers
  • Qualifiers precedence order
  • Basic syntax for create resource ID

String

  • String Resources
  • Plurals Resource
  • Java format string
  • HTML strings
  • HTML encode and decode
  • Quoted strings
  • Use multiple string resource files
  • String Arrays

Color Image

  • Color Resources
  • Color-Drawable Resources
  • Use color resource in a view definition
  • Image Resources
  • Create rounded corners in your Drawable

Layout

  • Layout Resources
  • Use string resource in layout resource
  • Dimension Resources

XML

  • Use any XML Resource Files
  • Parse xml resource

RAW

  • Use Raw Resources
  • Load and parse raw xml file
  • Use Static Resources

Assets

  • Use Assets
  • Load an HTML file located in the assets folder

File

  • Load the file from the external storage
  • Save to Internal Storage
  • Save to External Storage (SD Card)
  • Parse JSON Data
  • Read and parse CSV file from asset folder
  • Write and read External storage with File Utilities
  • Write and read file in External Storage Directory
  • Write and read file
  • Write and read from Internal Storage

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Sensor

Basic

  • Display the compass direction
  • Listen to sensor change event
  • User motion detector

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Service

Communication

  • Communicate Between A Service And An Activity
  • Pass data from Activity To Service

Basic

  • Create Your First Service
  • Create service
  • Create your first IntentService
  • Partial wake
  • extends IntentService to create your own service

Thread

  • Perform Long-Running Tasks in a Service
  • Perform Repeated Tasks in a Service
  • Put long-running service to a separate Thread

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android SMS

Basic

  • Send SMS Messages Programmatically
  • Send SMS Messages Using Intent
  • Get Feedback after Sending a Message
  • Receive SMS Messages
  • SMS reciver

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Spinner

Basic

  • Add items to Spinner
  • Listen to selection event from Spinner

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Tab

Basic

  • Add Tab to TabHost
  • Use TabHost

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android TextView

Basic

  • What is TextView

Properties

  • Reference color resource in TextView
  • Set text for TextView in XML

Format

  • TextView add links
  • Use format string in TextView
  • Use LinkMovementMethod in hyper link
  • Use SpannableString
  • Use TextView autoLink

Font

  • Extend TextView with custom font
  • Set ttf font for TextView

Event

  • Post from TextView
  • Use TextSwitcher with animation

AutoComplete

  • Listen to text changed event for AutoCompleteTextView
  • Set Threshold for AutoCompleteTextView
  • Use ArrayAdapter to fill data to AutoCompleteTextView
  • Use AutoCompleteTextView
  • Use MultiAutoCompleteTextView

Thread

  • Update TextView with a Thread

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Thread

Basic

  • Create an activity and do task with Thread
  • Producer and Consumer with Handler
  • Stop the AsyncTask
  • Update the UI from a separate thread with AsyncTask
  • Use Handler class to Update UI from another thread
  • Use background thread to do image processing

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Toast

Basic

  • Show Toast in four different corners

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android UI

Android UI

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
Home »
Android »
Android UI

java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android UI Basics

Basic

  • UI Development in Android
  • Common attributes

Build

  • Build a UI Completely in Code
  • Build a UI Completely in XML
  • Build a UI in XML with Code
  • Connect Layout xml to Java code

UI

  • Request window feature
  • Set System UI Visibility
  • Set system UI to full screen
  • Set system UI to low profile

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Video

Basic

  • Create VideoView
  • Create a Video recorder
  • Read metadata for a video
  • Video capture with Intent

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android View

Basic

  • Views and ViewGroups

Flipper

  • Flip ViewFlipper with animation
  • Use ViewFlipper

Custom

  • Extend View to create custom view
  • Create custom View
  • Create fade in fade out and slide animation for a View
  • Use ViewPager

Scroll

  • ScrollView

Draw

  • Draw and resize
  • Draw texture with thread
  • Draw to SurfaceView with thread

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android WebView

Basic

  • Load a URL with WebView
  • Load static html code in WebView
  • Dynamically create an HTML string and load it into the WebView
  • extends WebViewClient
  • Get web settings from WebView
  • Android WebView and Javascript-Java interaction process
  • Execute Javascript in WebView
  • Use webkit

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android WebView and Javascript-Java interaction process

Description

The following code shows how to use Android WebView and Javascript-Java interaction process.

Example

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

Java code

/*from w w  w  . jav  a 2 s .  c  o m*/
//package com.prasanta;

package com.java2s.myapplication3.app;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.util.Log;
import android.webkit.WebView;

/**
 * Demonstrates usage of Android WebView and Javascript-Java
 * interaction process.
 *
 * @author prasanta
 *
 */
public class MainActivity extends Activity implements Callback {

    WebView mWebView;
    String TAG = "Prasanta";
    Handler mHandler;
    ProgressDialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler(this);
        setContentView(initWebView());
    }

    /**
     * Initialize WebView
     * @return
     */
    private WebView initWebView() {
        mWebView = new WebView(this);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(false);
        // Scale
        mWebView.setInitialScale(0);

        // Define the JS-Java interaction object
        mWebView.addJavascriptInterface(new JSImp(), "native_java");

        // load content
        mWebView.loadUrl("file:///android_asset/web/index.html");

        return mWebView;
    }

    private class JSImp {

        public String getDataFromJava(final String name){
            // Ask handler to show Dialog Box
            mHandler.sendEmptyMessage(0);

        /*
         * Schedule one Task to Cancel Dialog and Update HTML element
         */
            Timer timer = new Timer();
            TimerTask task = new TimerTask(){
                public void run(){
                    if(dialog != null && dialog.isShowing())
                        dialog.cancel();

                    // Call JS method
              /*
               * Make sure you call this once the respective HTML/JavaScript code loading is over
               */
                    mWebView.loadUrl("javascript:updateMsg('"+ name +" got 750 messages')");
                }
            };

            timer.schedule(task, 2000);

            return name +" - you got 750 messages";
        }

    }

    public boolean handleMessage(Message msg) {
        // Show progress bar
        Log.i(TAG, "Showing progress....");
        dialog = new ProgressDialog(this);
        dialog.setTitle("Please wait...");
        dialog.show();
        return false;
    }
}
Android WebView and Javascript-Java interaction process

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Architecture of Content Providers

Content Provider (96/474)
« Previous

Architecture of Content Providers

Description

Each content provider on a device registers itself like a web site with a string called an authority.

The authority string forms the basis of a set of URIs that this content provider can offer.

This authority registration is defined in the AndroidManifest.xml file.

Example

Here are two examples of how you can register providers in AndroidManifest.xml:

<provider android:name="SomeProvider"
          android:authorities="com.your-company.SomeProvider" />
//from  www.j  av a  2s .c o  m
<provider android:name="NotePadProvider"
          android:authorities="com.google.provider.NotePad"/>

Note

An authority is like a domain name for that content provider.

A content provider, like a web site, has a base domain name that acts as a starting URL.

Given the preceding authority registration, these providers will take URLs starting with that authority prefix:

content://com.your-company.SomeProvider/
content://com.google.provider.NotePad/

The providers offered by Android may not have a fully qualified authority name.

For example, contacts as opposed to com.google.android.contacts.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Attach empty view for ListView for empty ListView adapter

ListView (380/474)
« Previous

Attach empty view for ListView for empty ListView adapter

Description

The following code shows how to Attach empty view for ListView for empty ListView adapter.

Example

Layout xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:id="@+id/myempty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="No Items to Display"
        />
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Tap Here to Refresh"
        />
    </LinearLayout>
    <ListView
        android:id="@+id/mylist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    />
</FrameLayout>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w  w w .  j av a2 s .  c  o m*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ListView;

public class MainActivity extends Activity {

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

        ListView list = (ListView)findViewById(R.id.mylist);
        LinearLayout empty = (LinearLayout)findViewById(R.id.myempty);

        list.setEmptyView(empty);

        //Continue adding adapters and data to the list
    }

}
Attach empty view for ListView for empty ListView adapter

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Attach TextView to empty ListView

ListView (379/474)
« Previous

Attach TextView to empty ListView

Description

The following code shows how to Attach TextView to empty ListView.

Example

Main layout xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/myempty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No Items to Display"
    />
    <ListView
        android:id="@+id/mylist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    />
</FrameLayout>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w ww  . j a v  a  2 s  .c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        ListView list = (ListView)findViewById(R.id.mylist);
        TextView empty = (TextView)findViewById(R.id.myempty);

        /*
         * Attach the empty view.  The framework will show this
         * view when the ListView's adapter has no elements.
         */
        list.setEmptyView(empty);

        //Continue adding adapters and data to the list
    }

}
Attach TextView to empty ListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Backup database to external storage

Database (121/474)
« Previous

Backup database to external storage

Description

The following code shows how to Backup database to external storage.

Example

Set permission for WRITE_EXTERNAL_STORAGE

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="com.java2s.myapplication3.app.READ_PREFERENCES" />
    <uses-permission android:name="com.java2s.myapplication3.app.WRITE_PREFERENCES" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout xml file

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

Main activity Java code

package com.java2s.myapplication3.app;
/*  ww  w .  ja va2  s .  com*/

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class MainActivity extends Activity implements BackupTask.CompletionListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SQLiteDatabase db = openOrCreateDatabase("mydb", Activity.MODE_PRIVATE, null);
        db.close();
    }

    @Override
    public void onResume() {
        super.onResume();
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
            BackupTask task = new BackupTask(this);
            task.setCompletionListener(this);
            task.execute(BackupTask.COMMAND_RESTORE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
            BackupTask task = new BackupTask(this);
            task.execute(BackupTask.COMMAND_BACKUP);
        }
    }

    @Override
    public void onBackupComplete() {
        Toast.makeText(this, "Backup Successful", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(int errorCode) {
        if(errorCode == BackupTask.RESTORE_NOFILEERROR) {
            Toast.makeText(this, "No Backup Found to Restore", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Error During Operation: "+errorCode, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRestoreComplete() {
        Toast.makeText(this, "Restore Successful", Toast.LENGTH_SHORT).show();
    }
}
class BackupTask extends AsyncTask<String,Void,Integer> {
    public interface CompletionListener {
        void onBackupComplete();
        void onRestoreComplete();
        void onError(int errorCode);
    }

    public static final int BACKUP_SUCCESS = 1;
    public static final int RESTORE_SUCCESS = 2;
    public static final int BACKUP_ERROR = 3;
    public static final int RESTORE_NOFILEERROR = 4;

    public static final String COMMAND_BACKUP = "backupDatabase";
    public static final String COMMAND_RESTORE = "restoreDatabase";

    private Context mContext;
    private CompletionListener listener;

    public BackupTask(Context context) {
        super();
        mContext = context;
    }

    public void setCompletionListener(CompletionListener aListener) {
        listener = aListener;
    }

    @Override
    protected Integer doInBackground(String... params) {
        File dbFile = mContext.getDatabasePath("mydb");
        File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        String command = params[0];
        if(command.equals(COMMAND_BACKUP)) {
            //Attempt file copy
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return BACKUP_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else if(command.equals(COMMAND_RESTORE)) {
            //Attempt file copy
            try {
                if(!backup.exists()) {
                    return RESTORE_NOFILEERROR;
                }
                dbFile.createNewFile();
                fileCopy(backup, dbFile);
                return RESTORE_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else {
            return BACKUP_ERROR;
        }
    }

    @Override
    protected void onPostExecute(Integer result) {

        switch(result) {
            case BACKUP_SUCCESS:
                if(listener != null) {
                    listener.onBackupComplete();
                }
                break;
            case RESTORE_SUCCESS:
                if(listener != null) {
                    listener.onRestoreComplete();
                }
                break;
            case RESTORE_NOFILEERROR:
                if(listener != null) {
                    listener.onError(RESTORE_NOFILEERROR);
                }
                break;
            default:
                if(listener != null) {
                    listener.onError(BACKUP_ERROR);
                }
        }
    }

    private void fileCopy(File source, File dest) throws IOException {
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(dest).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
}
Backup database to external storage

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Basic syntax for create resource ID

Resources (21/474)
« Previous

Basic syntax for create resource ID

Description

When you write

<TextView android:id="@+id/text1" ..../>

Its meaning is, "Use text1 to reference this instanceof TextView."

The + indicates that if the id of text1 is not defined as a resource, go ahead and define it with a unique number.

Define Your Own Resource IDs

It is possible to create IDs and use them in your own application.

IDs are treated as resources.

We can use a resource tag called item to define an ID without attaching to any particular resource as the following example.

<resources>
   <item type="id" name="text"/>
</resources>

The type refers to the type of resource id in this case. Once this ID is in place, the View definition in the following will work.

<TextView android:id="@id/text">
..
</TextView>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Block draw measure layout thread

Activity (75/474)
« Previous

Block draw measure layout thread

Description

The following code shows how to block draw measure layout thread.

Example

<?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:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="hello" />

    <com.java2s.SlowMeasureView
        android:id="@+id/slow_measure"
        android:layout_width="fill_parent"
        android:layout_height="30dp"
        android:background="#00ff00"
        android:text="slow measure" />

    <com.java2s.SlowLayoutView
        android:id="@+id/slow_layout"
        android:layout_width="fill_parent"
        android:layout_height="30dp"
        android:background="#0000ff"
        android:text="slow layout" />

    <com.java2s.SlowDrawView
        android:id="@+id/slow_draw"
        android:layout_width="fill_parent"
        android:layout_height="30dp"
        android:background="#ff0000"
        android:text="slow draw" />

</LinearLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning// ww w. ja  v  a 2 s .  c o m
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}
class ThreadUtils {

  private static final long DEFAULT_SLEEP_DURATION = 2500L;

  private ThreadUtils() {
  }

  public static void sleep() {
    sleep(DEFAULT_SLEEP_DURATION);
  }

  public static void sleep(long duration) {
    try {
      Thread.sleep(duration);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}

class SlowDrawView extends TextView {

  public SlowDrawView(Context context) {
    super(context);
  }

  public SlowDrawView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SlowDrawView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    /*
     * Please remember this is just a hack for the purpose of the demonstration.
     * Do not block the main thread in production code as it may fire an
     * "Application Not Responding" dialog.
     */
    ThreadUtils.sleep();
    super.onDraw(canvas);
  }
}

class SlowLayoutView extends TextView {

  public SlowLayoutView(Context context) {
    super(context);
  }

  public SlowLayoutView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SlowLayoutView(Context context, AttributeSet attrs,
      int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onLayout(boolean changed, int left, int top,
      int right, int bottom) {
    /*
     * Please remember this is just a hack for the purpose of the demonstration.
     * Do not block the main thread in production code as it may fire an
     * "Application Not Responding" dialog.
     */
    ThreadUtils.sleep();
    super.onLayout(changed, left, top, right, bottom);
  }
}

class SlowMeasureView extends TextView {

  public SlowMeasureView(Context context) {
    super(context);
  }

  public SlowMeasureView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SlowMeasureView(Context context, AttributeSet attrs,
      int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    /*
     * Please remember this is just a hack for the purpose of the demonstration.
     * Do not block the main thread in production code as it may fire an
     * "Application Not Responding" dialog.
     */
    ThreadUtils.sleep();
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }
}
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Bluetooth Communication

Network (184/474)
« Previous

Bluetooth Communication

Description

The following code shows how to do Bluetooth Communication.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

res\layout\main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Enter Your Email:"
  />
  <EditText
    android:id="@+id/emailField"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/label"
    android:singleLine="true"
    android:inputType="textEmailAddress"
  />
  <Button
    android:id="@+id/scanButton"
    android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentBottom="true"
     android:text="Connect and Share"
  />
  <Button
    android:id="@+id/listenButton"
    android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_above="@id/scanButton"
     android:text="Listen for Sharers"
  />
</RelativeLayout>

ExchangeActivity.java

/**/*  www . jav a  2 s .  c  om*/
 * Created on May 19, 2010 by Dave Smith
 * Wireless Designs, LLC
 *
 */

package com.java2s.myapplication3.app;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final UUID MY_UUID = UUID.fromString("311cb9fa-9066-5f58-945e-ef56d1ae16ec");
    private static final String SEARCH_NAME = "bluetooth.recipe";

    BluetoothAdapter mBtAdapter;
    BluetoothSocket mBtSocket;
    Button listenButton, scanButton;
    EditText emailField;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Activity");
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_main);

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBtAdapter == null) {
            Toast.makeText(this, "Bluetooth is not supported.", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE);
        }

        emailField = (EditText)findViewById(R.id.emailField);
        listenButton = (Button)findViewById(R.id.listenButton);
        listenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Make sure the device is discoverable first
                if (mBtAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                    startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE);
                    return;
                }
                startListening();
            }
        });
        scanButton = (Button)findViewById(R.id.scanButton);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtAdapter.startDiscovery();
                setProgressBarIndeterminateVisibility(true);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //Register the activity for broadcast intents
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if(mBtSocket != null) {
                mBtSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final int REQUEST_ENABLE = 1;
    private static final int REQUEST_DISCOVERABLE = 2;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case REQUEST_ENABLE:
                if(resultCode != Activity.RESULT_OK) {
                    Toast.makeText(this, "Bluetooth Not Enabled.", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            case REQUEST_DISCOVERABLE:
                if(resultCode == Activity.RESULT_CANCELED) {
                    Toast.makeText(this, "Cannot listen unless we are discoverable.", Toast.LENGTH_SHORT).show();
                } else {
                    startListening();
                }
                break;
            default:
                break;
        }
    }

    private void startListening() {
        AcceptTask task = new AcceptTask();
        task.execute(MY_UUID);
        setProgressBarIndeterminateVisibility(true);
    }

    //AsyncTask to accept incoming connections
    private class AcceptTask extends AsyncTask<UUID,Void,BluetoothSocket> {

        @Override
        protected BluetoothSocket doInBackground(UUID... params) {
            String name = mBtAdapter.getName();
            try {
                //While listening, set the discovery name to a specific value
                mBtAdapter.setName(SEARCH_NAME);
                BluetoothServerSocket socket = mBtAdapter.listenUsingRfcommWithServiceRecord("BluetoothRecipe", params[0]);
                BluetoothSocket connected = socket.accept();
                //Reset the BT adapter name
                mBtAdapter.setName(name);
                return connected;
            } catch (IOException e) {
                e.printStackTrace();
                mBtAdapter.setName(name);
                return null;
            }
        }

        @Override
        protected void onPostExecute(BluetoothSocket socket) {
            if(socket == null) {
                return;
            }
            mBtSocket = socket;
            ConnectedTask task = new ConnectedTask();
            task.execute(mBtSocket);
        }

    }

    //AsyncTask to receive a single line of data and post
    private class ConnectedTask extends AsyncTask<BluetoothSocket,Void,String> {

        @Override
        protected String doInBackground(BluetoothSocket... params) {
            InputStream in = null;
            OutputStream out = null;
            try {
                //Send your data
                out = params[0].getOutputStream();
                out.write(emailField.getText().toString().getBytes());
                //Receive the other's data
                in = params[0].getInputStream();
                byte[] buffer = new byte[1024];
                in.read(buffer);
                //Create a clean string from results
                String result = new String(buffer);
                //Close the connection
                mBtSocket.close();
                return result.trim();
            } catch (Exception exc) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {

            Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            setProgressBarIndeterminateVisibility(false);
        }

    }

    // The BroadcastReceiver that listens for discovered devices
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(TextUtils.equals(device.getName(), SEARCH_NAME)) {
                    //Matching device found, connect
                    mBtAdapter.cancelDiscovery();
                    try {
                        mBtSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                        mBtSocket.connect();
                        ConnectedTask task = new ConnectedTask();
                        task.execute(mBtSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "Error connecting to remote", Toast.LENGTH_SHORT).show();
                    }
                }
                //When discovery is complete
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
            }

        }
    };
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Build a UI Completely in Code

UI Basics (221/474)
« Previous

Build a UI Completely in Code

Description

The first example demonstrates how to build the UI entirely in code.

Example

Generate a project from Android Studio, cut and paste the following code to the MainActivity.java.

package com.java2s.app;
//from  w w w.j av  a2s .c o  m
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LinearLayout nameContainer = new LinearLayout(this);
        LinearLayout addressContainer = new LinearLayout(this);
        LinearLayout parentContainer = new LinearLayout(this);

        nameContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        nameContainer.setOrientation(LinearLayout.HORIZONTAL);

        TextView nameLbl = new TextView(this);
        nameLbl.setText("Name: ");

        TextView nameValue = new TextView(this);
        nameValue.setText("Java2s.com");

        nameContainer.addView(nameLbl);
        nameContainer.addView(nameValue);

        addressContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        addressContainer.setOrientation(LinearLayout.VERTICAL);

        TextView addrLbl = new TextView(this);
        addrLbl.setText("Address:");

        TextView addrValue = new TextView(this);
        addrValue.setText("Main Street");

        addressContainer.addView(addrLbl);
        addressContainer.addView(addrValue);

        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        parentContainer.addView(nameContainer);
        parentContainer.addView(addressContainer);

        setContentView(parentContainer);
    }
}
Build a UI Completely in Code

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Build a UI Completely in XML

UI Basics (222/474)
« Previous

Build a UI Completely in XML

Description

XML layout files are stored under the resources (/res/) directory in a folder called layout.

Example

<?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">
    <!-- NAME CONTAINER -->//ww w .  j av  a2s . c  o  m
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name:" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Java2s.com" />

    </LinearLayout>

    <!-- ADDRESS CONTAINER -->
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Address:" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Main Street" />
    </LinearLayout>

</LinearLayout>
Build a UI Completely in XML

Note

The following java code references the layout setContentView(R.layout.main).

package com.java2s.app;
//w  w  w.jav a 2s .co  m
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Build a UI in XML with Code

UI Basics (223/474)
« Previous

Build a UI in XML with Code

Description

You can build layouts in XML and then use code to populate the dynamic data.

Example

Creating a User Interface in XML with IDs

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- NAME CONTAINER -->/*from  ww w. ja  va2s .co m*/
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name" />

        <TextView
            android:id="@+id/nameValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
    <!-- ADDRESS CONTAINER -->
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name" />

        <TextView
            android:id="@+id/addrValue"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

The actual strings for these TextViews will come from our strings.xml file in the /res/values folder. The following code shows what our strings.xml file might look like.

<?xml version="1.0" encoding="utf-8"?>
<resources>/*from  w  w  w.j  a  v a2 s .  c o  m*/

    <string name="app_name">java2s.com</string>
    <string name="hello_world">java2s.com</string>
    <string name="action_settings">Settings</string>

</resources>

Referring to Controls in Resources at Runtime

/*ww  w  .j a  va  2  s. co  m*/
package com.java2s.app;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView nameValue = (TextView)findViewById(R.id.nameValue);
        nameValue.setText("Main");
        TextView addrValue = (TextView)findViewById(R.id.addrValue);
        addrValue.setText("Street");

    }
}
Build a UI in XML with Code

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Button with three state images

Button (246/474)
« Previous

Button with three state images

Description

We can set image to a button in state of pressed, focused and normal by using a selector.

The selector is a simple XML file that resides in the /res/drawable folder.

The content of a selector file will look like the following.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
     <item android:state_focused="true"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
     <item android:drawable="@drawable/icon" /> <!-- default -->
</selector>//from   w w  w.j  av  a2s  . co  m

Note

First, you do not specify a <resources> tag as in values XML files.

The order of the button images is important. Android will test each item in the selector, in order, to see if it matches.

The normal image should be last so it is used only if the button is not pressed and if the button does not have focus.

If the normal image was listed first, it would always match and be selected even if the button is pressed or has focus.

The drawables you refer to must exist in the /res/drawables folder.

In the definition of your button in the layout XML file, set the android:src property to the selector XML file as if it were a regular drawable.

<Button   ...    android:src="@drawable/imagebuttonselector"    ...   />

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Button XML attribute click handler

Button (243/474)
« Previous

Button XML attribute click handler

Description

We can use xml attribute to specify click event handler for a button.

The following code shows the XML for a Button where you specify an attribute for the handler, plus the Java code that is the click handler.

<Button   ...
          android:onClick="myClickHandler"
          ...  />

Java code to handle the click event.

public void myClickHandler(View target) {
    switch(target.getId()) {
       case R.id.button1:
       ...

The handler method will be called with target set to the View object representing the button that was clicked.

The switch statement in the click handler method uses the resource IDs of the buttons to select the logic to run.

In this way you won't have to explicitly create each Button object in your code, and you can reuse the same method across multiple buttons.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*from   w  ww .  ja v  a 2s .  c  om*/
    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OK"
        android:onClick="myClickHandler"
        />

</LinearLayout>

The following Java code implements the action listener.

package com.java2s.app;
// www  .  j  a  va 2s  .c o m
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    public void myClickHandler(View target) {
        System.out.println("java2s.com event");
        if(target.getId() == R.id.myButton) {

        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Capture an Image and save to external storage

Media (165/474)
« Previous

Capture an Image and save to external storage

Description

The following code shows how to Capture an Image and save to external storage.

Example

Register permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/capture"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take a Picture"
  />
  <ImageView
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="centerInside"
  />
</LinearLayout>

Main activity Java code

import java.io.File;
import java.io.FileInputStream;
/*from  w w w. j  a v  a2 s  . com*/
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MyActivity extends Activity {

    private static final int REQUEST_IMAGE = 100;

    Button captureButton;
    ImageView imageView;
    File destination;

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

        captureButton = (Button)findViewById(R.id.capture);
        captureButton.setOnClickListener(listener);

        imageView = (ImageView)findViewById(R.id.image);

        destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
            //Bitmap userImage = (Bitmap)data.getExtras().get("data");
            try {
                FileInputStream in = new FileInputStream(destination);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 10; //Downsample 10x
                Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
                imageView.setImageBitmap(userImage);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //Add extra to save full-image somewhere
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
            Toast.makeText(MyActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
            startActivityForResult(intent, REQUEST_IMAGE);
        }
    };
}
Capture an Image and save to external storage

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Change activity orientation

Activity (67/474)
« Previous

Change activity orientation

Description

The following code shows how to Change activity orientation.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ToggleButton
    android:id="@+id/toggleButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Lock"
    android:textOn="LOCKED"
  />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
/*w ww. j a v a  2 s  .com*/
public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton);
        if( getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED ) {
            toggle.setChecked(true);
        } else {
            toggle.setChecked(false);
        }
        toggle.setOnCheckedChangeListener(listener);
    }

    OnCheckedChangeListener listener = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int current = getResources().getConfiguration().orientation;
            if(isChecked) {
                switch(current) {
                case Configuration.ORIENTATION_LANDSCAPE:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                case Configuration.ORIENTATION_PORTRAIT:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                default:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
            }
        }
    };

}
Change activity orientation

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Change CheckBox text on select event

CheckBox (263/474)
« Previous

Change CheckBox text on select event

Description

The following code shows how to change CheckBox text on select event.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >/*  w  w w. j a  v a  2s. c  om*/
    <CheckBox
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This checkbox is: unchecked" />

</LinearLayout>

Java code

package com.java2s.app;
//  ww w .  java  2 s . c  o m
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends Activity
        implements CompoundButton.OnCheckedChangeListener {
    CheckBox cb;

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

        cb = (CheckBox) findViewById(R.id.check);
        cb.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
        if (isChecked) {
            cb.setText("This checkbox is: checked");
        } else {
            cb.setText("This checkbox is: unchecked");
        }
    }
}
Change CheckBox text on select event

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Change ListView Divider Height

ListView (368/474)
« Previous

Change ListView Divider Height

Description

The following code shows how to change ListView Divider Height.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#eeeeee"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
//ww w  .  j a  va  2  s . c om

public class MainActivity extends ListActivity {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};
  public static final int EIGHT_ID = Menu.FIRST+1;
  public static final int SIXTEEN_ID = Menu.FIRST+2;
  public static final int TWENTY_FOUR_ID = Menu.FIRST+3;
  public static final int TWO_ID = Menu.FIRST+4;
  public static final int THIRTY_TWO_ID = Menu.FIRST+5;
  public static final int FORTY_ID = Menu.FIRST+6;
  public static final int ONE_ID = Menu.FIRST+7;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items));
    selection=(TextView)findViewById(R.id.selection);

    registerForContextMenu(getListView());
  }

  public void onListItemClick(ListView parent, View v,
                                int position, long id) {
     selection.setText(items[position]);
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
    populateMenu(menu);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    populateMenu(menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    return(applyMenuChoice(item) ||
            super.onOptionsItemSelected(item));
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    return(applyMenuChoice(item) ||
            super.onContextItemSelected(item));
  }

  private void populateMenu(Menu menu) {
    menu.add(Menu.NONE, ONE_ID, Menu.NONE, "1 Pixel");
    menu.add(Menu.NONE, TWO_ID, Menu.NONE, "2 Pixels");
    menu.add(Menu.NONE, EIGHT_ID, Menu.NONE, "8 Pixels");
    menu.add(Menu.NONE, SIXTEEN_ID, Menu.NONE, "16 Pixels");
    menu.add(Menu.NONE, TWENTY_FOUR_ID, Menu.NONE, "24 Pixels");
    menu.add(Menu.NONE, THIRTY_TWO_ID, Menu.NONE, "32 Pixels");
    menu.add(Menu.NONE, FORTY_ID, Menu.NONE, "40 Pixels");
  }

  private boolean applyMenuChoice(MenuItem item) {
    switch (item.getItemId()) {
      case ONE_ID:
        getListView().setDividerHeight(1);
        return(true);

      case EIGHT_ID:
        getListView().setDividerHeight(8);
        return(true);

      case SIXTEEN_ID:
        getListView().setDividerHeight(16);
        return(true);

      case TWENTY_FOUR_ID:
        getListView().setDividerHeight(24);
        return(true);

      case TWO_ID:
        getListView().setDividerHeight(2);
        return(true);

      case THIRTY_TWO_ID:
        getListView().setDividerHeight(32);
        return(true);

      case FORTY_ID:
        getListView().setDividerHeight(40);
        return(true);
    }

    return(false);
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Change ListView Divider Height

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Change the Default Name of the Preferences File

Preference (194/474)
« Previous

Change the Default Name of the Preferences File

Description

The default name of the preferences file saved on the device is com.java2s..., with the package name used as the prefix.

The following code shows how to Change the Default Name of the Preferences File.

Example

We can use the following code to change the name of preferences file.

package com.java2s.myapplication3.app;
/*from  w  w w  .  jav a  2s  . c o m*/
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class MainActivity extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PreferenceManager prefMgr = getPreferenceManager();
        prefMgr.setSharedPreferencesName("appPreferences");

        //load the preferences from an XML file
        addPreferencesFromResource(R.xml.myapppreferences);
    }
}

Code to read the preference.

public void onClickDisplay(View view) {
    /*//from   ww  w .j  av  a  2s.  c o m
    SharedPreferences appPrefs =
            getSharedPreferences("com.java2s.UsingPreferences_preferences",
                    MODE_PRIVATE);
    */
    SharedPreferences appPrefs =
            getSharedPreferences("appPreferences", MODE_PRIVATE);

    DisplayText(appPrefs.getString("editTextPref", ""));
}

public void onClickModify(View view) {
    /*
    SharedPreferences appPrefs =
            getSharedPreferences("com.java2s.UsingPreferences_preferences",
                    MODE_PRIVATE);
    */
    SharedPreferences appPrefs =
            getSharedPreferences("appPreferences", MODE_PRIVATE);

    SharedPreferences.Editor prefsEditor = appPrefs.edit();
    prefsEditor.putString("editTextPref",
            ((EditText) findViewById(R.id.txtString)).getText().toString());
    prefsEditor.commit();
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Change the look of the ProgressBar

ProgressBar (404/474)
« Previous

Change the look of the ProgressBar

Description

The following code shows how to Change the look of the ProgressBar.

Example

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

<ProgressBar android:id="@+id/progressbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@android:style/Widget.ProgressBar.Horizontal" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//  w ww  .j  av a2 s.  c  o m
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
    static int progress;
    ProgressBar progressBar;
    int progressStatus = 0;
    Handler handler = new Handler();

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

        progress = 0;
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        progressBar.setMax(200);

        new Thread(new Runnable()
        {
            public void run()
            {
                while (progressStatus < 200)
                {
                    progressStatus = doSomeWork();
                    handler.post(new Runnable()
                    {
                        public void run() {
                            progressBar.setProgress(progressStatus);
                        }
                    });
                }
                handler.post(new Runnable()
                {
                    public void run()
                    {
                        progressBar .setVisibility(View.GONE);
                    }
                });
            }
            private int doSomeWork()
            {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                return ++progress;
            }
        }).start();
    }
}
Change the look of the ProgressBar

Note

Besides the horizontal style, you can also use the following constants:

  • Widget.ProgressBar.Horizontal
  • Widget.ProgressBar.Small
  • Widget.ProgressBar.Large
  • Widget.ProgressBar.Inverse
  • Widget.ProgressBar.Small.Inverse
  • Widget.ProgressBar.Large.Inverse

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Check if a given string exists in the specified table and column

Database (114/474)
« Previous

Check if a given string exists in the specified table and column

Description

The following code shows how to check if a given string exists in the specified table and column.

Example

import org.xmlpull.v1.XmlPullParser;
//  w w w. ja  v a  2 s.c  o  m
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();

  /** Checks if a given string exists in the specified table and column **/
  public static boolean exists(SQLiteDatabase db, String table, String column, String toCheck) {
    String[] selectionArgs = new String[] { toCheck };
    Cursor cursor = db.rawQuery("SELECT 1 FROM " + table + " where " + column + "=?", selectionArgs);
    boolean exists = cursor.moveToFirst();
    cursor.close();
    return exists;
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Check if any rows match the where clause

Database (115/474)
« Previous

Check if any rows match the where clause

Description

The following code shows how to check if any rows match the where clause.

Example

//from   ww w  .j a  va2s .  co m
import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();

  /** Checks if any rows match the arguments **/
  public static boolean exists(SQLiteDatabase db, String table, String whereClause, String[] whereArgs) {
    Cursor cursor = db.rawQuery("SELECT 1 FROM " + table + " where " + whereClause, whereArgs);
    boolean exists = cursor.moveToFirst();
    cursor.close();
    return exists;
  }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Check Network state

Network (183/474)
« Previous

Check Network state

Description

The following code shows how to Check Network state.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

res\layout\main.xml

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

Reachability.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import java.net.InetAddress;
import java.net.UnknownHostException;
//from  w w  w  .  ja  v  a 2 s  .c o m
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Reachability extends Activity {

    ReachabilityManager mReach;

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

        mReach = ReachabilityManager.getInstance(this);
        mReach.isHostReachable("209.85.227.104")
        Toast.makeText(this, "Network "+mReach.isNetworkReachable()+"\nGoogle "+mReach.isHostReachable(0xD155E368), Toast.LENGTH_SHORT).show();
    }
}
class ReachabilityManager {

    private ConnectivityManager mManager;

    private static ReachabilityManager instance;

    public static synchronized ReachabilityManager getInstance(Context context) {
        if(instance == null) {
            instance = new ReachabilityManager(context);
        }
        return instance;
    }

    private ReachabilityManager(Context context) {
        mManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public boolean isHostReachable(String hostName) {
        try {
            byte[] ipv4 = InetAddress.getByName(hostName).getAddress();
            int address = ipv4[0];
            address += ipv4[1] << 8;
            address += ipv4[2] << 16;
            address += ipv4[3] << 24;
            return isHostReachable(address);
        } catch (UnknownHostException e) {
            return false;
        }
    }

    public boolean isHostReachable(int hostAddress) {
        return ( mManager.requestRouteToHost(ConnectivityManager.TYPE_WIFI, hostAddress)
                || mManager.requestRouteToHost(ConnectivityManager.TYPE_MOBILE, hostAddress) );
    }

    public boolean isNetworkReachable() {
        NetworkInfo current = mManager.getActiveNetworkInfo();
        if(current == null) {
            return false;
        }
        return (current.getState() == NetworkInfo.State.CONNECTED);
    }
}
Check Network state

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Check Which Items Are Selected in ListView

ListView (375/474)
« Previous

Check Which Items Are Selected in ListView

Description

The following code shows how to Check Which Items Are Selected in ListView.

Example

Layout file

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

    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show selected items"
        android:onClick="onClick"/>

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

string resource file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, BasicViews5Activity!</string>
    <string name="app_name">BasicViews5</string>
    <string-array name="presidents_array">
        <item>Dwight D. Eisenhower</item>
        <item>John F. Kennedy</item>
        <item>Lyndon B. Johnson</item>
        <item>Richard Nixon</item>
        <item>Gerald Ford</item>
        <item>Jimmy Carter</item>
        <item>Ronald Reagan</item>
        <item>George H. W. Bush</item>
        <item>Bill Clinton</item>
        <item>George W. Bush</item>
        <item>Barack Obama</item>
    </string-array>
</resources>

Java code

package com.java2s.myapplication3.app;
//w w w .j ava2 s  . c  o m
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity  {

    String[] presidents;

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

        setContentView(R.layout.activity_main);

        ListView lstView = getListView();
        lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        lstView.setTextFilterEnabled(true);

        presidents =getResources().getStringArray(R.array.presidents_array);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_checked, presidents));
    }

    public void onListItemClick(
            ListView parent, View v, int position, long id)
    {
        Toast.makeText (this,
                "You have selected " + presidents [position],
                Toast.LENGTH_SHORT).show();
    }

    public void onClick(View view) {
        ListView lstView = getListView();

        String itemsSelected = "Selected items: \n";
        for (int i=0; i<lstView.getCount(); i++) {
            if (lstView.isItemChecked(i)) {
                itemsSelected += lstView.getItemAtPosition(i) + "\n";
            }
        }
        Toast.makeText (this, itemsSelected, Toast.LENGTH_LONG).show();
    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - CheckBox state change event

CheckBox (264/474)
« Previous

CheckBox state change event

Description

To implement specific logic when a check box is checked or unchecked, you can register for the on-checked event by calling setOnCheckedChangeListener() with an implementation of the OnCheckedChangeListener interface.

Then implement the onCheckedChanged() method, which will be called when the check box is checked or unchecked.

Example

Java code

package com.java2s.app;
/* www.  j ava2s. co  m*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CheckBox fishCB = (CheckBox) findViewById(R.id.fishCB);

        if (fishCB.isChecked()) {
            fishCB.toggle();     // flips the checkbox to unchecked if it was checked
        }
        fishCB.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
                        Log.v("CheckBoxActivity", "The fish checkbox is now "
                                + (isChecked ? "checked" : "not checked"));
                    }
                }
        );
    }
}

XML layout file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//from www .jav  a  2 s .c  o m
    <CheckBox
        android:id="@+id/chickenCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="XML" />

    <CheckBox
        android:id="@+id/fishCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CSS" />

    <CheckBox
        android:id="@+id/steakCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="HTML" />

</LinearLayout>
CheckBox state change event

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Color-Drawable Resources

Resources (31/474)
« Previous

Color-Drawable Resources

Description

In Android, an image is one type of a drawable resource.

Android supports another drawable resource called a color-drawable resource, which is essentially a colored rectangle.

Example

To define a color rectangle, you define an XML element by the node name of drawable in any XML file in the /res/values subdirectory.

The following code shows a couple of color-drawable resource examples.

<resources>
    <drawable name="red_rectangle">#f00</drawable>
    <drawable name="blue_rectangle">#0000ff</drawable>
    <drawable name="green_rectangle">#f0f0</drawable>
</resources>

The following code shows how you can use a color-drawable resource in Java.

/*from   w ww. j  ava2 s .  c o m*/
// Get a drawable
ColorDrawable redDrawable = (ColorDrawable)
         activity.getResources().getDrawable(R.drawable.red_rectangle);

//Set it as a background to a text view
textView.setBackgroundDrawable(redDrawable);

Reference in resource

The following code shows how you can use a color-drawable resource in layout resource.

<resources>
    <drawable name="red_rectangle">#f00</drawable>
    <drawable name="blue_rectangle">#0000ff</drawable>
    <drawable name="green_rectangle">#f0f0</drawable>
</resources>

The following resource file references the defined color drawable defined above.

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textAlign="center"
          android:background="@drawable/red_rectangle"/>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Color Resources

Resources (30/474)
« Previous

Color Resources

Description

You can use reference identifiers to indirectly reference colors.

The color IDs are available under the your-package.R.color namespace.

Android defines a base set of colors, which are accessible through the Android android.R.color namespace.

Example

The following shows some examples of specifying color in an XML resource file.

<resources>
    <color name="red">#f00</color>
    <color name="blue">#0000ff</color>
    <color name="green">#f0f0</color>
    <color name="main_back_ground_color">#ffffff00</color>
</resources>

The entries above need to be in a file residing in the /res/values subdirectory.

The name of the file can be anything you choose.

The following code shows an example of using a color resource in Java code.

int mainBackGroundColor =  activity.getResources.getColor(R.color.main_back_ground_color);

main_back_ground_color is defined in the resource file above.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Common attributes

UI Basics (220/474)
« Previous

Common attributes

Description

Each View and ViewGroup has a set of common attributes.

  • layout_width specifies the width of the View or ViewGroup
  • layout_height specifies the height of the View or ViewGroup
  • layout_marginTop specifies extra space on the top side of the View or ViewGroup
  • layout_marginBottom specifies extra space on the bottom side of the View or ViewGroup
  • layout_marginLeft specifies extra space on the left side of the View or ViewGroup
  • layout_marginRight specifies extra space on the right side of the View or ViewGroup
  • layout_gravity specifies how child Views are positioned
  • layout_weight specifies how much of the extra space in the layout should be allocated to the View
  • layout_x specifies the x-coordinate of the View or ViewGroup
  • layout_y specifies the y-coordinate of the View or ViewGroup

Note

The layout_weight and layout_gravity attributes are applicable only when a View is in either a LinearLayout or a TableLayout.

        <?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:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/hello" />
        </LinearLayout>

For example, the width of the <TextView> element fills the entire width of its parent using the fill_parent constant.

Its height is indicated by the wrap_content constant, which means that its height is the height of its content (in this case, the text contained within it).

If you don't want the <TextView> view to occupy the entire row, you can set its layout_width attribute to wrap_content, like this:

<TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/hello" />

The preceding code will set the width of the view to be equal to the width of the text contained within it.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Communicate Between A Service And An Activity

Service (202/474)
« Previous

Communicate Between A Service And An Activity

Description

The following code shows how to Communicate Between A Service And An Activity.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
/*w w  w .j av  a 2s  .c  o  m*/
import java.net.MalformedURLException;
import java.net.URL;

import android.app.IntentService;
import android.content.Intent;
public class MyService extends IntentService {

    public MyService() {
        super ("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            int result = DownloadFile(new URL("http://www.your server.com/somefile.pdf"));
            //send a broadcast to inform the activity
            //that the file has been downloaded
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
            getBaseContext().sendBroadcast(broadcastIntent);

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

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
//from ww w .j a v a  2 s  .  c  o m

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.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    IntentFilter intentFilter;

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

    @Override
    public void onResume() {
        super.onResume();
        //intent to filter for file downloaded intent
        intentFilter = new IntentFilter();
        intentFilter.addAction("FILE_DOWNLOADED_ACTION");

        //register the receiver
        registerReceiver(intentReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        //unregister the receiver
        unregisterReceiver(intentReceiver);
    }

    public void startService(View view) {
        startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText (getBaseContext(), "File downloaded!",
                    Toast.LENGTH_LONG).show();
        }
    };

}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Compiled and Uncompiled Android Resources

Description

Android supports resources primarily through two types of files: XML files and raw files. The raw files might be images, audio, and video.

Some of the XML file gets compiled into binary format, and the other is copied as-is to the device.

For example, string resource XML files and layout resource XML files are compiled into binary format before becoming part of the installable package.
These XML files have predefined formats where XML nodes can be translated to IDs.

You can compile your own strutured XML to binary formats and use the power of localization. To do this, you can place these XML files in the /res/xml/ subdirectory. In this case, you would use Android-supplied XML readers to read the XML nodes.

But if you place files, including XML files, in the /res/raw/ directory instead, they don't get compiled into binary format. However, because it's a resource, Android generates an ID through R.java.

The resource type for raw files is raw and we can access these file identities through R.raw.some-filename-minus-extension. But, you must use explicit stream-based APIs to read these files. Audio and video files fall into this category.

Since the raw directory is part of the /res/* hierarchy, even these raw audio and video files can use localization and ID generation like all other resources.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Config ListView layout in XML

ListView (369/474)
« Previous

Config ListView layout in XML

Description

The following code shows how to Config ListView layout in XML.

Example

Main activity layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

layout/row.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="horizontal"
>
  <ImageView
    android:id="@+id/icon"
    android:layout_width="22px"
    android:paddingLeft="2px"
    android:paddingRight="2px"
    android:paddingTop="2px"
    android:layout_height="wrap_content"
    android:src="@drawable/ok"
  />
  <TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="44sp"
  />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
//  w  w w.ja v  a  2  s  .c o m
public class MainActivity extends ListActivity {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue",
          "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new ArrayAdapter<String>(this,
                        R.layout.row, R.id.label,
                        items));
    selection=(TextView)findViewById(R.id.selection);
  }

  public void onListItemClick(ListView parent, View v,
                              int position,  long id) {
     selection.setText(items[position]);
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Config ListView layout in XML

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Connect Layout xml to Java code

UI Basics (224/474)
« Previous

Connect Layout xml to Java code

Description

The code that connects the activity to the UI (main_layout_xml_file.xml) is the setContentView() method:

Example

/*from w w  w  .java  2s  .c o  m*/
package com.java2s.app;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Add the following code in bold to the res/layout/ your main xml file for layout:

<?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" >
//from  www .  java  2  s  .co  m
  <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/hello" />

  <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="This is my first Android Application!" />

  <Button
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="And this is a clickable button!" />

</LinearLayout>
Connect Layout xml to Java code

Note

R.layout.main refers to the main.xml file located in the res/layout folder.

As you add additional XML files to the res/layout folder, the filenames will automatically be generated in the R.java file.

The onCreate() method is one of many methods that are fired when an activity is loaded.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Connect to the web to download content

Network (174/474)
« Previous

Connect to the web to download content

Description

The following code shows how to Connect to the web to download content.

Example

Add the following statement to the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main Activity Java code

package com.java2s.myapplication3.app;
//from  w w  w  .  j a  v a2s.com

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.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {
    private InputStream OpenHttpConnection(String urlString) throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex)
        {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;
    }

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

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Consume Json Services

Network (182/474)
« Previous

Consume Json Services

Description

JSON is a lightweight data-interchange format that is easy for humans to read and write.

The following lines of code show what a JSON message looks like:

[
      {
          "Id":"1",
          "Date":"2014-03 14",
          "Time":"12:19:47"
      },
      {
          "Id":"32",
          "Date":"2008-03-14",
          "Time":"22:43:09"
      }
]

The information is represented as a collection of key/value pairs. Each key/value pair is grouped into an ordered list of objects.

The following code shows how to Consume Json Services.

Example

AndroidManifest.xml file:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".JSONActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main Activity Java code

package com.java2s.myapplication3.app;
/* w w  w.  j av  a  2 s  .c o m*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity  {

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return readJSONFeed(urls[0]);
        }

        protected void onPostExecute(String result) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                Log.i("JSON", "Number of surveys in feed: " +
                        jsonArray.length());

                //---print out the content of the json feed---
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Toast.makeText (getBaseContext(), jsonObject.getString("appeId") +
                                    " - " + jsonObject.getString("inputTime"),
                            Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ReadJSONFeedTask().execute(
                "http://your address.html");
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Content provider MIME type

Content Provider (98/474)
« Previous

Content provider MIME type

Description

A content provider has an added responsibility to return the MIME type for a given URI.

A content provider exposes internal data as a service. Its output is like a result set from a JDBC statement. The caller should know the structure of the rows and columns returned.

A content provider allows you to determine the MIME type of the data represented by the URI.

Example

MIME types work in Android similarly to how they work in HTTP.

You get the MIME type for a given URI from a provider.

The MIME type returned is a two-part string identifying its MIME type according to the standard web MIME conventions.

A MIME type has two parts: a type and a subtype. Here are some examples of well-known MIME-type pairs:

text/html//  ww  w . j av a  2  s.com
text/css
text/xml
text/vnd.curl
application/pdf
application/rtf
application/vnd.ms-excel

You can see a complete list of registered types and subtypes at the Internet Assigned Numbers Authority (IANA) web site:

http://www.iana.org/assignments/media-types/

Type and sub types

The primary registered content types are

application
audio
example
image
message
model
multipart
text
video

Each of these primary types has subtypes.

If a vendor has proprietary data formats, the subtype name begins with vnd.

For example, Microsoft Excel spreadsheets are identified by the subtype vnd.ms-excel.

Some subtypes start with x-; these are nonstandard subtypes that don't have to be registered.

Here are a few examples:

application/x-tar
audio/x-aiff
video/x-msvideo

Android MIME type

Android follows a similar convention to define MIME types.

The vnd in Android MIME types indicates that these types and subtypes are nonstandard, vendor-specific forms.

The Android MIME type for each content type has two forms: one for a specific record and one for multiple records.

For a single record, the MIME type looks like this:

vnd.android.cursor.item/vnd.yourcompanyname.contenttype

For a collection of records or rows, the MIME type looks like this:

vnd.android.cursor.dir/vnd.yourcompanyname.contenttype

Here are a couple of examples:

//One single note//from w  ww  . j a  va 2  s .  c  o  m
vnd.android.cursor.item/vnd.google.note

//A collection or a directory of notes
vnd.android.cursor.dir/vnd.google.note

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Content provider URL

Content Provider (97/474)
« Previous

Content provider URL

Description

Content providers provide REST-like URLs to retrieve or manipulate data.

Content URIs in Android look similar to HTTP URIs, except that they start with content and have the general form

content://*/*/*

or

content://authority-name/path-segment1/path-segment2/etc...

Example

The URI to identify a directory or a collection of notes in the NotePadProvider database is

content://com.google.provider.NotePad/Notes

The URI to identify a specific note is

content://com.google.provider.NotePad/Notes/#

where # is the id of a particular note.

Here's an example URI that identifies a note numbered 9 in a database of notes:

content://com.google.provider.NotePad/notes/9

After content: the URI contains a unique identifier for the authority, which is used to locate the provider in the provider registry.

In the preceding example, com.google.provider.NotePad is the authority portion of the URI.

/notes/9 is the path section of the URI that is specific to each provider.

The notes and 9 portions of the path section are called path segments.

Each provider should interpret the path section and path segments of the URIs.

Example 2

The following code lists examples of URIs that some data providers accept:

content://media/internal/images
content://media/external/images
content://contacts/people/
content://contacts/people/9
/*  w w  w  . jav a2 s. c  o  m*/

media (content://media) and contacts (content://contacts) don't have a fully qualified structure.

A content provider's URIs also resemble the names of stored procedures in a database.

The provider is also expected to alter content at this URI using any of the state-change methods: insert, update, or delete.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Content-provider vs Others

Content Provider (99/474)
« Previous

Content-provider vs Others

Description

Content-provider abstraction is required only if you want to share data externally or between applications.

Internal

For internal data access, an application can use the following:

  • Preferences: A set of key/value pairs that you can persist to store application preferences
  • Files: Files internal to applications
  • SQLite: SQLite databases
  • Network : retrieve or store data externally through the Internet via HTTP services

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Context Menu

Menu (390/474)
« Previous

Context Menu

Description

A context menu is associated with a view on an activity, and it is displayed when the user taps and holds an item.

To associate a context menu with a view, use the setOnCreateContextMenuListener() method of that particular view.

The following Try It Out shows how you can associate a context menu with a Button view.

Example

Add the following statements to the main.xml file:

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click and hold on it" />

</LinearLayout>

Add the following statements to the MenusActivity.java file:

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/*  w w  w. j ava2s. c  o m*/
public class MenusActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View view,
    ContextMenuInfo menuInfo)
    {
         super.onCreateContextMenu(menu, view, menuInfo);
         CreateMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
         return MenuChoice(item);
    }
    private void CreateMenu(Menu menu)
    {
        MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
        {
            mnu1.setAlphabeticShortcut( 'a');
            mnu1.setIcon(R.drawable.ic_launcher);
        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
        {
            mnu2.setAlphabeticShortcut( 'b');
            mnu2.setIcon(R.drawable.ic_launcher);
        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
        {
            mnu3.setAlphabeticShortcut( 'c');
            mnu3.setIcon(R.drawable.ic_launcher);
        }
        MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
        {
            mnu4.setAlphabeticShortcut( 'd');
        }
        menu.add(0, 4, 4, "Item 5");
        menu.add(0, 5, 5, "Item 6");
        menu.add(0, 6, 6, "Item 7");
    }

    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId()) {
        case 0:
            Toast.makeText (this, "You clicked on Item 1",
                Toast.LENGTH_LONG).show();
            return true;
        case 1:
            Toast.makeText (this, "You clicked on Item 2",
                Toast.LENGTH_LONG).show();
            return true;
        case 2:
            Toast.makeText (this, "You clicked on Item 3",
                Toast.LENGTH_LONG).show();
            return true;
        case 3:
          Toast.makeText (this, "You clicked on Item 4",
              Toast.LENGTH_LONG).show();
          return true;
      case 4:
          Toast.makeText (this, "You clicked on Item 5",
              Toast.LENGTH_LONG).show();
          return true;
      case 5:
          Toast.makeText (this, "You clicked on Item 6",
              Toast.LENGTH_LONG).show();
          return true;
      case 6:
          Toast.makeText (this, "You clicked on Item 7",
              Toast.LENGTH_LONG).show();
          return true;
      }
      return false;
  }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Context menu action handler

Menu (391/474)
« Previous

Context menu action handler

Description

The following code shows how to implement Context menu action handler.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
            android:id="@+id/testText"
          android:text="BEFORE KEYSTROKE DETECTED TEXT!"
          android:textColor="#FFDDAA"
          android:textSize="19px"/>
  <Button android:text="Long-Click Here to Access ContextMenu"
      android:id="@+id/contextButton"
      android:nextFocusUp="@+id/thirdButton"
      android:nextFocusDown="@+id/secondButton"
      android:layout_gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
  <Button android:text="Second Button"
      android:id="@+id/secondButton"
      android:nextFocusUp="@+id/contextButton"
      android:nextFocusDown="@+id/thirdButton"
      android:layout_gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
  <Button android:text="Third Button"
      android:id="@+id/thirdButton"
      android:nextFocusUp="@+id/secondButtonButton"
      android:nextFocusDown="@+id/contextButton"
      android:layout_gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"/>
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;
/*from   w w w  . j ava  2  s  .  co m*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button secondButton = (Button) findViewById(R.id.secondButton);
        registerForContextMenu(secondButton);
        Button thirdButton = (Button) findViewById(R.id.thirdButton);
        registerForContextMenu(thirdButton);
        Button contextButton = (Button) findViewById(R.id.contextButton);
        registerForContextMenu(contextButton);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view,ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, view, menuInfo);
    menu.setHeaderTitle("Android Context Menu");
    menu.add(0, view.getId(), 0, "Invoke Context Function 1");
    menu.add(0, view.getId(), 0, "Invoke Context Function 2");
  }
    @Override
  public boolean onContextItemSelected(MenuItem item) {
         if(item.getTitle()=="Invoke Context Function 1"){contextFunction1(item.getItemId());}
      else if(item.getTitle()=="Invoke Context Function 2"){contextFunction2(item.getItemId());}
      else {return false;}
  return true;
  }
    public void contextFunction1(int id){
      Toast.makeText(this, "function 1 invoked!", Toast.LENGTH_SHORT).show();
    }
    public void contextFunction2(int id){
      Toast.makeText(this, "function 2 invoked!", Toast.LENGTH_SHORT).show();
    }
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_ENTER) {
          textUpdate();
                return true;
        }
      return false;
    }
  public void textUpdate() {
    TextView text = (TextView)findViewById(R.id.testText);
    text.setText("ENTER KEY PRESSED!");
  }
}
Context menu action handler

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Control the Orientation of the Activity

Activity (62/474)
« Previous

Control the Orientation of the Activity

Description

To ensure that your application is displayed in only a certain orientation, you can programmatically force a change in orientation using the setRequestOrientation() method of the Activity class.

import android.content.pm.ActivityInfo;
/*from  w w w .  ja  va2 s  . com*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //---change to landscape mode---
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

You can also use the android:screenOrientation attribute on the <activity> element in AndroidManifest.xml as follows to constrain the activity to a certain orientation:

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".OrientationsActivity"
            android:screenOrientation="landscape" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The activity will not be destroyed and the onCreate() method will not be fired again when the orientation of the device changes.

Following are two other values that you can specify in the android:screenOrientation attribute:

  • portrait - Portrait mode
  • sensor - Based on the accelerometer (default)

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Convert Dp To Px

Layout (337/474)
« Previous

Convert Dp To Px

Description

The formula for converting dp to px (pixels) is as follows:

pixels = dp * (dpi / 160)

where dpi is either 120, 160, 240, or 320.

If the Button on a 235 dpi screen, its actual width is

160 * (240/160) = 240 px.

When run on the 180 dpi emulator, which isregarded as a 160 dpi device, its actual pixel is now 160 * (160/160) = 160 px.

In this case, one dp is equivalent to one px.

You can use the getWidth() method of a View object to get its width in pixels:

public void onClick(View view) {
    Toast.makeText (this,String.valueOf(view.getWidth()),Toast.LENGTH_LONG).show();
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a Button

Button (240/474)
« Previous

Create a Button

Description

The basic button class in Android is android.widget.Button. You use it to handle click events.

Example

The following code shows how to add a button to activity and add click action handler.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/* w w  w. j  a v  a 2 s  .  c  om*/
    <Button android:id="@+id/button1"
        android:text="My Button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java code

package com.java2s.app;
/*  w ww.  j  a va  2  s .c  o  m*/
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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

        Button button1 = (Button) this.findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.java2s.com"));
                startActivity(intent);
            }
        });
    }

}
Create a Button

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a class representing a row in a table with CRUD methods

Database (116/474)
« Previous

Create a class representing a row in a table with CRUD methods

Description

The following code has a class representing a row in a table with CRUD methods.

Example

//from  w ww . j a  va 2s .  com
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * Abstract class used to represent a row in a table. Has CRUD methods, as well
 * as the ability to create the table. Public, non-transient fields of basic
 * types are used as columns.
 **/
public abstract class SqlObject implements Serializable {

  // DATABASE FIELDS
  public long id;

  // DATABASE FIELD NAMES
  public static String ID = "id";

  // UNIMPORTANT CACHE DATA
  private String[] mColNames;

  // CONSTANTS
  private static final String TAG = SqlObject.class.getSimpleName();
  public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";
  public static final String DATE_FORMAT_TAIL = ":ss.SSS";

  // RAW QUERY CONSTANTS
  public static final String CHECK_TABLE_EXISTS = "SELECT distinct tbl_name from sqlite_master where tbl_name=?";

  // SQL TYPES
  public static final String INTEGER = "INTEGER";
  public static final String LONG = "INTEGER";
  public static final String BOOLEAN = "INTEGER";
  public static final String ENUM = "STRING";
  public static final String FLOAT = "FLOAT";
  public static final String STRING = "STRING";
  public static final String DATE = "STRING";
  public static final String OTHER = "STRING";

  public String[] getColNames() {
    if (mColNames != null)
      return mColNames;

    Field[] fields = getClass().getDeclaredFields();
    ArrayList<String> cols = new ArrayList<String>();
    for (int i = 0; i < fields.length; i++) {
      try {
        Field field = fields[i];
        if (isColField(field))
          cols.add(field.getName());
      } catch (Exception e) {
        Log.d(TAG, "Error: couldn't get column names for object = "
            + toString());
      }
    }
    // add ID field
    cols.add(ID);
    mColNames = (String[]) cols.toArray(new String[cols.size()]);
    return mColNames;
  }

  public String getTableName() {
    return this.getClass().getSimpleName();
  }

  // CRUD OPERATIONS

  /**
   * Creates a new entry in the database. Will throw an exception if any data
   * isn't set before now. Extend this method in subclass to do error checking
   * / setup, then call super.create()
   *
   * @throws Exception
   **/
  protected boolean createAndGenerateId(SQLiteDatabase db) {
    ContentValues values = this.toContentValues();
    // we're not setting id when we create this
    values.remove(ID);

    id = db.insert(getTableName(), null, values);
    return (id != -1);
  }

  /**
   * Creates a new entry in the database, including the id field. Will throw
   * an exception if any data isn't set before now. Extend this method in
   * subclass to do error checking / setup, then call super.create()
   *
   * @throws Exception
   **/
  protected boolean createWithId(SQLiteDatabase db) {
    ContentValues values = this.toContentValues();
    return id == db.insert(getTableName(), null, values);
  }

  public boolean read(SQLiteDatabase db, long idToRead) {
    Cursor cursor = db.query(getTableName(), getColNames(), ID + "=?",
        new String[] { Long.toString(idToRead) }, null, null, null);

    if (cursor.moveToFirst()) {
      readFromCursor(cursor);
      cursor.close();
      return true;
    } else {
      Log.d(TAG, "Couldn't find id=" + id + " in the " + getTableName()
          + " table");
      cursor.close();
      return false;
    }
  }

  public void readFromCursor(Cursor cursor) {
    id = cursor.getLong(cursor.getColumnIndex(ID));
    Field[] fields = getColFields();

    for (Field field : fields) {
      try {
        Class<?> type = field.getType();
        if (type.isAssignableFrom(Integer.TYPE)) {
          field.set(this, cursor.getInt(cursor.getColumnIndex(field
              .getName())));
        } else if (type.isAssignableFrom(Boolean.TYPE)) {
          int bool = cursor.getInt(cursor.getColumnIndex(field
              .getName()));
          boolean val = intToBool(bool);
          field.set(this, val);
        } else if (type.isAssignableFrom(Float.TYPE)) {
          field.set(this, cursor.getFloat(cursor.getColumnIndex(field
              .getName())));
        } else if (type.isAssignableFrom(Long.TYPE)) {
          field.set(this, cursor.getLong(cursor.getColumnIndex(field
              .getName())));
        } else if (type.isEnum()) {
          Method valueOf = type.getMethod("valueOf", String.class);
          String enumName = cursor.getString(cursor
              .getColumnIndex(field.getName()));
          if (enumName != null)
            field.set(this, valueOf.invoke(null, enumName));
        } else if (type.isAssignableFrom(String.class)) {
          field.set(this, cursor.getString(cursor
              .getColumnIndex(field.getName())));
        } else if (type.isAssignableFrom(Date.class)) {
          field.set(this, stringToDate(cursor.getString(cursor
              .getColumnIndex(field.getName()))));
        } else {
          throw new Exception("Object: " + field.toString()
              + " isn't one of the supported type");
        }
      } catch (Exception e) {
        Log.d(TAG,
            "Error reading object\n" + toString() + ": \n\n"
                + e.toString());
      }
    }
  }

  public boolean update(SQLiteDatabase db) {
    ContentValues values = this.toContentValues();
    return db.update(getTableName(), values, ID + "=?",
        new String[] { Long.toString(id) }) > 0;
  }

  public boolean delete(SQLiteDatabase db) {
    if (!DbUtils.exists(db, getTableName(), ID, Long.toString(id))) {
      Log.d(TAG, "Tried to delete a nonexistent " + ID + "=" + id);
      return false;
    } else {
      return db.delete(getTableName(), ID + "=?",
          new String[] { Long.toString(id) }) == 1;
    }
  }

  // TABLE OPERATIONS

  /** Creates a table for these objects if one doesn't already exist **/
  public boolean createTable(SQLiteDatabase db) {
    Field[] fields = getColFields();
    String statement = "CREATE TABLE IF NOT EXISTS " + getTableName()
        + " ( ";
    statement += ID + " INTEGER PRIMARY KEY, ";
    for (Field col : fields) {
      // skip id (although I don't think it will show up in subclasses)
      if (col.getName().equals(ID))
        continue;

      // handle other types
      statement += col.getName() + " " + getFieldSqlType(col) + ", ";
    }
    // remove final comma (,)
    statement = statement.substring(0, statement.length() - 2);
    statement += " ) ";
    db.execSQL(statement);
    return true;
  }

  /** Check if the table this object defines exists **/
  public boolean tableExists(SQLiteDatabase db) {
    Cursor c = db.rawQuery(CHECK_TABLE_EXISTS,
        new String[] { getTableName() });
    return (c != null && c.moveToFirst());
  }
  // UTIL METHODS
  public static String dateToString(Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
    return sdf.format(date);
  }

  public static Date stringToDate(String date) {
    date += DATE_FORMAT_TAIL;
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
    Date toReturn = null;
    try {
      toReturn = sdf.parse(date);
    } catch (ParseException e) {
      Log.d(TAG, "Error parsing date=" + date);
    }
    return toReturn;
  }

  public int boolToInt(boolean b) {
    return b ? 1 : 0;
  }

  public boolean intToBool(int i) {
    return i == 1;
  }

  // PROTECTED UTILS

  private boolean isColField(Field toCheck) {
    int modifiers = toCheck.getModifiers();
    return (!Modifier.isTransient(modifiers)
        && Modifier.isPublic(modifiers) && !Modifier
          .isStatic(modifiers));
  }

  private Field[] getColFields() {
    // Field[] fields = getClass().getDeclaredFields();
    Field[] fields = getClass().getFields();
    List<Field> colFields = new ArrayList<Field>();

    for (int i = 0; i < fields.length; i++) {
      try {
        Field field = fields[i];
        if (isColField(field))
          colFields.add(field);
      } catch (Exception e) {
        Log.d(TAG,
            "Error getting ColFields " + toString() + ": "
                + e.toString());
      }
    }

    return (Field[]) colFields.toArray(new Field[colFields.size()]);
  }

  protected String getFieldSqlType(Field field) {
    try {
      Object toSave = field.get(this);
      if (toSave instanceof Integer) {
        return INTEGER;
      } else if (toSave.getClass().isEnum()) {
        return ENUM;
      } else if (toSave instanceof Boolean) {
        return BOOLEAN;
      } else if (toSave instanceof Float) {
        return FLOAT;
      } else if (toSave instanceof Long) {
        return LONG;
      } else if (toSave instanceof String) {
        return STRING;
      } else if (toSave instanceof Date) {
        return DATE;
      } else {
        return OTHER;
      }
    } catch (Exception e) {
      Log.d(TAG, "Error getting FieldSqlType: " + field.toString());
      return OTHER;
    }
  }

  protected ContentValues toContentValues() {
    ContentValues values = new ContentValues();
    Field[] fields = getColFields();

    for (Field field : fields) {
      try {
        Object toSave = field.get(this);
        if (toSave == null)
          continue; // object is null, don't put it in ContentValues

        if (toSave instanceof Integer) {
          values.put(field.getName(), (Integer) toSave);
        } else if (toSave.getClass().isEnum()) {
          values.put(field.getName(), toSave.toString());
        } else if (toSave instanceof Boolean) {
          values.put(field.getName(), (Boolean) toSave);
        } else if (toSave instanceof Float) {
          values.put(field.getName(), (Float) toSave);
        } else if (toSave instanceof Long) {
          values.put(field.getName(), (Long) toSave);
        } else if (toSave instanceof String) {
          values.put(field.getName(), (String) toSave);
        } else if (toSave instanceof Date) {
          values.put(field.getName(), dateToString((Date) toSave));
        } else {
          values.put(field.getName(), toSave.toString());
        }

      } catch (Exception e) {
        Log.d(TAG,
            "Error saving object " + toString() + ": "
                + e.toString());
        throw new RuntimeException("Error creating object="
            + getTableName(), e);
      }
    }

    // put id in
    values.put(ID, id);

    return values;
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a DatePicker

Clock Date Picker (271/474)
« Previous

Create a DatePicker

Description

You use the DatePicker control to select a date.

Example

<?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">
//from  w  w w .j  a  v a2  s  .  c  o m
    <TextView
        android:id="@+id/dateDefault"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

The following code sets the DatePicker with Date.

/*from   w w  w .  j  a  v  a 2  s.  c o m*/
package com.java2s.app;

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

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView dateDefault = (TextView) findViewById(R.id.dateDefault);

        DatePicker dp = (DatePicker) this.findViewById(R.id.datePicker);
        // subtract 1 from December (12) to set it to December
        dp.init(2008, 11, 10, null);
        // The month, and just the month, is zero-based.
        dateDefault.setText("Date defaulted to " + (dp.getMonth() + 1) + "/" +
                dp.getDayOfMonth() + "/" + dp.getYear());

    }
}
Create a DatePicker

Note

For the month, the internal value is zero-based, which means that January is 0 and December is 11.

If you do not set values for these controls, the default values will be the current date and time as known to the device.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a DigitalClock

Clock Date Picker (269/474)
« Previous

Create a DigitalClock

Description

The digital clock supports seconds in addition to hours and minutes.

The control is just for displaying the current time.

Example

The following layout xml has a DigitalClock widget.

<?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">
/*from w  ww  .  java2s . c o  m*/
    <DigitalClock
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Java code

package com.java2s.app;
/*from  w ww. j a v a2s  . c o m*/
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Create a DigitalClock

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a MapView

Map (386/474)
« Previous

Create a MapView

Description

The com.google.android.maps.MapView control can display a map.

You can instantiate this control either via XML layout or code, but the activity that uses it must extend MapActivity.

MapActivity takes care of multithreading requests to load a map, perform caching, and so on.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
// w  w  w.j  a  va 2 s .c om
    <com.google.android.maps.MapView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="myAPIKey"
        />

</LinearLayout>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a RadioButton

RadioButton (407/474)
« Previous

Create a RadioButton

Description

A radio button gives the users several choices and users can only selec a single item.

Radio buttons generally belong to a group, and each group can only have one item selected at a time.

To create a group of radio buttons in Android, first create a RadioGroup, and then populate the group with radio buttons.

Example

In Android, you implement a radio group using android.widget.RadioGroup and a radio button using android.widget.RadioButton.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/rBtnGrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/chRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="XML" />

        <RadioButton
            android:id="@+id/fishRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="HTML" />

        <RadioButton
            android:id="@+id/stkRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CSS" />

    </RadioGroup>

</LinearLayout>
Create a RadioButton

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a TableLayout with only one row

Layout (360/474)
« Previous

Create a TableLayout with only one row

Description

The following code shows how to Create a TableLayout with only one row.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TableRow>
        <TextView android:id="@+id/text_view_1"
            android:layout_width="150px"
            android:layout_height="100px"
            android:background="@android:color/darker_gray"
            />
        <TextView android:id="@+id/text_view_2"
            android:layout_width="150px"
            android:layout_height="100px"
            android:background="@android:color/white"
            />
    </TableRow>
</TableLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
//from   w  w w  .  j  av a2s .  co  m
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
    }
}
Create a TableLayout with only one row

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a TimePicker

Clock Date Picker (274/474)
« Previous

Create a TimePicker

Description

You use the TimePicker control to pick a time.

Example

The following xml layout defines a TimePicker.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*from ww w.j a v a2  s.  com*/
    <TextView
        android:id="@+id/timeDefault"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The following code sets TimePicker with Time.

package com.java2s.app;
/* w w  w .j  a  v a 2 s.  co m*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends Activity {

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

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

        TimePicker tp = (TimePicker)this.findViewById(R.id.timePicker);

        java.util.Formatter timeF = new java.util.Formatter();
        timeF.format("Time defaulted to %d:%02d", tp.getCurrentHour(),
                tp.getCurrentMinute());
        timeDefault.setText(timeF.toString());

        tp.setIs24HourView(true);
        tp.setCurrentHour(new Integer(10));
        tp.setCurrentMinute(new Integer(10));
    }

}
Create a TimePicker

Note

For the TimePicker, the number of hours and minutes is set to 10. TimePicker supports 24-hour view.

If you do not set values for these controls, the default values will be the current date and time as known to the device.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a Tip Calculator

EditText (288/474)
« Previous

Create a Tip Calculator

Description

The following code shows how to create a Tip Calculator. It shows

  • how to get value from EditText.
  • how to set value to TextView.
  • how to format a number.
  • how to catch exception and log it.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >/*from www.  j a v  a  2  s  .  co m*/
    <EditText
        android:id="@+id/mealprice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:autoText="true"
        />
    <Button
        android:id="@+id/calculate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate Tip"
        />
    <TextView
        android:id="@+id/answer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        />

</LinearLayout>

Java code

package com.java2s.app;
//from ww w.jav a2  s  .  co m
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.text.NumberFormat;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText mealpricefield = (EditText) findViewById(R.id.mealprice);
        final TextView answerfield = (TextView) findViewById(R.id.answer);

        final Button button = (Button) findViewById(R.id.calculate);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                try {
                    // grab the meal price from the UI
                    String mealprice = mealpricefield.getText().toString();
                    String answer = "";
                    if (mealprice.indexOf("$") == -1) {
                        mealprice = "$" + mealprice;
                    }
                    float fmp = 0.0F;
                    NumberFormat nf = java.text.NumberFormat.getCurrencyInstance();
                    fmp = nf.parse(mealprice).floatValue();
                    //  20% tip
                    fmp *= 1.2;
                    answer = "Full Price, Including 20% Tip: " + nf.format(fmp);
                    answerfield.setText(answer);
                } catch (java.text.ParseException pe) {
                    Log.i("java2s.com", "Parse exception caught");
                    answerfield.setText("Failed to parse amount?");
                } catch (Exception e) {
                    Log.e("java2s.com", "Failed to Calculate Tip:" + e.getMessage());
                    e.printStackTrace();
                    answerfield.setText(e.getMessage());
                }
            }
        });
    }
}
Create a Tip Calculator

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create a Video recorder

Video (451/474)
« Previous

Create a Video recorder

Description

The following code shows how to Create a Video recorder.

Example

Setup permission in manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout xml file

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

    <Button
        android:id="@+id/button_record"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="onRecordClick" />

    <SurfaceView
        android:id="@+id/surface_video"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/button_record" />

</RelativeLayout>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w  ww .  ja  v a 2  s . c o  m*/
import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    private Camera mCamera;
    private MediaRecorder mRecorder;

    private SurfaceView mPreview;
    private Button mRecordButton;

    private boolean mRecording = false;

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

        mRecordButton = (Button) findViewById(R.id.button_record);
        mRecordButton.setText("Start Recording");

        mPreview = (SurfaceView) findViewById(R.id.surface_video);
        mPreview.getHolder().addCallback(this);
        mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mCamera = Camera.open();
        //Rotate the preview display to match portrait
        mCamera.setDisplayOrientation(90);
        mRecorder = new MediaRecorder();
    }

    @Override
    protected void onDestroy() {
        mCamera.release();
        mCamera = null;
        super.onDestroy();
    }

    public void onRecordClick(View v) {
        updateRecordingState();
    }

    /*
     * The order of these methods are important.
     */
    private void initializeRecorder() throws IllegalStateException, IOException   {
        mCamera.unlock();
        mRecorder.setCamera(mCamera);

        mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        File recordOutput = new File(Environment.getExternalStorageDirectory(), "recorded_video.mp4");
        if (recordOutput.exists()) {
            recordOutput.delete();
        }
        CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
        mRecorder.setProfile(cpHigh);
        mRecorder.setOutputFile(recordOutput.getAbsolutePath());

        mRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

        mRecorder.setMaxDuration(50000); // 50 seconds
        mRecorder.setMaxFileSize(5000000); // Approximately 5 megabytes

        mRecorder.prepare();
    }

    private void updateRecordingState() {
        if (mRecording) {
            mRecording = false;
            mRecorder.stop();
            mRecorder.reset();
            mCamera.lock();
            mRecordButton.setText("Start Recording");
        } else {
            try {
                initializeRecorder();
                mRecording = true;
                mRecorder.start();
                mRecordButton.setText("Stop Recording");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) { }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) { }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create AlertDialog from ArrayAdapter

Dialog (283/474)
« Previous

Create AlertDialog from ArrayAdapter

Description

The following code shows how to Create AlertDialog from ArrayAdapter.

Example

Layout activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:minHeight="?android:attr/listPreferredItemHeight">
    <TextView
        android:id="@+id/text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceMedium"/>
    <TextView
        android:id="@+id/text_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceSmall"/>
</RelativeLayout>

Main activity Java code

package com.java2s.myapplication3.app;
//from  w w w.  jav  a2 s.c  om
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity
        implements DialogInterface.OnClickListener, View.OnClickListener {

    private static final String[] ZONES =
            {"Pacific Time", "Mountain Time", "Central Time", "Eastern Time", "Atlantic Time"};
    private static final String[] OFFSETS =
            {"GMT-08:00", "GMT-07:00", "GMT-06:00", "GMT-05:00", "GMT-04:00"};

    Button mButton;
    AlertDialog mActions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Activity");
        mButton = new Button(this);
        mButton.setText("Click for Time Zones");
        mButton.setOnClickListener(this);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_main) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View row = convertView;
                if (row == null) {
                    row = getLayoutInflater().inflate(R.layout.activity_main, parent, false);
                }

                TextView name = (TextView) row.findViewById(R.id.text_name);
                TextView detail = (TextView) row.findViewById(R.id.text_detail);

                name.setText(ZONES[position]);
                detail.setText(OFFSETS[position]);

                return row;
            }

            @Override
            public int getCount() {
                return ZONES.length;
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select Time Zone");
        builder.setAdapter(adapter, this);
        builder.setNegativeButton("Cancel", null);
        mActions = builder.create();

        setContentView(mButton);
    }
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String selected = ZONES[which];
        mButton.setText(selected);
    }
    @Override
    public void onClick(View v) {
        mActions.show();
    }
}
Create AlertDialog from ArrayAdapter

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create an activity and do task with Thread

Thread (441/474)
« Previous

Create an activity and do task with Thread

Description

The following code shows how to Create an activity and do task without Thread.

Example

Main layout xml file

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<Button
    android:id="@+id/btnStartCounter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    android:onClick="startCounter" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
/*from   ww  w . j  av  a  2  s.c  o  m*/
public class MainActivity extends Activity {
    TextView txtView1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtView1 = (TextView) findViewById(R.id.textView1);
    }

    public void startCounter(View view) {
        for (int i=0; i<=1000; i++) {
            txtView1.setText(String.valueOf(i));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                     Log.d("Threading", e.getLocalizedMessage());
                  }
        }
    }
}
Create an activity and do task with Thread

Note

When you run the application and click the Start button, the application is briefly frozen, and after a while you may see the message.

To solve this problem, one option is to wrap the part of the code that contains the loop using a Thread and Runnable class.

You can use the post() method of a View to create another Runnable block to be added to the message queue.

The new Runnable block created will be executed in the UI thread, so it would be safe to execute your application:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
/*from   w w  w  .j  a  v  a  2  s .co  m*/
public class MainActivity extends Activity {
    TextView txtView1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        txtView1 = (TextView) findViewById(R.id.textView1);
    }

        public void startCounter(View view) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<=1000; i++) {
                        final int valueOfi = i;
                        txtView1.post(new Runnable() {
                            public void run() {
                                //UI thread for updating
                                txtView1.setText(String.valueOf(valueOfi));
                            }
                        });

                        //insert a delay
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            Log.d ("Threading", e.getLocalizedMessage());
                        }
                    }
                }
            }).start();
        }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create AnalogClock

Clock Date Picker (268/474)
« Previous

Create AnalogClock

Description

The analog clock in Android is a two-handed clock, with one hand for the hour indicator and the other hand for the minute indicator.

The control is just for displaying the current time.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*from   w  w w  .  jav  a2 s  . c  o m*/
    <AnalogClock
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.app;
//from   ww w  . ja  v  a2 s .  c  om
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Button with code only

Button (241/474)
« Previous

Create Button with code only

Description

The following code shows how to create a Button and add to Activity with code only. It also sets up the on click listener.

Example

package com.java2s.app;
//from w  w w  . ja v a  2s .  c o m
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("OK");
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.v("java2s.com","button clicked");
            }
        });

        setContentView(parentContainer);
    }
}
Create Button with code only

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create button with rounded corner

Button (242/474)
« Previous

Create button with rounded corner

Description

The following code shows how to create button with rounded corner.

Example

res/drawable/button_rounded_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#AAAAAA"/>
    <corners android:radius="15dp"/>
</shape>

Layout xml

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

    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World, MainActivity!"
        android:textColor="#000000"
        android:padding="10dp"
        android:background="@drawable/button_rounded_background"/>

</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
//w w  w  .  java  2 s .  c  om
public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}
Create button with rounded corner

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create CheckBox

CheckBox (265/474)
« Previous

Create CheckBox

Description

The CheckBox control is another two-state button that allows the user to toggle its state.

In Android, you can create a check box by creating an instance of android.widget.CheckBox.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*w w  w.  j  a va  2 s  .c o  m*/
    <CheckBox
        android:id="@+id/chickenCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="XML" />

    <CheckBox
        android:id="@+id/fishCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CSS" />

    <CheckBox
        android:id="@+id/steakCB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="HTML" />

</LinearLayout>

Java code

package com.java2s.app;
//from  w w w.j  av a  2s  . com
import android.app.Activity;
import android.os.Bundle;

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

    }
}

You manage the state of a check box by calling setChecked() or toggle(). You can obtain the state by calling isChecked().

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Content Provider to read from Asset folder

Content Provider (102/474)
« Previous

Create Content Provider to read from Asset folder

Description

The following code shows how to Create Content Provider to read from Asset folder.

Example

Register content provider in manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:name=".MyProvider"
        android:authorities="com.java2s.myapplication3.app.imageprovider">
    </provider>

    </application>

</manifest>

Layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="20dip"
    android:layout_gravity="center_horizontal"
  />
  <ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="50dip"
    android:layout_gravity="center_horizontal"
  />
  <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
</LinearLayout>

Main activity Java code

// ww  w. ja v a 2 s.c o  m
package com.java2s.myapplication3.app;

import java.io.FileNotFoundException;
import java.io.InputStream;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MainActivity extends Activity implements
        LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {
    private static final int LOADER_LIST = 100;
    SimpleCursorAdapter mAdapter;

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

        mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
                null, new String[]{MyProvider.COLUMN_NAME}, new int[]{android.R.id.text1}, 0);

        ListView list = (ListView)findViewById(R.id.list);
        list.setOnItemClickListener(this);
        list.setAdapter(mAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        //Seek the cursor to the selection
        Cursor c = mAdapter.getCursor();
        c.moveToPosition(position);

        //Load the name column into the TextView
        TextView tv = (TextView)findViewById(R.id.name);
        tv.setText(c.getString(1));

        ImageView iv = (ImageView)findViewById(R.id.image);
        try {
            //Load the content from the image column into the ImageView
            InputStream in = getContentResolver().openInputStream(Uri.parse(c.getString(2)));
            Bitmap image = BitmapFactory.decodeStream(in);
            iv.setImageBitmap(image);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] projection = new String[]{"_id",
                MyProvider.COLUMN_NAME,
                MyProvider.COLUMN_IMAGE};
        return new CursorLoader(this, MyProvider.CONTENT_URI,
                projection, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

Java code for image content provider

package com.java2s.myapplication3.app;
/* w  w w.  jav a2s .c  om*/
import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;

public class MyProvider extends ContentProvider {

    public static final Uri CONTENT_URI = Uri.parse("content://com.examples.share.imageprovider");

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "nameString";
    public static final String COLUMN_IMAGE = "imageUri";
    /* Default projection if none provided */
    private static final String[] DEFAULT_PROJECTION = {
            COLUMN_ID, COLUMN_NAME, COLUMN_IMAGE
    };

    private String[] mNames, mFilenames;

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("This ContentProvider is read-only");
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        throw new UnsupportedOperationException("This ContentProvider is read-only");
    }

    @Override
    public boolean onCreate() {
        mNames = new String[] {"John Doe", "Jane Doe", "Jill Doe"};
        mFilenames = new String[] {"logo1.png", "logo2.png", "logo3.png"};
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        //Return all columns if no projection given
        if (projection == null) {
            projection = DEFAULT_PROJECTION;
        }
        MatrixCursor cursor = new MatrixCursor(projection);

        for(int i = 0; i < mNames.length; i++) {
            //Insert only the columns they requested
            MatrixCursor.RowBuilder builder = cursor.newRow();
            for(String column : projection) {
                if(COLUMN_ID.equals(column)) {
                    //Use the array index as a unique id
                    builder.add(i);
                }
                if(COLUMN_NAME.equals(column)) {
                    builder.add(mNames[i]);
                }
                if(COLUMN_IMAGE.equals(column)) {
                    builder.add(Uri.withAppendedPath(CONTENT_URI, String.valueOf(i)));
                }
            }
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("This ContentProvider is read-only");
    }

    @Override
    public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
        int requested = Integer.parseInt(uri.getLastPathSegment());
        AssetFileDescriptor afd;
        AssetManager manager = getContext().getAssets();
        //Return the appropriate asset for the requested item
        try {
            switch(requested) {
                case 0:
                case 1:
                case 2:
                    afd = manager.openFd(mFilenames[requested]);
                    break;
                default:
                    afd = manager.openFd(mFilenames[0]);
                    break;
            }
            return afd;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create custom animation

Animation (237/474)
« Previous

Create custom animation

Description

The following code shows how to Create custom animation.

Example

//w ww  . ja va2s . c  o  m
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

package com.java2s.myapplication3.app;

import android.content.Context;
import android.graphics.Canvas;
import android.view.View;

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

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class MainActivity extends Activity {

    private DrawView mDrawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Display display = getWindowManager().getDefaultDisplay();
        mDrawView = new DrawView(this);
        mDrawView.height = display.getHeight();
        mDrawView.width = display.getWidth();

        setContentView(mDrawView);
    }
}

class Rectangle extends View {
    public static final int MAX_SIZE = 40;
    private static final int ALPHA = 255;
    private int mCoordX = 0;
    private int mCoordY = 0;
    private int mRealSize = 40;
    private int mSpeedX = 3;
    private int mSpeedY = 3;

    private boolean goRight = true;
    private boolean goDown = true;
    private DrawView mDrawView;

    private Paint mInnerPaint;
    private RectF mDrawRect;

    public Rectangle(Context context, DrawView drawView) {
        super(context);
        mDrawView = drawView;

        mInnerPaint = new Paint();

        mDrawRect = new RectF();

    /* Red is default */
        mInnerPaint.setARGB(ALPHA, 255, 0, 0);
        mInnerPaint.setAntiAlias(true);
    }

    public void setARGB(int a, int r, int g, int b) {
        mInnerPaint.setARGB(a, r, g, b);
    }

    public void setX(int newValue) {
        mCoordX = newValue;
    }

    public void setY(int newValue) {
        mCoordY = newValue;
    }

    public void move() {
        moveTo(mSpeedX, mSpeedY);
    }

    private void moveTo(int goX, int goY) {

        // check the borders, and set the direction if a border has reached
        if (mCoordX > (mDrawView.width - MAX_SIZE)) {
            goRight = false;
        }

        if (mCoordX < 0) {
            goRight = true;
        }

        if (mCoordY > (mDrawView.height - MAX_SIZE)) {
            goDown = false;
        }
        if (mCoordY < 0) {
            goDown = true;
        }

        // move the x and y
        if (goRight) {
            mCoordX += goX;
        } else {
            mCoordX -= goX;
        }
        if (goDown) {
            mCoordY += goY;
        } else {
            mCoordY -= goY;
        }

    }

    public int getSpeedX() {
        return mSpeedX;
    }

    public void setSpeedX(int speedX) {
        mSpeedX = speedX;
    }

    public int getmSpeedY() {
        return mSpeedY;
    }

    public void setSpeedY(int speedY) {
        mSpeedY = speedY;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mDrawRect.set(mCoordX, mCoordY, mCoordX + mRealSize, mCoordY
                + mRealSize);
        canvas.drawRoundRect(mDrawRect, 0, 0, mInnerPaint);

    }

    public void setSize(int newSize) {
        mRealSize = newSize;
    }

    public int getSize() {
        return mRealSize;
    }
}

class DrawView extends View {
    private Rectangle mRectangle;
    public int width;
    public int height;

    public DrawView(Context context) {
        super(context);

        mRectangle = new Rectangle(context, this);
        mRectangle.setARGB(255, 255, 0, 0);
        mRectangle.setSpeedX(3);
        mRectangle.setSpeedY(3);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        invalidate();

        mRectangle.move();
        mRectangle.onDraw(canvas);
    }

}
Create custom animation

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create custom layout

Layout (339/474)
« Previous

Create custom layout

Description

The following code shows how to create custom layout.

Example

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<FrameLayout xmlns:cascade="http://schemas.android.com/apk/res/com.manning.androidhacks.hack003"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <com.manning.androidhacks.hack003.view.CascadeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        cascade:horizontal_spacing="30dp"
        cascade:vertical_spacing="20dp" >

        <View
            android:layout_width="100dp"
            android:layout_height="150dp"
            cascade:layout_vertical_spacing="90dp"
            android:background="#FF0000" />

        <View
            android:layout_width="100dp"
            android:layout_height="150dp"
            android:background="#00FF00" />

        <View
            android:layout_width="100dp"
            android:layout_height="150dp"
            android:background="#0000FF" />
    </com.manning.androidhacks.hack003.view.CascadeLayout>
</FrameLayout>

res/layout/framelayout_with_margins.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->

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

    <View
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:background="#FF0000" />

    <View
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="20dp"
        android:background="#00FF00" />

    <View
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:layout_marginLeft="60dp"
        android:layout_marginTop="40dp"
        android:background="#0000FF" />

</RelativeLayout>

Main Activity java

/*******************************************************************************
 * Copyright (c) 2012 Manning/*  w  ww .j  a  v a2s.  com*/
 * See the file license.txt for copying permission.
 ******************************************************************************/
package com.manning.androidhacks.hack003;

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

public class MainActivity extends Activity {

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

Custom layout Java file

/*******************************************************************************
 * Copyright (c) 2012 Manning//www.  j  a v  a2 s. c om
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.manning.androidhacks.hack003.R;

public class CascadeLayout extends ViewGroup {

  private int mHorizontalSpacing;
  private int mVerticalSpacing;

  public CascadeLayout(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs,
        R.styleable.CascadeLayout);

    try {
      mHorizontalSpacing = a.getDimensionPixelSize(
          R.styleable.CascadeLayout_horizontal_spacing,
          getResources().getDimensionPixelSize(
              R.dimen.cascade_horizontal_spacing));

      mVerticalSpacing = a.getDimensionPixelSize(
          R.styleable.CascadeLayout_vertical_spacing, getResources()
              .getDimensionPixelSize(R.dimen.cascade_vertical_spacing));
    } finally {
      a.recycle();
    }

  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = getPaddingLeft();
    int height = getPaddingTop();
    int verticalSpacing;

    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
      verticalSpacing = mVerticalSpacing;

      View child = getChildAt(i);
      measureChild(child, widthMeasureSpec, heightMeasureSpec);

      LayoutParams lp = (LayoutParams) child.getLayoutParams();
      width = getPaddingLeft() + mHorizontalSpacing * i;

      lp.x = width;
      lp.y = height;

      if (lp.verticalSpacing >= 0) {
        verticalSpacing = lp.verticalSpacing;
      }

      width += child.getMeasuredWidth();
      height += verticalSpacing;
    }

    width += getPaddingRight();
    height += getChildAt(getChildCount() - 1).getMeasuredHeight()
        + getPaddingBottom();

    setMeasuredDimension(resolveSize(width, widthMeasureSpec),
        resolveSize(height, heightMeasureSpec));
  }

  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {

    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
      View child = getChildAt(i);
      LayoutParams lp = (LayoutParams) child.getLayoutParams();

      child.layout(lp.x, lp.y, lp.x + child.getMeasuredWidth(), lp.y
          + child.getMeasuredHeight());
    }
  }

  @Override
  protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof LayoutParams;
  }

  @Override
  protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
  }

  @Override
  public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new LayoutParams(getContext(), attrs);
  }

  @Override
  protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
    return new LayoutParams(p.width, p.height);
  }

  public static class LayoutParams extends ViewGroup.LayoutParams {
    int x;
    int y;
    public int verticalSpacing;

    public LayoutParams(Context context, AttributeSet attrs) {
      super(context, attrs);

      TypedArray a = context.obtainStyledAttributes(attrs,
          R.styleable.CascadeLayout_LayoutParams);
      try {
        verticalSpacing = a
            .getDimensionPixelSize(
                R.styleable.CascadeLayout_LayoutParams_layout_vertical_spacing,
                -1);
      } finally {
        a.recycle();
      }
    }

    public LayoutParams(int w, int h) {
      super(w, h);
    }

  }
}

res/values/dimen.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->

<resources>
    <dimen name="cascade_horizontal_spacing">10dp</dimen>
    <dimen name="cascade_vertical_spacing">10dp</dimen>
</resources>

res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->

<resources>
    <declare-styleable name="CascadeLayout">
        <attr name="horizontal_spacing" format="dimension" />
        <attr name="vertical_spacing" format="dimension" />
    </declare-styleable>

    <declare-styleable name="CascadeLayout_LayoutParams">
        <attr name="layout_vertical_spacing" format="dimension" />
    </declare-styleable>
</resources>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create custom Theme

Activity (74/474)
« Previous

Create custom Theme

Description

The following code shows how to create custom Theme.

Example

res/values/theme.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.NoBackground" parent="android:Theme">
        <item name="android:windowBackground">@null</item>
        <item name="android:windowNoTitle">true</item>
    </style>

</resources>

Set customized theme in manifest file

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

    <application
        ...
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.NoBackground" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Create custom Theme

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create custom View

View (460/474)
« Previous

Create custom View

Description

The following code shows how to Create custom View.

Example

Main Activity Java code

package com.java2s.myapplication3.app;
//from www  .  jav a  2  s.  c  o m
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView myView = new MyView(this);

        setContentView(myView);
    }
}
class MyView extends View {

    private Paint mPaint;

    private Point mCenter;
    private float mRadius;

    /*
     * Java Constructor
     */
    public BullsEyeView(Context context) {
        this(context, null);
    }

    /*
     * XML Constructor
     */
    public BullsEyeView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /*
     * XML Constructor with Style
     * Do any initialization of your view in this constructor
     */
    public BullsEyeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Style.FILL);
        mCenter = new Point();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width, height;
        int contentWidth = 200;
        int contentHeight = 200;

        width = getMeasurement(widthMeasureSpec, contentWidth);
        height = getMeasurement(heightMeasureSpec, contentHeight);
        setMeasuredDimension(width, height);
    }
    private int getMeasurement(int measureSpec, int contentSize) {
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (MeasureSpec.getMode(measureSpec)) {
            case MeasureSpec.AT_MOST:
                return Math.min(specSize, contentSize);
            case MeasureSpec.UNSPECIFIED:
                return contentSize;
            case MeasureSpec.EXACTLY:
                return specSize;
            default:
                return 0;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            //If there was a change, reset the parameters
            mCenter.x = w / 2;
            mCenter.y = h / 2;
            mRadius = Math.min(mCenter.x, mCenter.y);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(Color.RED);
        canvas.drawCircle(mCenter.x, mCenter.y, mRadius, mPaint);
    }
}
Create custom View

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create custom view from FrameLayout

Layout (361/474)
« Previous

Create custom view from FrameLayout

Description

The following code shows how to Create custom view from FrameLayout.

Example

Main Activity Java code

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
//w w  w  .  java  2s. c  om
import android.os.Bundle;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextImageButton myView = new TextImageButton(this);
        myView.setText("Text");
        myView.setImageResource();
        setContentView(myView);
    }
}
class TextImageButton extends FrameLayout {

    private ImageView imageView;
    private TextView textView;

    public TextImageButton(Context context) {
        this(context, null);
    }

    public TextImageButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextImageButton(Context context, AttributeSet attrs, int defaultStyle) {
        super(context, attrs, android.R.attr.buttonStyle);
        imageView = new ImageView(context, attrs, defaultStyle);
        textView = new TextView(context, attrs, defaultStyle);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT,
                    Gravity.CENTER);

        this.addView(imageView, params);
        this.addView(textView, params);

        if(imageView.getDrawable() != null) {
            textView.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
        } else {
            textView.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
        }
    }
    public void setText(CharSequence text) {
        textView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.GONE);
        textView.setText(text);
    }

    public void setImageResource(int resId) {
        textView.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(resId);
    }
    public void setImageDrawable(Drawable drawable) {
        textView.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageDrawable(drawable);
    }
}
Create custom view from FrameLayout

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Database Helper

Database (113/474)
« Previous

Create Database Helper

Description

The following code shows how to create database helper.

Example

//from  w  w  w .j av  a 2 s.c om
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

  private static DatabaseHelper mInstance = null;

  private Context mContext;

  public static DatabaseHelper getInstance(Context context, String databaseName, int databaseVersion) {
    /**
     * use the application context as suggested by CommonsWare.
     * this will ensure that you dont accidentally leak an Activitys
     * context (see this article for more information:
     * http://developer.android.com/resources/articles/avoiding-memory-leaks.html)
     */
    if (mInstance == null) {
      mInstance = new DatabaseHelper(context.getApplicationContext(), databaseName, databaseVersion);
    }
    return mInstance;
  }

  /**
   * constructor should be private to prevent direct instantiation.
   * make call to static factory method "getInstance()" instead.
   */
  private DatabaseHelper(Context context, String databaseName, int databaseVersion) {
    super(context, databaseName, null, databaseVersion);
    this.mContext = context;
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Database Helper Class

Database (112/474)
« Previous

Create Database Helper Class

Description

A good practice for dealing with databases is to create a helper class to encapsulate all the complexities of accessing the data.

Example

package com.java2s.myapplication3.app;
// ww w.  j  a va 2 s  .  c  o m
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "_id";
    static final String KEY_NAME = "name";
    static final String KEY_EMAIL = "email";
    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "MyDB";
    static final String DATABASE_TABLE = "contacts";
    static final int DATABASE_VERSION = 1;

    static final String DATABASE_CREATE =
            "create table contacts (_id integer primary key autoincrement, "
                    + "name text not null, email text not null);";

    final Context context;

    DatabaseHelper DBHelper;
    SQLiteDatabase db;

    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }
    //opens the database
    public DBAdapter open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //closes the database
    public void close()
    {
        DBHelper.close();
    }

    //insert a contact into the database
    public long insertContact(String name, String email)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_EMAIL, email);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //deletes a particular contact
    public boolean deleteContact(long rowId)
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    //retrieves all the contacts
    public Cursor getAllContacts()
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_EMAIL}, null, null, null, null, null);
    }

    //retrieves a particular contact
    public Cursor getContact(long rowId) throws SQLException
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                                KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //updates a contact
    public boolean updateContact(long rowId, String name, String email)
    {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_EMAIL, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

Add Contacts

The following code demonstrates how you can add a contact to the table.

      import android.app.Activity;
      import android.os.Bundle;
/*from w  w w . jav a2s.c o m*/
      public class DatabasesActivity extends Activity {
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);

              DBAdapter db = new DBAdapter(this);

              //add a contact
              db.open();
              long id = db.insertContact("Jack", "xml@example.com");
              id = db.insertContact("Jane", "html@example.com");
              db.close();
          }
       }

Retrieve All the Contacts

         import android.app.Activity;
         import android.database.Cursor;
         import android.os.Bundle;
         import android.widget.Toast;
//  w  w w .  j  av a 2 s .  c o m
         public class DatabasesActivity extends Activity {
             @Override
             public void onCreate(Bundle savedInstanceState) {
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.main);

                 DBAdapter db = new DBAdapter(this);

              //get all contacts
              db.open();
              Cursor c = db.getAllContacts();
              if (c.moveToFirst())
              {
                  do {
                      DisplayContact(c);
                  } while (c.moveToNext());
              }
              db.close();
          }

          public void DisplayContact(Cursor c)
          {
              Toast.makeText (this,
                      "id: " + c.getString(0) + "\n" +
                      "Name: " + c.getString(1) + "\n" +
                      "Email:  " + c.getString(2),
                      Toast.LENGTH_LONG).show();
          }
       }

Retrieve a Single Contact

@Override//from w w w. j  a v  a 2  s.c om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DBAdapter db = new DBAdapter(this);
    //get a contact
    db.open();
    Cursor c = db.getContact(2);
    if (c.moveToFirst())
       DisplayContact(c);
    else
       Toast.makeText (this, "No contact found", Toast.LENGTH_LONG).show();
    db.close();
}

Update a Contact

@Override/*from  www  . j av  a 2  s. c  o m*/
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   DBAdapter db = new DBAdapter(this);
   //update contact
   db.open();
   if (db.updateContact(1, "XML", "XML@example.com"))
      Toast.makeText (this, "Update successful.", Toast.LENGTH_LONG).show();
   else
      Toast.makeText (this, "Update failed.", Toast.LENGTH_LONG).show();
   db.close();
}

Delete a Contact

@Override//from   www .jav  a 2  s  . c  o  m
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   DBAdapter db = new DBAdapter(this);

   //delete a contact
   db.open();
   if (db.deleteContact(1))
      Toast.makeText (this, "Delete successful.", Toast.LENGTH_LONG).show();
   else
      Toast.makeText (this, "Delete failed.", Toast.LENGTH_LONG).show();
   db.close();
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create DatePickerDialog from onCreateDialog method

Clock Date Picker (270/474)
« Previous

Create DatePickerDialog from onCreateDialog method

Description

The following code shows how to Create DatePickerDialog from onCreateDialog method.

Example

Layout 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:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="5dp"
    android:paddingRight="5dp" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/date" />

    <Button
        android:id="@+id/details_date"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/edit_text"
        android:gravity="center_vertical" />

</LinearLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning//from   w w  w.j  av a  2 s  . c o  m
 * See the file license.txt for copying permission.
 ******************************************************************************/

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.Toast;

public class MainActivity extends Activity {

  private static final int DATE_DIALOG_ID = 0;

  private int mYear;
  private int mMonth;
  private int mDay;
  private OnDateSetListener mDateSetListener;

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

    // get the current date
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear,
          int dayOfMonth) {
        Toast.makeText(
            MainActivity.this,
            getString(R.string.picked_date_format, monthOfYear,
                dayOfMonth, year), Toast.LENGTH_SHORT).show();
      }
    };

    findViewById(R.id.details_date).setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
          }
        });
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
      return new DatePickerDialog(this, mDateSetListener, mYear,
          mMonth, mDay);
    }
    return super.onCreateDialog(id);
  }

}
Create DatePickerDialog from onCreateDialog method

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create email preference dialog

Preference (193/474)
« Previous

Create email preference dialog

Description

The following code shows how to create preference dialog for email value.

Example

res/xml/prefs.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->

<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="pref_first_preferencescreen_key"
    android:title="Preferences">

    <PreferenceCategory
        android:title="User">

        <EditTextPreference
            android:key="pref_username"
            android:summary="Username:"
            android:title="Username"/>

    </PreferenceCategory>

    <PreferenceCategory
        android:title="Application">

        <Preference
            android:key="pref_rate"
            android:summary="Rate the app in the store!"
            android:title="Rate the app"/>

        <Preference
            android:key="pref_share"
            android:summary="Share the app with your friends"
            android:title="Share it"/>

        <com.manning.androidhacks.hack004.preference.EmailDialog
            android:dialogIcon="@drawable/ic_launcher"
            android:dialogTitle="Send Feedback"
            android:dialogMessage="Do you want to send an email with feedback?"
            android:key="pref_sendemail_key"
            android:negativeButtonText="Cancel"
            android:positiveButtonText="OK"
            android:summary="Send your feedback by e-mail"
            android:title="Send Feedback"/>

        <com.manning.androidhacks.hack004.preference.AboutDialog
            android:dialogIcon="@drawable/ic_launcher"
            android:dialogTitle="About"
            android:key="pref_about_key"
            android:negativeButtonText="@null"
            android:title="About"/>

    </PreferenceCategory>

</PreferenceScreen>

Main activity Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning//from   w  w w . j a v a2  s .  co  m
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class MainActivity extends PreferenceActivity implements
    OnSharedPreferenceChangeListener {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.prefs);

    Preference sharePref = findPreference("pref_share");
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Check this app!");
    shareIntent.putExtra(Intent.EXTRA_TEXT,
        "Check this awesome app at: ...");
    sharePref.setIntent(shareIntent);

    Preference ratePref = findPreference("pref_rate");
    Uri uri = Uri.parse("market://details?id=" + getPackageName());
    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
    ratePref.setIntent(goToMarket);

    updateUserText();
  }

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

    getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);

  }

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

    getPreferenceScreen().getSharedPreferences()
        .unregisterOnSharedPreferenceChangeListener(this);
  }

  @Override
  public void onSharedPreferenceChanged(
      SharedPreferences sharedPreferences, String key) {

    if (key.equals("pref_username")) {
      updateUserText();
    }
  }

  private void updateUserText() {
    EditTextPreference pref;
    pref = (EditTextPreference) findPreference("pref_username");
    String user = pref.getText();

    if (user == null) {
      user = "?";
    }

    pref.setSummary(String.format("Username: %s", user));
  }
}

Launch Email Util Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning/*  ww  w  .  java 2 s . c  o  m*/
 * See the file license.txt for copying permission.
 ******************************************************************************/
package com.manning.androidhacks.hack004.util;

import android.content.Context;
import android.content.Intent;

public class LaunchEmailUtil {

  public static void launchEmailToIntent(Context context) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL,
        new String[] { "feed@back.com" });
    intent.putExtra(Intent.EXTRA_SUBJECT, "[50AH] Feedback");
    intent.putExtra(Intent.EXTRA_TEXT, "Feedback:\n");
    context
        .startActivity(Intent.createChooser(intent, "Send feedback"));
  }
}

AboutDialog Java file

/*******************************************************************************
 * Copyright (c) 2012 Manning//w w w  . ja v  a2 s .c  om
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.DialogPreference;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AboutDialog extends DialogPreference {

  private Context mContext;
  private String mVersionNumber;

  public AboutDialog(Context context) {
    this(context, null);
  }

  public AboutDialog(Context context, AttributeSet attrs) {
    this(context, attrs, 0);

  }

  public AboutDialog(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mContext = context;
  }

  @Override
  protected View onCreateDialogView() {
    LinearLayout layout = new LinearLayout(mContext);
    layout.setOrientation(LinearLayout.VERTICAL);
    TextView splashText = new TextView(mContext);
    String fmt = "Version %s<br />"
        + "<a href=\"http://manning.com/sessa\">MoreInfo</a>";
    try {
      String pkg = mContext.getPackageName();
      mVersionNumber = mContext.getPackageManager().getPackageInfo(pkg,
          0).versionName;
    } catch (NameNotFoundException e) {
      e.printStackTrace();
    }

    if (mVersionNumber != null) {
      String aboutMsg = String.format(fmt, mVersionNumber);
      splashText.setText(Html.fromHtml(aboutMsg));
      splashText.setMovementMethod(LinkMovementMethod.getInstance());
    }

    layout.addView(splashText);

    return layout;
  }
}

EmailDialog Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning// w w  w .j a  va2  s. co  m
 * See the file license.txt for copying permission.
 ******************************************************************************/
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;

public class EmailDialog extends DialogPreference {
  Context mContext;

  public EmailDialog(Context context) {
    this(context, null);
  }

  public EmailDialog(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public EmailDialog(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mContext = context;
  }

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

    if (DialogInterface.BUTTON_POSITIVE == which) {
      LaunchEmailUtil.launchEmailToIntent(mContext);
    }
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create empty ImageView

ImageView (325/474)
« Previous

Create empty ImageView

Description

The following code shows how to Create empty ImageView.

Example

res/drawable/empty_view.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#AA00FF00"/>
</shape>

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/my_list_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <ImageView
        android:id="@+id/empty_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/empty_view" />

</FrameLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning/*from   ww w  .j av a 2s .  c o  m*/
 * See the file license.txt for copying permission.
 ******************************************************************************/

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

public class MainActivity extends Activity {

  private ListView mListView;

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

    mListView = (ListView) findViewById(R.id.my_list_view);
    mListView.setEmptyView(findViewById(R.id.empty_view));
  }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create fade in fade out and slide animation for a View

View (461/474)
« Previous

Create fade in fade out and slide animation for a View

Description

The following code shows how to Create fade in fade out and slide animation for a View.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/toggleButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click to Toggle"
  />
  <View
    android:id="@+id/theView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#AAA"
  />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
//ww w. j  av a2  s . c om
public class MainActivity extends Activity implements View.OnClickListener {

    View viewToAnimate;

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

        Button button = (Button)findViewById(R.id.toggleButton);
        button.setOnClickListener(this);

        viewToAnimate = findViewById(R.id.theView);
    }

    @Override
    public void onClick(View v) {
        if(viewToAnimate.getAlpha() > 0f) {
            //slide it out to the right
            viewToAnimate.animate().alpha(0f).translationX(500f);
        } else {
            //do a fade-in in-place
            viewToAnimate.setTranslationX(0f);
            viewToAnimate.animate().alpha(1f);
        }
    }
}
Create fade in fade out and slide animation for a View

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create FrameLayout with TouchDelegate

Layout (357/474)
« Previous

Create FrameLayout with TouchDelegate

Description

The following code shows how to Create FrameLayout with TouchDelegate.

Example

//from w  w  w . j  av  a2s.  c  om
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.TouchDelegate;
import android.widget.CheckBox;
import android.widget.FrameLayout;

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TouchDelegateLayout layout = new TouchDelegateLayout(this);

        setContentView(layout);
    }
}
class TouchDelegateLayout extends FrameLayout {

    public TouchDelegateLayout(Context context) {
        super(context);
        init(context);
    }

    public TouchDelegateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TouchDelegateLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private CheckBox mButton;

    private void init(Context context) {
        mButton = new CheckBox(context);
        mButton.setText("Tap Anywhere");

        LayoutParams lp = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                Gravity.CENTER);
        addView(mButton, lp);
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            Rect bounds = new Rect(0, 0, w, h);
            TouchDelegate delegate = new TouchDelegate(bounds, mButton);
            setTouchDelegate(delegate);
        }
    }
}
Create FrameLayout with TouchDelegate

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create FrameLayout with two TextView

Layout (358/474)
« Previous

Create FrameLayout with two TextView

Description

The following code shows how to Create FrameLayout with two TextView.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <TextView
      android:layout_width="150px"
      android:layout_height="150px"
      android:background="@android:color/darker_gray"
      />
  <TextView
      android:layout_width="75px"
      android:layout_height="75px"
      android:background="@android:color/white"
      />
</FrameLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
/* www  .j  a  v a 2  s. c o  m*/
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
    }
}
Create FrameLayout with two TextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Image mask on Canvas

Canvas (251/474)
« Previous

Create Image mask on Canvas

Description

The following code shows how to Create Image mask on Canvas.

Example

Main Activity Java code

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.widget.ImageView;
/*ww w .  j av a  2s .co  m*/
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView iv = new ImageView(this);

        Bitmap source = BitmapFactory.decodeResource(getResources(), R.drawable.dog);
        Bitmap mask = BitmapFactory.decodeResource(getResources(), R.drawable.triangle);

        Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);

        canvas.drawBitmap(mask, 0, 0, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        paint.setXfermode(null);

        iv.setImageBitmap(result);
        setContentView(iv);
    }
}
Create Image mask on Canvas

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Layout Changes Animation

Layout (359/474)
« Previous

Create Layout Changes Animation

Description

The following code shows how to Create Layout Changes Animation.

Example

Main layout xml file

<?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:gravity="center_horizontal"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onAddClick"
        android:text="Click To Add Item" />

    <LinearLayout
        android:id="@+id/verticalContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        android:orientation="vertical" />

</LinearLayout>

Main Activity Java code

import android.animation.Animator;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
/*from  ww w. j a v a2 s.c o  m*/
public class MainActivity extends Activity {

    LinearLayout mContainer;

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

        mContainer = (LinearLayout) findViewById(R.id.verticalContainer);
        LayoutTransition transition = new LayoutTransition();
        mContainer.setLayoutTransition(transition);

        Animator appearAnim = ObjectAnimator.ofFloat(null, "rotationY", 90f, 0f)
                .setDuration(transition.getDuration(LayoutTransition.APPEARING));
        transition.setAnimator(LayoutTransition.APPEARING, appearAnim);

        Animator disappearAnim = ObjectAnimator.ofFloat(null, "rotationX", 0f, 90f)
                .setDuration(transition.getDuration(LayoutTransition.DISAPPEARING));
        transition.setAnimator(LayoutTransition.DISAPPEARING, disappearAnim);

        PropertyValuesHolder pvhSlide = PropertyValuesHolder.ofFloat("y", 0, 1);
        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0.4f, 1f);
        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0.6f, 1f);
        Animator changingAppearingAnim = ObjectAnimator.ofPropertyValuesHolder(this, pvhSlide, pvhScaleY, pvhScaleX)
                .setDuration(transition.getDuration(LayoutTransition.CHANGE_DISAPPEARING));
        transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, changingAppearingAnim);
    }

    public void onAddClick(View v) {
        Button button = new Button(this);
        button.setText("Click To Remove");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContainer.removeView(v);
            }
        });

        mContainer.addView(button, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    }
}
Create Layout Changes Animation

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create LinearLayout Programmatically

Layout (343/474)
« Previous

Create LinearLayout Programmatically

Description

The following code shows how to Create LinearLayout Programmatically.

Example

/*from  www . j  av  a 2  s .  co m*/
package com.java2s.myapplication3.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutParams params =
                new LinearLayout.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT);

        //---create a layout---
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        //---create a textview---
        TextView tv = new TextView(this);
        tv.setText("This is a TextView");
        tv.setLayoutParams(params);

        //---create a button---
        Button btn = new Button(this);
        btn.setText("This is a Button");
        btn.setLayoutParams(params);

        //---adds the textview---
        layout.addView(tv);

        //---adds the button---
        layout.addView(btn);

        //---create a layout param for the layout---
        LinearLayout.LayoutParams layoutParam =
                new LinearLayout.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT );

        this.addContentView(layout, layoutParam);
    }
}
Create LinearLayout Programmatically

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create ListView in code

ListView (367/474)
« Previous

Create ListView in code

Description

The following code shows how to create a ListView.

Example

/*from   www .  j av a  2s .c  om*/
package com.java2s.myapplication3.app;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity  {
    String[] presidents = {
            "XML",
            "HTML",
            "CSS",
            "Java",
            "Javascript"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, presidents));
    }

    public void onListItemClick(
            ListView parent, View v, int position, long id)
    {
        Toast.makeText (this,
                "You have selected " + presidents [position],
                Toast.LENGTH_SHORT).show();
    }

}
Create ListView in code

Note

MainActivity class extends the ListActivity class. The ListActivity class extends the Activity class and it displays a list of items by binding to a data source.

There is no need to modify the main.xml file to include the ListView; the ListActivity class itself contains a ListView.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Menu in the code

Menu (392/474)
« Previous

Create Menu in the code

Description

The following code shows how to create Menu in the code.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#eeeeee"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/*  ww  w.j a v  a  2  s.  c om*/

public class MainActivity extends ListActivity {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};
  public static final int EIGHT_ID = Menu.FIRST+1;
  public static final int SIXTEEN_ID = Menu.FIRST+2;
  public static final int TWENTY_FOUR_ID = Menu.FIRST+3;
  public static final int TWO_ID = Menu.FIRST+4;
  public static final int THIRTY_TWO_ID = Menu.FIRST+5;
  public static final int FORTY_ID = Menu.FIRST+6;
  public static final int ONE_ID = Menu.FIRST+7;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items));
    selection=(TextView)findViewById(R.id.selection);

    registerForContextMenu(getListView());
  }

  public void onListItemClick(ListView parent, View v,
                                int position, long id) {
     selection.setText(items[position]);
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
    populateMenu(menu);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    populateMenu(menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    return(applyMenuChoice(item) ||
            super.onOptionsItemSelected(item));
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    return(applyMenuChoice(item) ||
            super.onContextItemSelected(item));
  }

  private void populateMenu(Menu menu) {
    menu.add(Menu.NONE, ONE_ID, Menu.NONE, "1 Pixel");
    menu.add(Menu.NONE, TWO_ID, Menu.NONE, "2 Pixels");
    menu.add(Menu.NONE, EIGHT_ID, Menu.NONE, "8 Pixels");
    menu.add(Menu.NONE, SIXTEEN_ID, Menu.NONE, "16 Pixels");
    menu.add(Menu.NONE, TWENTY_FOUR_ID, Menu.NONE, "24 Pixels");
    menu.add(Menu.NONE, THIRTY_TWO_ID, Menu.NONE, "32 Pixels");
    menu.add(Menu.NONE, FORTY_ID, Menu.NONE, "40 Pixels");
  }

  private boolean applyMenuChoice(MenuItem item) {
    switch (item.getItemId()) {
      case ONE_ID:
        getListView().setDividerHeight(1);
        return(true);

      case EIGHT_ID:
        getListView().setDividerHeight(8);
        return(true);

      case SIXTEEN_ID:
        getListView().setDividerHeight(16);
        return(true);

      case TWENTY_FOUR_ID:
        getListView().setDividerHeight(24);
        return(true);

      case TWO_ID:
        getListView().setDividerHeight(2);
        return(true);

      case THIRTY_TWO_ID:
        getListView().setDividerHeight(32);
        return(true);

      case FORTY_ID:
        getListView().setDividerHeight(40);
        return(true);
    }

    return(false);
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Create Menu in the code

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create nested LinearLayout

Layout (344/474)
« Previous

Create nested LinearLayout

Description

The following example shows how to Create nested LinearLayout.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Number to dial:"
      />
    <EditText android:id="@+id/number"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:cursorVisible="true"
      android:editable="true"
      android:singleLine="true"
    />
  </LinearLayout>
  <Button android:id="@+id/dial"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Dial It!"
  />
</LinearLayout>

Java code

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/*from   ww w. j  a va  2 s .c  o  m*/
public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    final EditText number=(EditText)findViewById(R.id.number);
    Button dial=(Button)findViewById(R.id.dial);

    dial.setOnClickListener(new Button.OnClickListener() {
      public void onClick(View v) {
        String toDial="tel:"+number.getText().toString();

        startActivity(new Intent(Intent.ACTION_DIAL,
                                  Uri.parse(toDial)));
      }
    });
  }
}
Create nested LinearLayout

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create PopupMenu to display just below TextView

Menu (393/474)
« Previous

Create PopupMenu to display just below TextView

Description

The following code shows how to Create PopupMenu to display just below TextView.

Example

Layout activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:id="@+id/anchor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Menu Will Show Here" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Show Menu"
        android:onClick="onShowMenuClick"/>
</RelativeLayout>

Menu xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add"
        android:title="Add Item"
        android:icon="@android:drawable/ic_menu_add"
        android:showAsAction="always|collapseActionView"
        android:actionLayout="@layout/activity_main" />
    <item android:id="@+id/menu_remove"
        android:title="Remove Item"
        android:icon="@android:drawable/ic_menu_delete"
        android:showAsAction="ifRoom" />
    <item android:id="@+id/menu_edit"
        android:title="Edit Item"
        android:icon="@android:drawable/ic_menu_edit"
        android:showAsAction="ifRoom" />
    <item android:id="@+id/menu_settings"
        android:title="Settings"
        android:icon="@android:drawable/ic_menu_preferences"
        android:showAsAction="never" />
</menu>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w ww  . j  ava  2 s .co m*/
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.PopupMenu;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class OptionsActivity extends Activity implements
        PopupMenu.OnMenuItemClickListener,
        CompoundButton.OnCheckedChangeListener {

    private MenuItem mOptionsItem;
    private CheckBox mFirstOption, mSecondOption;

    private PopupMenu mPopup;

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

        //Create a PopupMenu to display just below our TextView
        mPopup = new PopupMenu(this, findViewById(R.id.anchor));
        mPopup.setOnMenuItemClickListener(this);
        //Use the same options menu as our Activity
        mPopup.inflate(R.menu.main);
    }

    public void onShowMenuClick(View v) {
        mPopup.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Use this callback to create the menu and do any
        // initial setup necessary
        getMenuInflater().inflate(R.menu.main, menu);

        //Find and initialize our action item
        mOptionsItem = menu.findItem(R.id.menu_add);
        mOptionsItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(
                    MenuItem item) {
                // Must return true to have item expand
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(
                    MenuItem item) {
                mFirstOption.setChecked(false);
                mSecondOption.setChecked(false);
                // Must return true to have item collapse
                return true;
            }
        });

        mFirstOption = (CheckBox) mOptionsItem
                .getActionView()
                .findViewById(R.id.menu_add);
        mFirstOption
                .setOnCheckedChangeListener(this);
        mSecondOption = (CheckBox) mOptionsItem
                .getActionView()
                .findViewById(R.id.menu_remove);
        mSecondOption
                .setOnCheckedChangeListener(this);

        return true;
    }

    /* CheckBox Callback Methods */

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (mFirstOption.isChecked() && mSecondOption.isChecked()) {
            mOptionsItem.collapseActionView();
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        //Use this callback to do setup that needs to happen
        // each time the menu opens
        return super.onPrepareOptionsMenu(menu);
    }

    //Callback from the PopupMenu click
    public boolean onMenuItemClick(MenuItem item) {
        menuItemSelected(item);
        return true;
    }

    //Callback from a standard options menu click
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        menuItemSelected(item);
        return true;
    }

    //Private helper so each unique callback can trigger the same actions
    private void menuItemSelected(MenuItem item) {
        //Get the selected option by id
        switch (item.getItemId()) {
            case R.id.menu_add:
                //Do add action
                break;
            case R.id.menu_remove:
                //Do remove action
                break;
            case R.id.menu_edit:
                //Do edit action
                break;
            case R.id.menu_settings:
                //Do settings action
                break;
            default:
                break;
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create region monitor service

Location (159/474)
« Previous

Create region monitor service

Description

The following code shows how to Create region monitor service.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Register service in manifest xml file

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

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

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

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

        <service android:name="com.androidrecipes.regionmonitor.RegionMonitorService" />
    </application>

</manifest>

Main xml file

<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/status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <SeekBar
        android:id="@+id/radius"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="1000"/>
    <TextView
        android:id="@+id/radius_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Set Geofence at My Location"
        android:onClick="onSetGeofenceClick" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Monitoring"
        android:onClick="onStartMonitorClick" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Monitoring"
        android:onClick="onStopMonitorClick" />
</LinearLayout>

Main activity Java code

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationStatusCodes;
/*  w w w. j ava 2s  . c o  m*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity implements
        OnSeekBarChangeListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        LocationClient.OnAddGeofencesResultListener,
        LocationClient.OnRemoveGeofencesResultListener {
    private static final String TAG = "RegionMonitorActivity";

    private static final String FENCE_ID = "com.androidrecipes.FENCE";

    private LocationClient mLocationClient;
    private SeekBar mRadiusSlider;
    private TextView mStatusText, mRadiusText;

    private Geofence mCurrentFence;
    private Intent mServiceIntent;
    private PendingIntent mCallbackIntent;

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

        mStatusText = (TextView) findViewById(R.id.status);
        mRadiusText = (TextView) findViewById(R.id.radius_text);
        mRadiusSlider = (SeekBar) findViewById(R.id.radius);
        mRadiusSlider.setOnSeekBarChangeListener(this);
        updateRadiusDisplay();

        switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)) {
            case ConnectionResult.SUCCESS:
                //Do nothing, move on
                break;
            case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                Toast.makeText(this,
                        "Geofencing service requires an update, please open Google Play.",
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
            default:
                Toast.makeText(this,
                        "Geofencing service is not available on this device.",
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
        }
        //Create a client for Google Services
        mLocationClient = new LocationClient(this, this, this);
        //Create an Intent to trigger our service
        mServiceIntent = new Intent(this, RegionMonitorService.class);
        //Create a PendingIntent for Google Services to use with callbacks
        mCallbackIntent = PendingIntent.getService(this, 0, mServiceIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Connect to all services
        if (!mLocationClient.isConnected()
                && !mLocationClient.isConnecting()) {
            mLocationClient.connect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //Disconnect when not in the foreground
        mLocationClient.disconnect();
    }

    public void onSetGeofenceClick(View v) {
        //Obtain the last location from services and radius
        // from the UI
        Location current = mLocationClient.getLastLocation();
        int radius = mRadiusSlider.getProgress();

        //Create a new Geofence using the Builder
        Geofence.Builder builder = new Geofence.Builder();
        mCurrentFence = builder
            //Unique to this geofence
            .setRequestId(FENCE_ID)
            //Size and location
            .setCircularRegion(
                current.getLatitude(),
                current.getLongitude(),
                radius)
            //Events both in and out of the fence
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER
                    | Geofence.GEOFENCE_TRANSITION_EXIT)
            //Keep alive
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .build();

        mStatusText.setText(String.format("Geofence set at %.3f, %.3f",
                current.getLatitude(), current.getLongitude()) );
    }

    public void onStartMonitorClick(View v) {
        if (mCurrentFence == null) {
            Toast.makeText(this, "Geofence Not Yet Set",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        //Add the fence to start tracking, the PendingIntent will
        // be triggered with new updates
        ArrayList<Geofence> geofences = new ArrayList<Geofence>();
        geofences.add(mCurrentFence);
        mLocationClient.addGeofences(geofences, mCallbackIntent, this);
    }

    public void onStopMonitorClick(View v) {
        //Remove to stop tracking
        mLocationClient.removeGeofences(mCallbackIntent, this);
    }

    /** SeekBar Callbacks */

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromUser) {
        updateRadiusDisplay();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) { }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) { }

    private void updateRadiusDisplay() {
        mRadiusText.setText(mRadiusSlider.getProgress() + " meters");
    }

    /** Google Services Connection Callbacks */

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.v(TAG, "Google Services Connected");
    }

    @Override
    public void onDisconnected() {
        Log.w(TAG, "Google Services Disconnected");
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.w(TAG, "Google Services Connection Failure");
    }

    /** LocationClient Callbacks */

    /*
     * Called when the asynchronous geofence add is complete.
     * When this happens we start our monitoring service.
     */
    @Override
    public void onAddGeofencesResult(int statusCode,
            String[] geofenceRequestIds) {
        if (statusCode == LocationStatusCodes.SUCCESS) {
            Toast.makeText(this, "Geofence Added Successfully", Toast.LENGTH_SHORT).show();
        }

        Intent startIntent = new Intent(mServiceIntent);
        startIntent.setAction(RegionMonitorService.ACTION_INIT);
        startService(mServiceIntent);
    }

    /*
     * Called when the asynchronous geofence remove is complete.
     * The version called depends on whether you requested the
     * removal via PendingIntent or request Id.
     * When this happens we stop our monitoring service.
     */
    @Override
    public void onRemoveGeofencesByPendingIntentResult(
            int statusCode, PendingIntent pendingIntent) {
        if (statusCode == LocationStatusCodes.SUCCESS) {
            Toast.makeText(this, "Geofence Removed Successfully",
                    Toast.LENGTH_SHORT).show();
        }

        stopService(mServiceIntent);
    }

    @Override
    public void onRemoveGeofencesByRequestIdsResult(
            int statusCode, String[] geofenceRequestIds) {
        if (statusCode == LocationStatusCodes.SUCCESS) {
            Toast.makeText(this, "Geofence Removed Successfully",
                    Toast.LENGTH_SHORT).show();
        }

        stopService(mServiceIntent);
    }
}

Service Java code

package com.java2s.myapplication3.app;
//w  w  w.j a v a2  s  .co  m
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "RegionMonitorService";

    private static final int NOTE_ID = 100;
    //Unique action to identify start requests vs. events
    public static final String ACTION_INIT =
            "com.androidrecipes.regionmonitor.ACTION_INIT";

    private NotificationManager mNoteManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mNoteManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //Post a system notification when the service starts
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("Geofence Service");
        builder.setContentText("Waiting for transition...");
        builder.setOngoing(true);

        Notification note = builder.build();
        mNoteManager.notify(NOTE_ID, note);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Nothing to do yet, just starting the service
        if (ACTION_INIT.equals(intent.getAction())) {
            //We don't care if this service dies unexpectedly
            return START_NOT_STICKY;
        }

        if (LocationClient.hasError(intent)) {
            //Log any errors
            Log.w(TAG, "Error monitoring region: "
                    + LocationClient.getErrorCode(intent));
        } else {
            //Update the ongoing notification from the new event
            NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(this);
            builder.setSmallIcon(R.drawable.ic_launcher);
            builder.setDefaults(Notification.DEFAULT_SOUND
                    | Notification.DEFAULT_LIGHTS);
            builder.setOngoing(true);

            int transitionType = LocationClient.getGeofenceTransition(intent);
            //Check whether we entered or exited the region
            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) {
                builder.setContentTitle("Geofence Transition");
                builder.setContentText("Entered your Geofence");
            } else if (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
                builder.setContentTitle("Geofence Transition");
                builder.setContentText("Exited your Geofence");
            }

            Notification note = builder.build();
            mNoteManager.notify(NOTE_ID, note);
        }

        //We don't care if this service dies unexpectedly
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //When the service dies, cancel our ongoing notification
        mNoteManager.cancel(NOTE_ID);
    }

    /* We are not binding to this service */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Restrictions Receiver

Notification (188/474)
« Previous

Create Restrictions Receiver

Description

The following code shows how to Create Restrictions Receiver.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Register Permission

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

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

    <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>
        <receiver android:name=".RestrictionsReceiver">
            <intent-filter>
                <action android:name="android.intent.action.GET_RESTRICTION_ENTRIES"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Main layout xml file

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

    <com.androidrecipes.restrictedprofiles.DrawingView
        android:id="@+id/drawing_surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <Button
        android:id="@+id/button_purchase"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="$$$$"
        android:onClick="onPurchaseClick"/>

    <SeekBar
        android:id="@+id/full_slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:max="45"/>
    <RadioGroup
        android:id="@+id/simple_selector"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/option_small"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#555"
            android:text="Small" />
        <RadioButton
            android:id="@+id/option_medium"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#555"
            android:text="Medium" />
        <RadioButton
            android:id="@+id/option_large"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#555"
            android:text="Big" />
        <RadioButton
            android:id="@+id/option_xlarge"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#555"
            android:text="Really Big" />
    </RadioGroup>
</FrameLayout>

Main Activity Java code

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.UserManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
/*from   ww w .j av  a 2 s. c o  m*/
@SuppressLint("NewApi")
public class MainActivity extends Activity implements
        OnSeekBarChangeListener, OnCheckedChangeListener {

    private Button mPurchaseButton;
    private DrawingView mDrawingView;
    private SeekBar mFullSlider;
    private RadioGroup mSimpleSelector;

    /* Profile Restriction Values */
    private boolean mHasPurchases;
    private int mMinAge;
    /* Content Purchase Flags */
    private boolean mHasCanvasColors = false;
    private boolean mHasPaintColors = false;

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

        mPurchaseButton = (Button) findViewById(R.id.button_purchase);
        mDrawingView = (DrawingView) findViewById(R.id.drawing_surface);
        mFullSlider = (SeekBar) findViewById(R.id.full_slider);
        mSimpleSelector = (RadioGroup) findViewById(R.id.simple_selector);

        mFullSlider.setOnSeekBarChangeListener(this);
        mSimpleSelector.setOnCheckedChangeListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            UserManager manager = (UserManager) getSystemService(USER_SERVICE);
            //Check for system-level restrictions
            Bundle restrictions = manager.getUserRestrictions();
            if (restrictions != null && !restrictions.isEmpty()) {
                showSystemRestrictionsDialog(restrictions);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        /*
         * Restrictions may change while the app is in the background so we need
         * to check this each time we return
         */
        updateRestrictions();
        // Update UI based on restriction changes
        updateDisplay();
    }

    public void onPurchaseClick(View v) {
        AlertDialog.Builder builder =
                new AlertDialog.Builder(this);
        builder.setTitle("Content Upgrades")
                .setMessage(
                        "Tap any of the following items to add them.")
                .setPositiveButton("Canvas Colors $2.99",
                        mPurchaseListener)
                .setNeutralButton("Paint Colors $2.99",
                        mPurchaseListener)
                .setNegativeButton("Both Items $4.99",
                        mPurchaseListener).show();
    }

    private DialogInterface.OnClickListener mPurchaseListener =
            new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    mHasCanvasColors = true;
                    break;
                case DialogInterface.BUTTON_NEUTRAL:
                    mHasPaintColors = true;
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    mHasCanvasColors = true;
                    mHasPaintColors = true;
                    break;
            }
            Toast.makeText(getApplicationContext(), "Thank You For Your Purchase!",
                    Toast.LENGTH_SHORT).show();
            updateDisplay();
        }
    };

    private void showSystemRestrictionsDialog(Bundle restrictions) {
        StringBuilder message = new StringBuilder();
        for (String key : restrictions.keySet()) {
            //Make sure the value of the restriction is true
            if (restrictions.getBoolean(key)) {
                message.append(RestrictionsReceiver.getNameForRestriction(key));
                message.append("\n");
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("System Restrictions")
            .setMessage(message.toString())
            .setPositiveButton("OK", null)
            .show();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        float width;
        switch(checkedId) {
            default:
            case R.id.option_small:
                width = 4f;
                break;
            case R.id.option_medium:
                width = 12f;
                break;
            case R.id.option_large:
                width = 25f;
                break;
            case R.id.option_xlarge:
                width = 45f;
                break;
        }
        mDrawingView.setStrokeWidth(width);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromUser) {
        mDrawingView.setStrokeWidth(progress);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) { }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) { }

    private void updateDisplay() {
        //Show/hide purchase button
        mPurchaseButton.setVisibility(
                mHasPurchases ? View.VISIBLE : View.GONE);

        //Update age-restricted content
        mFullSlider.setVisibility(View.GONE);
        mSimpleSelector.setVisibility(View.GONE);
        switch (mMinAge) {
            case 18:
                //Full-range slider
                mFullSlider.setVisibility(View.VISIBLE);
                mFullSlider.setProgress(4);
                break;
            case 10:
                //Four options
                mSimpleSelector.setVisibility(View.VISIBLE);
                findViewById(R.id.option_medium).setVisibility(View.VISIBLE);
                findViewById(R.id.option_xlarge).setVisibility(View.VISIBLE);
                mSimpleSelector.check(R.id.option_medium);
                break;
            case 5:
                //Big/small option
                mSimpleSelector.setVisibility(View.VISIBLE);
                findViewById(R.id.option_medium).setVisibility(View.GONE);
                findViewById(R.id.option_xlarge).setVisibility(View.GONE);
                mSimpleSelector.check(R.id.option_small);
                break;
            case 3:
            default:
                //No selection
                break;
        }

        //Update display with purchases
        mDrawingView.setPaintColor(mHasPaintColors ? Color.BLUE : Color.GRAY);
        mDrawingView.setCanvasColor(mHasCanvasColors ? Color.GREEN : Color.TRANSPARENT);
    }

    private void updateRestrictions() {
        // Check for restrictions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            UserManager manager = (UserManager) getSystemService(USER_SERVICE);
            Bundle restrictions = manager
                    .getApplicationRestrictions(getPackageName());
            if (restrictions != null) {
                // Read restriction settings
                mHasPurchases = restrictions.getBoolean(
                        RestrictionsReceiver.RESTRICTION_PURCHASE, true);
                try {
                    mMinAge = Integer.parseInt(restrictions.getString(
                            RestrictionsReceiver.RESTRICTION_AGERANGE, "18"));
                } catch (NumberFormatException e) {
                    mMinAge = 0;
                }
            } else {
                // We have no restrictions
                mHasPurchases = true;
                mMinAge = 18;
            }
        } else {
            // We are not on a system that supports restrictions
            mHasPurchases = true;
            mMinAge = 18;
        }
    }
}

DrawingView Java code

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/*  w  ww . j a va  2  s.  c  om*/
public class DrawingView extends View {

    private Paint mFingerPaint;
    private Path mPath;

    public DrawingView(Context context) {
        super(context);
        init();
    }

    public DrawingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DrawingView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        //Set up the paint brush
        mFingerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mFingerPaint.setStyle(Style.STROKE);
        mFingerPaint.setStrokeCap(Cap.ROUND);
        mFingerPaint.setStrokeJoin(Join.ROUND);
        //Default stroke width
        mFingerPaint.setStrokeWidth(8f);
    }

    public void setPaintColor(int color) {
        mFingerPaint.setColor(color);
    }

    public void setStrokeWidth(float width) {
        mFingerPaint.setStrokeWidth(width);
    }

    public void setCanvasColor(int color) {
        setBackgroundColor(color);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                mPath = new Path();
                //Start at the touch down
                mPath.moveTo(event.getX(), event.getY());
                //Re-draw
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                //Add all touch points between events
                for (int i=0; i < event.getHistorySize(); i++) {
                    mPath.lineTo(event.getHistoricalX(i),
                            event.getHistoricalY(i) );
                }
                //Re-draw
                invalidate();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //Draw the background
        super.onDraw(canvas);
        //Draw the paint stroke
        if (mPath != null) {
            canvas.drawPath(mPath, mFingerPaint);
        }
    }
}

RestrictionsReceiver Java code

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.RestrictionEntry;
import android.os.Bundle;
import android.os.UserManager;
/*from   w ww  . ja va 2  s  .c  o m*/
import java.util.ArrayList;

@SuppressLint("NewApi")
public class RestrictionsReceiver extends BroadcastReceiver {

    public static final String RESTRICTION_PURCHASE = "purchases";
    public static final String RESTRICTION_AGERANGE = "age_range";

    private static final String[] AGES = {"3+", "5+", "10+", "18+"};
    private static final String[] AGE_VALUES = {"3", "5", "10", "18"};

    @Override
    public void onReceive(Context context, Intent intent) {
        ArrayList<RestrictionEntry> restrictions = new ArrayList<RestrictionEntry>();

        RestrictionEntry purchase = new RestrictionEntry(RESTRICTION_PURCHASE, false);
        purchase.setTitle("Content Purchases");
        purchase.setDescription("Allow purchasing of content in the application.");
        restrictions.add(purchase);

        RestrictionEntry ages = new RestrictionEntry(RESTRICTION_AGERANGE, AGE_VALUES[0]);
        ages.setTitle("Age Level");
        ages.setDescription("Difficulty level for application content.");
        ages.setChoiceEntries(AGES);
        ages.setChoiceValues(AGE_VALUES);
        restrictions.add(ages);

        Bundle result = new Bundle();
        result.putParcelableArrayList(Intent.EXTRA_RESTRICTIONS_LIST, restrictions);

        setResultExtras(result);
    }

    /*
     * Utility to get readable strings from restriction keys
     */
    public static String getNameForRestriction(String key) {
        if (UserManager.DISALLOW_CONFIG_BLUETOOTH.equals(key)) {
            return "Unable to configure Bluetooth";
        }
        if (UserManager.DISALLOW_CONFIG_CREDENTIALS.equals(key)) {
            return "Unable to configure user credentials";
        }
        if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
            return "Unable to configure Wifi";
        }
        if (UserManager.DISALLOW_INSTALL_APPS.equals(key)) {
            return "Unable to install applications";
        }
        if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
            return "Unable to enable unknown sources";
        }
        if (UserManager.DISALLOW_MODIFY_ACCOUNTS.equals(key)) {
            return "Unable to modify accounts";
        }
        if (UserManager.DISALLOW_REMOVE_USER.equals(key)) {
            return "Unable to remove users";
        }
        if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
            return "Unable to toggle location sharing";
        }
        if (UserManager.DISALLOW_UNINSTALL_APPS.equals(key)) {
            return "Unable to uninstall applications";
        }
        if (UserManager.DISALLOW_USB_FILE_TRANSFER.equals(key)) {
            return "Unable to transfer files";
        }

        return "Unknown Restriction: "+key;
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Rounded Corner ImageView from View to show Image

ImageView (332/474)
« Previous

Create Rounded Corner ImageView from View to show Image

Description

The following code shows how to Create Rounded Corner ImageView from View to show Image.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main Activity Java code

/*w w  w. jav a  2s. c o m*/
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RoundedCornerImageView iv = new RoundedCornerImageView(this);
        Bitmap source = BitmapFactory.decodeResource(getResources(), R.drawable.dog);

        iv.setImage(source);
        setContentView(iv);
    }
}
class RoundedCornerImageView extends View {

    private Bitmap mImage;
    private Paint mBitmapPaint;

    private RectF mBounds;
    private float mRadius = 25.0f;

    public RoundedCornerImageView(Context context) {
        super(context);
        init();
    }

    public RoundedCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundedCornerImageView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBounds = new RectF();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height, width;
        height = width = 0;
        int imageHeight, imageWidth;
        if (mImage == null) {
            imageHeight = imageWidth = 0;
        } else {
            imageHeight = mImage.getHeight();
            imageWidth = mImage.getWidth();
        }
        width = getMeasurement(widthMeasureSpec, imageWidth);
        height = getMeasurement(heightMeasureSpec, imageHeight);

        setMeasuredDimension(width, height);
    }
    private int getMeasurement(int measureSpec, int contentSize) {
        int specSize = MeasureSpec.getSize(measureSpec);
        switch (MeasureSpec.getMode(measureSpec)) {
            case MeasureSpec.AT_MOST:
                return Math.min(specSize, contentSize);
            case MeasureSpec.UNSPECIFIED:
                return contentSize;
            case MeasureSpec.EXACTLY:
                return specSize;
            default:
                return 0;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            int imageWidth, imageHeight;
            if (mImage == null) {
                imageWidth = imageHeight = 0;
            } else {
                imageWidth = mImage.getWidth();
                imageHeight = mImage.getHeight();
            }
            int left = (w - imageWidth) / 2;
            int top = (h - imageHeight) / 2;
            mBounds.set(left, top, left+imageWidth, top+imageHeight);
            if (mBitmapPaint.getShader() != null) {
                Matrix m = new Matrix();
                m.setTranslate(left, top);
                mBitmapPaint.getShader().setLocalMatrix(m);
            }
        }
    }

    public void setImage(Bitmap bitmap) {
        if (mImage != bitmap) {
            mImage = bitmap;
            if (mImage != null) {
                BitmapShader shader = new BitmapShader(mImage, TileMode.CLAMP, TileMode.CLAMP);
                mBitmapPaint.setShader(shader);
            } else {
                mBitmapPaint.setShader(null);
            }
            requestLayout();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mBitmapPaint != null) {
            canvas.drawRoundRect(mBounds, mRadius, mRadius, mBitmapPaint);
        }
    }
}
Create Rounded Corner ImageView from View to show Image

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create rounded corners in your Drawable

Resources (34/474)
« Previous

Create rounded corners in your Drawable

Description

To achieve the rounded corners in your Drawable, you can use the currently undocumented <shape> tag.

This tag needs to reside in a file by itself in the /res/drawable directory.

Example

The following code shows how you can use the <shape> tag to define a rounded rectangle in a file called /res/drawable/my_rounded_rectangle.xml.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#f0600000"/>
    <stroke android:width="3dp" color="#ffff8080"/>
    <corners android:radius="13dp" />
    <padding android:left="10dp"
             android:top="10dp"
             android:right="10dp"
             android:bottom="10dp" />
</shape>

You can then use this drawable resource as a background of the previous text view example, as follows.

GradientDrawable roundedRectangle = (GradientDrawable)
activity.getResources().getDrawable(R.drawable.my_rounded_rectangle);

textView.setBackgroundDrawable(roundedRectangle);

Note

In the end, a bitmap image in the drawable subdirectory resolves to a BitmapDrawable class. A drawable resource value, such as one of the rectangles, resolves to a ColorDrawable.

An XML file with a <shape> tag in it resolves to a GradientDrawable.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create ScaleAnimation

Animation (235/474)
« Previous

Create ScaleAnimation

Description

The following code shows how to Create ScaleAnimation.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <ImageView
    android:id="@+id/flip_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
  />
</RelativeLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
//from  w w  w  . j av a  2 s .c om
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

public class MainActivity extends Activity {

    boolean isHeads;
    ScaleAnimation shrink, grow;
    ImageView flipImage;

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

        flipImage = (ImageView)findViewById(R.id.flip_image);
        flipImage.setImageResource(R.drawable.ic_launcher);
        isHeads = true;

        shrink = new ScaleAnimation(.3f, 0.4f, 1.0f, 1.0f,
                ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
                ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
        shrink.setDuration(150);
        shrink.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationRepeat(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {
                isHeads = false;
                flipImage.setImageResource(R.drawable.ic_launcher);
                flipImage.startAnimation(grow);
            }
        });
        grow = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f,
                ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
                ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
        grow.setDuration(150);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            flipImage.startAnimation(shrink);
            return true;
        }
        return super.onTouchEvent(event);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create service

Service (204/474)
« Previous

Create service

Description

The following code shows how to Create your own service.

Example

Install service in manifest file

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<manifest...

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

        <service android:name=".MyService" />
    </application>

</manifest>

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<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/text_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

</LinearLayout>

Main activity

//from w  w w  .j  a va  2 s .c o  m
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  private ProgressDialog mProgressDialog;
  private TextView mTextView;

  private BroadcastReceiver mReceiver;
  private IntentFilter mIntentFilter;

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

    mTextView = (TextView) findViewById(R.id.text_view);

    mProgressDialog = ProgressDialog.show(this, "Loading",
        "Please wait");
    mProgressDialog.show();

    mReceiver = new MyServiceReceiver();
    mIntentFilter = new IntentFilter(MyService.ACTION);

    startService(new Intent(this, MyService.class));
  }

  @Override
  protected void onResume() {
    super.onResume();
    registerReceiver(mReceiver, mIntentFilter);
  }

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

  private void update(String msg) {
    mProgressDialog.dismiss();
    mTextView.setText(msg);
  }

  class MyServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      update(intent.getExtras().getString(MyService.MSG_KEY));

    }

  }
}

Service

/* ww w .  j  a  v  a  2 s  .c  om*/
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

import java.util.Date;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;

public class MyService extends IntentService {

  public static final String ACTION = "com.java2s.SERVICE_MSG";
  public static final String MSG_KEY = "MSG_KEY";

  public MyService() {
    super("MyService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
    SystemClock.sleep(5000L);
    Intent broadcast = new Intent(ACTION);
    broadcast.putExtra(MSG_KEY, new Date().toGMTString());
    sendBroadcast(broadcast);
  }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create TextWatcher for currency value

EditText (296/474)
« Previous

Create TextWatcher for currency value

Description

The following code shows how to Create TextWatcher for currency value.

Example

Main layout xml file

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

Main activity Java code

package com.java2s.myapplication3.app;
//from w  w  w .  j a  v a  2s.  c  o m
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

import java.text.NumberFormat;

import android.text.Editable;
import android.text.TextWatcher;
public class MainActivity extends Activity {

    EditText text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        text = new EditText(this);
        text.addTextChangedListener(new CurrencyTextWatcher());

        setContentView(text);
    }

}
class CurrencyTextWatcher implements TextWatcher {

    boolean mEditing;

    public CurrencyTextWatcher() {
        mEditing = false;
    }

    public synchronized void afterTextChanged(Editable s) {
        if(!mEditing) {
            mEditing = true;

            //Strip symbols
            String digits = s.toString().replaceAll("\\D", "");
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            try{
                String formatted = nf.format(Double.parseDouble(digits)/100);
                s.replace(0, s.length(), formatted);
            } catch (NumberFormatException nfe) {
                s.clear();
            }

            mEditing = false;
        }
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    public void onTextChanged(CharSequence s, int start, int before, int count) { }

}
Create TextWatcher for currency value

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create VideoView

Video (450/474)
« Previous

Create VideoView

Description

The following code shows how to use VideoView to play a m4v media file.

Example

Layout file

<?xml version="1.0" encoding="utf-8"?>
<!--/*  w ww . j a  va  2 s .  co  m*/
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:id="@+id/main_portrait_content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="0.25"
            android:orientation="horizontal" >

            <ScrollView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:text="test" />
            </ScrollView>

            <View
                android:id="@+id/main_portrait_position"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_margin="2dp"
                android:layout_weight="1"
                android:background="#ffffff" />
        </LinearLayout>

        <View
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="5dp"
            android:background="#ffffff" />

        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_marginTop="2dp"
            android:layout_weight="0.75" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="text" />
        </ScrollView>
    </LinearLayout>

    <VideoView
        android:id="@+id/main_videoview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="gone" />

</RelativeLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning/*from   w  ww  .  java  2  s  .  c  o  m*/
 * See the file license.txt for copying permission.
 ******************************************************************************/
package com.manning.androidhacks.hack014;

import android.app.Activity;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.VideoView;

public class MainActivity extends Activity {

  private VideoView mVideoView;
  private View mPortraitPosition;
  private View mPortraitContent;

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

    mPortraitPosition = findViewById(R.id.main_portrait_position);
    mPortraitContent = findViewById(R.id.main_portrait_content);
    mVideoView = (VideoView) findViewById(R.id.main_videoview);

    // We use a post to call initVideoView because
    // we need the width and height of mPortraitPosition
    mVideoView.post(new Runnable() {
      @Override
      public void run() {
        initVideoView();
      }
    });
  }

  private void initVideoView() {
    mVideoView.setMediaController(new MediaController(this));
    Uri uri = Uri.parse("android.resource://" + getPackageName() + "/"
        + R.raw.bigbuck);
    mVideoView.setVideoURI(uri);

    setVideoViewPosition();
    mVideoView.start();
  }

  private void setVideoViewPosition() {
    switch (getResources().getConfiguration().orientation) {
    case Configuration.ORIENTATION_LANDSCAPE: {
      mPortraitContent.setVisibility(View.GONE);

      RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
          LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

      params.addRule(RelativeLayout.CENTER_IN_PARENT);
      mVideoView.setLayoutParams(params);
      break;
    }

    case Configuration.ORIENTATION_SQUARE:
    case Configuration.ORIENTATION_UNDEFINED:
    case Configuration.ORIENTATION_PORTRAIT:
    default: {

      mPortraitContent.setVisibility(View.VISIBLE);

      int[] locationArray = new int[2];
      mPortraitPosition.getLocationOnScreen(locationArray);

      RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
          mPortraitPosition.getWidth(), mPortraitPosition.getHeight());

      params.leftMargin = locationArray[0];
      params.topMargin = locationArray[1];

      mVideoView.setLayoutParams(params);

      break;
    }
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    setVideoViewPosition();
    super.onConfigurationChanged(newConfig);
  }
}

Download

hack14.zip

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create XML based animation

Animation (236/474)
« Previous

Create XML based animation

Description

The following code shows how to Create XML based animation.

Example

res\anim\grow.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <scale
    android:duration="150"
    android:fromXScale="0.0"
    android:toXScale="1.0"
    android:fromYScale="1.0"
    android:toYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"
  />
<translate
    android:duration="150"
    android:fromXDelta="0%"
    android:toXDelta="0%"
    android:fromYDelta="50%"
    android:toYDelta="0%"
  />
</set>

res\anim\shrink.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <scale
    android:duration="150"
    android:fromXScale="1.0"
    android:toXScale="0.0"
    android:fromYScale="1.0"
    android:toYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"
  />
<translate
    android:duration="150"
    android:fromXDelta="0%"
    android:toXDelta="0%"
    android:fromYDelta="0%"
    android:toYDelta="50%"
  />
</set>

res\layout\main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <ImageView
    android:id="@+id/flip_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
  />
</RelativeLayout>

MainActivity.java

package com.examples.animationxml;
/*  w  ww  .  ja  va  2  s.  c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends Activity {

    boolean isHeads;
    Animation shrink, grow;
    ImageView flipImage;

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

        flipImage = (ImageView)findViewById(R.id.flip_image);
        flipImage.setImageResource(R.drawable.heads);
        isHeads = true;

        shrink = AnimationUtils.loadAnimation(this, R.anim.shrink);
        shrink.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationRepeat(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {
                if(isHeads) {
                    isHeads = false;
                    flipImage.setImageResource(R.drawable.tails);
                } else {
                    isHeads = true;
                    flipImage.setImageResource(R.drawable.heads);
                }
                flipImage.startAnimation(grow);
            }
        });
        grow = AnimationUtils.loadAnimation(this, R.anim.grow);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            flipImage.startAnimation(shrink);
            return true;
        }
        return super.onTouchEvent(event);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create your first IntentService

Service (205/474)
« Previous

Create your first IntentService

Description

The following code shows how to Create your first IntentService.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
//from w w  w . ja  va2 s.  c om
import java.net.MalformedURLException;
import java.net.URL;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class MyService extends IntentService {

    public MyService() {
        super("MyIntentServiceName");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            int result = DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));
            Log.d("IntentService", "Downloaded " + result + " bytes");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/*from w w  w .j a v a 2s. c  om*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
           startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Your First Service

Service (203/474)
« Previous

Create Your First Service

Description

The following code shows how to Create Your First Service.

The following code shows you the steps to create a simple service.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
//from  w  ww  . ja  v  a 2s  .  c o m
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        Toast.makeText (this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText (this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
// www  .ja va 2s.c om
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
           startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Create Your Own Content Providers

Content Provider (100/474)
« Previous

Create Your Own Content Providers

Description

The following code shows how to Create Your Own Content Providers.

All you need to do is extend the abstract ContentProvider class and override the various methods defined within it.

Example

package com.java2s.myapplication3.app;
//from   ww w  .  jav  a2  s.com
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class BooksProvider extends ContentProvider {
    static final String PROVIDER_NAME =
            "com.java2s.provider.Books";

    static final Uri CONTENT_URI =
            Uri.parse ("content://"+ PROVIDER_NAME + "/books");

    static final String _ID = "_id";
    static final String TITLE = "title";
    static final String ISBN = "isbn";

    static final int BOOKS = 1;
    static final int BOOK_ID = 2;

    private static final UriMatcher uriMatcher;
    static{
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "books", BOOKS);
        uriMatcher.addURI(PROVIDER_NAME, "books/#", BOOK_ID);
    }

    SQLiteDatabase booksDB;
    static final String DATABASE_NAME = "Books";
    static final String DATABASE_TABLE = "titles";
    static final int DATABASE_VERSION = 1;
    static final String DATABASE_CREATE =
            "create table " + DATABASE_TABLE +
                    " (_id integer primary key autoincrement, "
                    + "title text not null, isbn text not null);";

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
                              int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS titles");
            onCreate(db);
        }
    }

    @Override
    public int delete(Uri arg0, String arg1, String[] arg2) {
        // arg0 = uri
        // arg1 = selection
        // arg2 = selectionArgs
        int count=0;
        switch (uriMatcher.match(arg0)){
            case BOOKS:
                count = booksDB.delete(
                        DATABASE_TABLE,
                        arg1,
                        arg2);
                break;
            case BOOK_ID:
                String id = arg0.getPathSegments().get(1);
                count = booksDB.delete(DATABASE_TABLE,_ID + " = 4" ,arg2);
                break;
            default: throw new IllegalArgumentException("Unknown URI " + arg0);
        }
        getContext().getContentResolver().notifyChange(arg0, null);
        return count;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)){
            //get all books
            case BOOKS:
                return "vnd.android.cursor.dir/vnd.java2s.books ";

            //get a particular book
            case BOOK_ID:
                return "vnd.android.cursor.item/vnd.java2s.books ";

            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        //add a new book
        long rowID = booksDB.insert(
                DATABASE_TABLE,
                "",
                values);
        //if added successfully
        if (rowID>0)
        {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        DatabaseHelper dbHelper = new DatabaseHelper(context);
        booksDB = dbHelper.getWritableDatabase();
        return (booksDB == null)? false:true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        sqlBuilder.setTables(DATABASE_TABLE);

        if (uriMatcher.match(uri) == BOOK_ID)
            //if getting a particular book
            sqlBuilder.appendWhere(
                    _ID + " = " + uri.getPathSegments().get(1));

        if (sortOrder==null || sortOrder=="")
            sortOrder = TITLE;

        Cursor c = sqlBuilder.query(
                booksDB,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                sortOrder);

        //register to watch a content URI for changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)){
            case BOOKS:
                count = booksDB.update(
                        DATABASE_TABLE,
                        values,
                        selection,
                        selectionArgs);
                break;
            case BOOK_ID:
                count = booksDB.update(
                        DATABASE_TABLE,
                        values,
                        _ID + " = 2" ,selectionArgs);
                break;
            default: throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
}

Add the following statements to the AndroidManifest.xml file:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".ContentProvidersActivity" >
              <intent-filter >
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
          <provider android:name="BooksProvider"
              android:authorities="com.java2s.provider.Books">
          </provider>
      </application>

</manifest>

Use The Content Provider

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="ISBN" />

<EditText
    android:id="@+id/txtISBN"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Title" />

<EditText
    android:id="@+id/txtTitle"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" />

<Button
    android:text="Add title"
    android:id="@+id/btnAdd"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="onClickAddTitle" />

<Button
    android:text="Retrieve titles"
    android:id="@+id/btnRetrieve"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:onClick="onClickRetrieveTitles"  />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*from ww w.  java  2s. com*/
import android.app.Activity;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClickAddTitle(View view) {
        //add a book
        ContentValues values = new ContentValues();
        values.put(BooksProvider.TITLE, ((EditText)
                findViewById(R.id.txtTitle)).getText().toString());
        values.put(BooksProvider.ISBN, ((EditText)
                findViewById(R.id.txtISBN)).getText().toString());
        Uri uri = getContentResolver().insert(
                BooksProvider.CONTENT_URI, values);
        Toast.makeText (getBaseContext(),uri.toString(),
                Toast.LENGTH_LONG).show();
    }

    public void onClickRetrieveTitles(View view) {
        //retrieve the titles
        Uri allTitles = Uri.parse (
                "content://com.java2s.provider.Books/books");
        Cursor c;
        if (android.os.Build.VERSION.SDK_INT <11) {
            //before Honeycomb
            c = managedQuery(allTitles, null, null, null,
                    "title desc");
        } else {
            //Honeycomb and later
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allTitles, null, null, null,
                    "title desc");
            c = cursorLoader.loadInBackground();
        }
        if (c.moveToFirst()) {
            do{
                Toast.makeText (this,
                        c.getString(c.getColumnIndex(
                                BooksProvider._ID)) + ", " +
                                c.getString(c.getColumnIndex(
                                        BooksProvider.TITLE)) + ", " +
                                c.getString(c.getColumnIndex(
                                        BooksProvider.ISBN)),
                        Toast.LENGTH_SHORT).show();
            } while (c.moveToNext());
        }
    }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Custom ListView item

ListView (381/474)
« Previous

Custom ListView item

Description

The following code shows how to Custom ListView item.

Example

res\layout\row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:padding="10dip">
  <ImageView
    android:id="@+id/leftimage"
    android:layout_width="32dip"
    android:layout_height="32dip"
  />
  <ImageView
    android:id="@+id/rightimage"
    android:layout_width="32dip"
    android:layout_height="32dip"
    android:layout_alignParentRight="true"
  />

  <TextView
    android:id="@+id/line1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/rightimage"
    android:layout_toRightOf="@id/leftimage"
    android:layout_centerVertical="true"
    android:gravity="center_horizontal"
  />
</RelativeLayout>

MainActivity.java

package com.java2s.myapplication3.app;
/*from w ww  . ja va2s  . com*/
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListView list = new ListView(this);
        setContentView(list);

        CustomAdapter adapter = new CustomAdapter(this,
                R.layout.row,
                R.id.line1,
                new String[] {"XML","HTML","CSS","Javascript"});
        list.setAdapter(adapter);

    }

    private static class CustomAdapter extends ArrayAdapter<String> {

        public CustomAdapter(Context context, int layout, int resId, String[] items) {
            //Call through to ArrayAdapter implementation
            super(context, layout, resId, items);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            if(row == null) {
                row = LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
            }

            String item = getItem(position);
            ImageView left = (ImageView)row.findViewById(R.id.leftimage);
            ImageView right = (ImageView)row.findViewById(R.id.rightimage);
            TextView text = (TextView)row.findViewById(R.id.line1);

            left.setImageResource(R.drawable.ic_launcher);
            right.setImageResource(R.drawable.ic_launcher);
            text.setText(item);

            return row;
        }
    }
}
Custom ListView item

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Customize the Action Items and Application Icon

Action Bar (231/474)
« Previous

Customize the Action Items and Application Icon

Description

To display the text for the action item together with the icon, you could use the "|" operator together with the MenuItem.SHOW_AS_ACTION_WITH_TEXT constant:

MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
{/*from w  ww .j a  v  a2  s. c o m*/
    mnu1.setIcon(R.drawable.ic_launcher);
    mnu1.setShowAsAction(
        MenuItem.SHOW_AS_ACTION_IF_ROOM |
        MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}

Example

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

</LinearLayout>

package com.java2s.myapplication3.app;
/*  ww w.j  a  va  2 s  . c  om*/
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice(item);
    }

    private void CreateMenu(Menu menu)
    {
        MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
        {
            mnu1.setIcon(R.drawable.ic_launcher);
            mnu1.setShowAsAction(
                    MenuItem.SHOW_AS_ACTION_IF_ROOM |
                            MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
        {
            mnu2.setIcon(R.drawable.ic_launcher);
            mnu2.setShowAsAction(
                    MenuItem.SHOW_AS_ACTION_IF_ROOM |
                            MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
        {
            mnu3.setIcon(R.drawable.ic_launcher);
            mnu3.setShowAsAction(
                    MenuItem.SHOW_AS_ACTION_IF_ROOM |
                            MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        }
        MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
        {
            mnu4.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
        MenuItem mnu5 = menu.add(0, 4, 4, "Item 5");
        {
            mnu5.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
    }

    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId()) {
            case 0:
                Toast.makeText(this, "You clicked on Item 1",
                        Toast.LENGTH_LONG).show();
                return true;
            case 1:
                Toast.makeText(this, "You clicked on Item 2",
                        Toast.LENGTH_LONG).show();
                return true;
            case 2:
                Toast.makeText(this, "You clicked on Item 3",
                        Toast.LENGTH_LONG).show();
                return true;
            case 3:
                Toast.makeText(this, "You clicked on Item 4",
                        Toast.LENGTH_LONG).show();
                return true;
            case 4:
                Toast.makeText(this, "You clicked on Item 5",
                        Toast.LENGTH_LONG).show();
                return true;
        }
        return false;
    }

}
Customize the Action Items and Application Icon

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Database backed Content provider

Content Provider (101/474)
« Previous

Database backed Content provider

Description

The following code shows how to create Database backed Content provider.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"/>
</LinearLayout>

Java code

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
/*ww w.  java2 s .  c  o  m*/
public class MainActivity extends Activity {
  private MyDatabaseHelper mDatabaseHelper;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);

    mDatabaseHelper = new MyDatabaseHelper(this);

    Cursor c = mDatabaseHelper.query(MyDatabaseHelper.TABLE_USERS, MyDatabaseHelper.COL_NAME);
    String[] from = new String[]{MyDatabaseHelper.COL_NAME, MyDatabaseHelper.COL_EMAIL};
    int[] to = { android.R.id.text1, android.R.id.text2 };

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, from, to, 0);

    ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    addUser(null, null, 0);
    addUser("XML", "xml@example.com", 0);
    addUser("HRML", "html@example.com", 0);
    addUser("CSS", "css@example.com", 0);
  }

  private void addUser(String name, String email, long dateOfBirthMillis) {
    ContentValues values = new ContentValues();
    values.put(MyDatabaseHelper.COL_NAME, name);

    if (email != null) {
      values.put(MyDatabaseHelper.COL_EMAIL, email);
    }

    if (dateOfBirthMillis != 0) {
      values.put(MyDatabaseHelper.COL_DOB, dateOfBirthMillis);
    }

    try {
      mDatabaseHelper.insert(MyDatabaseHelper.TABLE_USERS, values);
    } catch (MyDatabaseHelper.NotValidException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
  }
}

class MyDatabaseHelper extends SQLiteOpenHelper {
  public static final String TABLE_USERS = "users";
  public static final String COL_ID = BaseColumns._ID;
  public static final String COL_NAME = "name";
  public static final String COL_EMAIL = "email";
  public static final String COL_DOB = "date_of_birth";
  private static final String DATABASE_NAME = "my_app.db";
  private static final int DATABASE_VERSION = 1;

  public MyDatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_USERS + " ("
        + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + COL_NAME + " TEXT NOT NULL,"
        + COL_EMAIL + " TEXT,"
        + COL_DOB + " INTEGER"
        + ");");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS + ";");
    onCreate(db);
  }

  public long insert(String tableName, ContentValues values) throws NotValidException {
    validate(values);

    return getWritableDatabase().insert(tableName, null, values);
  }

  public int update(String tableName, long id, ContentValues values) throws NotValidException {
    validate(values);

    String selection = COL_ID + " = ?";
    String[] selectionArgs = {String.valueOf(id)};

    return getWritableDatabase().update(tableName, values, selection, selectionArgs);
  }

  public int delete(String tableName, long id) {
    String selection = COL_ID + " = ?";
    String[] selectionArgs = {String.valueOf(id)};

    return getWritableDatabase().delete(tableName, selection, selectionArgs);
  }

  protected void validate(ContentValues values) throws NotValidException {
    if (!values.containsKey(COL_NAME) || values.getAsString(COL_NAME) == null || values.getAsString(COL_NAME).isEmpty()) {
      throw new NotValidException("User name must be set");
    }
  }

  public Cursor query(String tableName, String orderedBy) {
    String[] projection = {COL_ID, COL_NAME, COL_EMAIL, COL_DOB};
    return getReadableDatabase().query(tableName, projection, null, null, null, null, orderedBy);
  }

  public static class NotValidException extends Throwable {
    public NotValidException(String msg) {
      super(msg);
    }
  }
}

The code above generates the following result.

Database backed Content provider

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Determine portrait mode or landscape mode

Activity (63/474)
« Previous

Determine portrait mode or landscape mode

Description

You can use the WindowManager to determine whether the device is currently in portrait mode or landscape mode.

Example

package com.java2s.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
// w w w.  ja va2  s .com
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //get the current display info
        WindowManager wm = getWindowManager();
        Display d = wm.getDefaultDisplay();
        if (d.getWidth() > d.getHeight())
        {
            //landscape mode
        }else{
            //portrait mode
        }
    }
}

Note

The code above check the orientation in the onCreate method. The logic is only called when the onCreate method is invoked

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Dimension Resources

Resources (37/474)
« Previous

Dimension Resources

Description

Pixels, inches, and points are all examples of dimensions that can play a part in XML layouts or Java code.

Example

The following code shows you can use dimension resources in XML.

<resources>
    <dimen name="mysize_in_pixels">1px</dimen>
    <dimen name="mysize_in_dp">5dp</dimen>
    <dimen name="medium_size">100sp</dimen>
</resources>

You can specify the dimensions in any of the following units:

  • px: Pixels
  • in: Inches
  • mm: Millimeters
  • pt: Points
  • dp: Density-independent pixels based on a 160dpi screen
  • sp: Scale-independent pixels

The following code shows how to access the defined Dimension Resources.

float dimen = activity.getResources().getDimension(R.dimen.mysize_in_pixels);

mysize_in_pixels is defined in the resource file above.

Use Dimension Resources in XML

The following code has the definition for Dimension Resources in XML.

<resources>
    <dimen name="mysize_in_pixels">1px</dimen>
    <dimen name="mysize_in_dp">5dp</dimen>
    <dimen name="medium_size">100sp</dimen>
</resources>

The following xml layout resource references the dimensions defined above.

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textSize="@dimen/medium_size"/>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Dispatch event to a control

Event (299/474)
« Previous

Dispatch event to a control

Description

The following code shows how to Dispatch event to a control.

Example

Layout activity_main.xml file

<?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/text_touch"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Scroll Anywhere Here" />

    <HorizontalScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#CCC">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal" >
            <ImageView
                android:layout_width="250dp"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/ic_launcher" />
            <ImageView
                android:layout_width="250dp"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/ic_launcher" />
            <ImageView
                android:layout_width="250dp"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/ic_launcher" />
            <ImageView
                android:layout_width="250dp"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/ic_launcher" />
        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

Main activity Java code

package com.java2s.myapplication3.app;
//from   w  w w.  j  a  va 2 s  .  c o  m
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnTouchListener {

    private TextView mTouchText;
    private HorizontalScrollView mScrollView;

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

        mTouchText = (TextView) findViewById(R.id.text_touch);
        mScrollView = (HorizontalScrollView) findViewById(R.id.scroll_view);
        mTouchText.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        event.setLocation(event.getX(), mScrollView.getHeight() / 2);
        mScrollView.dispatchTouchEvent(event);
        return true;
    }
}
Dispatch event to a control

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Display a Dialog Window

Dialog (277/474)
« Previous

Display a Dialog Window

Description

To display a dialog window to get a confirmation from the user, you can override the onCreateDialog() protected method defined in the Activity base class to display a dialog window.

Example

Java code

package com.java2s.app;
//from   w w  w  . j  av  a2 s  .  c  o  m
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    CharSequence[] items = {"XML", "CSS", "HTML"};
    boolean[] itemsChecked = new boolean[items.length];

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

        new AlertDialog.Builder(this)
                .setIcon(R.drawable.ic_launcher)
                .setTitle("Title text...")
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Toast.makeText(getBaseContext(),
                                        "OK clicked!", Toast.LENGTH_SHORT).show();
                            }
                        }
                ).setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Toast.makeText(getBaseContext(),
                                "Cancel clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
        ).setMultiChoiceItems(items, itemsChecked,
                new DialogInterface.OnMultiChoiceClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int which, boolean isChecked) {
                        Toast.makeText(getBaseContext(),
                                items[which] + (isChecked ? " checked!" : " unchecked!"),
                                Toast.LENGTH_SHORT).show();
                    }
                }
        ).create().show();
    }

}
Display a Dialog Window

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Display a Progress Dialog

Dialog (281/474)
« Previous

Display a Progress Dialog

Description

The following code shows how to display a progress dialog.

Example

package com.java2s.app;
//  w ww  .j  a  v  a  2 s  .  c o m
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;

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

        final ProgressDialog dialog = ProgressDialog.show(
                this, "Doing something", "Please wait...", true);
        new Thread(new Runnable() {
            public void run() {
                try {
                    //---simulate doing something lengthy---
                    Thread.sleep(5000);
                    dialog.dismiss();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
Display a Progress Dialog

Note

To perform a long-running task in the background, you created a Thread using a Runnable block.

After the five seconds elapse, you dismiss the dialog by calling the dismss() method.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Display all contacts in a ListView

ListView (382/474)
« Previous

Display all contacts in a ListView

Description

The following code shows how to Display all contacts in a ListView.

Example

Main Activity Java code

package com.java2s.myapplication3.app;
//w  w  w .  j  a v a  2 s  . c o  m
import android.app.AlertDialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    Cursor mContacts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);

        //
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, mContacts,
                new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                new int[] { android.R.id.text1 });
        setListAdapter(mAdapter);
        // Listen for item selections
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        if (mContacts.moveToPosition(position)) {
            int selectedId = mContacts.getInt(0); // _ID column
            // Gather email data from email table
            Cursor email = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    new String[] { ContactsContract.CommonDataKinds.Email.DATA },
                    ContactsContract.Data.CONTACT_ID + " = " + selectedId, null, null);

            //Build the dialog message
            StringBuilder sb = new StringBuilder();
            sb.append(email.getCount() + " Emails\n");
            if (email.moveToFirst()) {
                do {
                    sb.append("Email: " + email.getString(0));
                    sb.append('\n');
                } while (email.moveToNext());
                sb.append('\n');
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(mContacts.getString(1)); // Display name
            builder.setMessage(sb.toString());
            builder.setPositiveButton("OK", null);
            builder.create().show();

            email.close();
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Display Notifications

Notification (189/474)
« Previous

Display Notifications

Description

The following code shows how to use the NotificationManager to display a persistent message at the top of the device, commonly known as the status bar.

Example

Add the following statements in bold to the AndroidManifest.xml file:

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

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".NotificationsActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NotificationView"
            android:label="Details of notification">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Add the following statements to the main layut xml file:

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

<Button
    android:id="@+id/btn_displaynotif"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Display Notification"
    android:onClick="onClick"/>

</LinearLayout>

Add the following statements to the MainActivity.java file:

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
//from   w  w  w  .  j a  va2  s .  co m
public class MainActivity extends Activity {
    int notificationID = 1;

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

    public void onClick(View view) {
        displayNotification();
    }

    protected void displayNotification()
    {
        Intent i = new Intent(this, NotificationView.class);
        i.putExtra("notificationID", notificationID);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);

        NotificationManager nm = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);

        Notification notif = new Notification(
            R.drawable.ic_launcher,
            "Reminder: Meeting starts in 5 minutes",
            System.currentTimeMillis());

        CharSequence from = "System Alarm";
        CharSequence message = "Buzz at 3pm...";

        notif.setLatestEventInfo(this, from, message, pendingIntent);

        //---100ms delay, vibrate for 250ms, pause for 100 ms and
        // then vibrate for 500ms---
        notif.vibrate = new long[] { 100, 250, 100, 500};
        nm.notify(notificationID, notif);
    }

}

Populate the SecondActivity.java file as follows

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
/*from www  .  j a  v  a  2 s  . c  o  m*/
public class SecondActivity extends Activity
{
   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.notification);
       NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
       nm.cancel(getIntent().getExtras().getInt("notificationID"));
   }
}

Populate the notification.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Here are the details for the notification..." />
</LinearLayout>

Note

A PendingIntent object helps you to perform an action on your application's behalf, often at a later time, regardless of whether your application is running or not.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Display the compass direction

Sensor (198/474)
« Previous

Display the compass direction

Description

The following code shows how to .

Example

Main layout activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:id="@+id/direction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textSize="64dip"
    android:textStyle="bold"
  />
  <TextView
    android:id="@+id/values"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
  />
</RelativeLayout>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w  w w  .j a  v  a2  s.  co  m*/
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {

    //Allocate data arrays once and reuse
    float[] temp = new float[9];
    float[] rotation = new float[9];
    float[] values = new float[3];

    private SensorManager mSensorManager;
    private Sensor mAccelerometer, mField;
    private TextView valueView, directionView;

    private float[] mGravity = new float[3];
    private float[] mMagnetic = new float[3];

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

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        valueView = (TextView) findViewById(R.id.values);
        directionView = (TextView) findViewById(R.id.direction);
    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
        mSensorManager.registerListener(this, mField, SensorManager.SENSOR_DELAY_UI);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    private void updateDirection() {
        SensorManager.getRotationMatrix(temp, null, mGravity, mMagnetic);
        SensorManager.remapCoordinateSystem(temp, SensorManager.AXIS_X, SensorManager.AXIS_Z, rotation);
        SensorManager.getOrientation(rotation, values);
        for (int i = 0; i < values.length; i++) {
            Double degrees = (values[i] * 180) / Math.PI;
            values[i] = degrees.floatValue();
        }
        directionView.setText(getDirectionFromDegrees(values[0]));
        valueView.setText(String.format("Azimuth: %1$1.2f, Pitch: %2$1.2f, Roll: %3$1.2f",
                values[0], values[1], values[2]));
    }

    private String getDirectionFromDegrees(float degrees) {
        if (degrees >= -22.5 && degrees < 22.5) {
            return "N";
        }
        if (degrees >= 22.5 && degrees < 67.5) {
            return "NE";
        }
        if (degrees >= 67.5 && degrees < 112.5) {
            return "E";
        }
        if (degrees >= 112.5 && degrees < 157.5) {
            return "SE";
        }
        if (degrees >= 157.5 || degrees < -157.5) {
            return "S";
        }
        if (degrees >= -157.5 && degrees < -112.5) {
            return "SW";
        }
        if (degrees >= -112.5 && degrees < -67.5) {
            return "W";
        }
        if (degrees >= -67.5 && degrees < -22.5) {
            return "NW";
        }

        return null;
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                System.arraycopy(event.values, 0, mGravity, 0, event.values.length);
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                System.arraycopy(event.values, 0, mMagnetic, 0, event.values.length);
                break;
            default:
                return;
        }

        if (mGravity != null && mMagnetic != null) {
            updateDirection();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Display the Progress of an Operation

Dialog (282/474)
« Previous

Display the Progress of an Operation

Description

The following code shows how to display the Progress of an Operation.

Example

Java code

package com.java2s.app;
//  ww  w .jav  a2s. c  o  m
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    ProgressDialog progressDialog;

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

        progressDialog = new ProgressDialog(this);
        progressDialog.setIcon(R.drawable.ic_launcher);
        progressDialog.setTitle("Downloading files...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Toast.makeText(getBaseContext(),
                                "OK clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
        );
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int whichButton) {
                        Toast.makeText(getBaseContext(),
                                "Cancel clicked!", Toast.LENGTH_SHORT).show();
                    }
                }
        );
        progressDialog.show();
        progressDialog.setProgress(0);

        new Thread(new Runnable() {
            public void run() {
                for (int i = 1; i <= 15; i++) {
                    try {
                        //---simulate doing something lengthy---
                        Thread.sleep(1000);
                        //---update the dialog---
                        progressDialog.incrementProgressBy((int) (100 / 15));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                progressDialog.dismiss();
            }
        }).start();
    }
}
Display the Progress of an Operation

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download a series of images asynchronously

Network (175/474)
« Previous

Download a series of images asynchronously

Description

The following code shows how to Download a series of images asynchronously.

Example

Add the following statement to the AndroidManifest.xml file:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".NetworkingActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout xml file

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

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

        </LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/* w ww.  ja v a2 s  .  c om*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {
    ImageView img;

    private InputStream OpenHttpConnection(String urlString) throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex)
        {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            Log.d("NetworkingActivity", e1.getLocalizedMessage());
        }
        return bitmap;
    }

    private class DownloadImageTask extends AsyncTask<String, Bitmap, Long> {
        protected Long doInBackground(String... urls) {
            long imagesCount = 0;
            for (int i = 0; i < urls.length; i++) {
                Bitmap imageDownloaded = DownloadImage(urls[i]);
                if (imageDownloaded != null)  {
                    imagesCount++;
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    publishProgress(imageDownloaded);
                }
            }
            return imagesCount;
        }
        protected void onProgressUpdate(Bitmap... bitmap) {
            img.setImageBitmap(bitmap[0]);
        }
        protected void onPostExecute(Long imagesDownloaded) {
            Toast.makeText(getBaseContext(),
                    "Total " + imagesDownloaded + " images downloaded",
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView) findViewById(R.id.img);
        new DownloadImageTask().execute(
                "http://www.java2s.com/style/download.png",
                "http://www.java2s.com/style/download.png");
    }

}
Download a series of images asynchronously

Note

When working with the Android emulator, you may frequently need to access data hosted on the local web server using localhost.

In such cases, you should use the special IP address of 10.0.2.2 (not 127.0.0.1) to refer to the host computer's loopback interface. From the Android emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download App from Market

Intent (145/474)
« Previous

Download App from Market

Description

The following code shows how to Download App from Market.

Example

package com.java2s.myapplication3.app;
/*  w  w w  .  j  a  v  a  2  s  .c o  m*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity {

    private static final int REQUEST_RECOGNIZE = 100;

    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        setContentView(tv);

        Intent intent = new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                "Tell Me Your Name");
        try {
            startActivityForResult(intent, REQUEST_RECOGNIZE);
        } catch (ActivityNotFoundException e) {
            showDownloadDialog();
        }
    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                this);
        builder.setTitle("Not Available");
        builder.setMessage("No recognition application installed."
                + "  Would you like to download one?");
        builder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                        marketIntent.setData(Uri.parse("market://details?id=com.google.android.voicesearch"));
                    }
                }
        );
        builder.setNegativeButton("No", null);
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode,
                                    int resultCode, Intent data) {
        if (requestCode == REQUEST_RECOGNIZE && resultCode == Activity.RESULT_OK) {
            ArrayList<String> matches = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            StringBuilder sb = new StringBuilder();
            for (String piece : matches) {
                sb.append(piece);
                sb.append('\n');
            }
            tv.setText(sb.toString());
        } else {
            Toast.makeText(this, "Operation Canceled",
                    Toast.LENGTH_SHORT).show();
        }
    }
}
Download App from Market

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download Binary Data from the web

Network (176/474)
« Previous

Download Binary Data from the web

Description

The following code shows how to Download Binary Data from the web.

Example

Add the following statement to the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Layout xml file

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

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*from  w w  w  .  ja  va2s  . com*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {
    ImageView img;

    private InputStream OpenHttpConnection(String urlString) throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex)
        {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            Log.d("NetworkingActivity", e1.getLocalizedMessage());
        }
        return bitmap;
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        protected Bitmap doInBackground(String... urls) {
            return DownloadImage(urls[0]);
        }

        protected void onPostExecute(Bitmap result) {
            ImageView img = (ImageView) findViewById(R.id.img);
            img.setImageBitmap(result);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadImageTask().execute(
                "http://www.java2s.com/style/download.png");
    }
}
Download Binary Data from the web

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download from market

Intent (133/474)
« Previous

Download from market

Description

The following code shows how to download app from market.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="main content" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="onLayarClick"
        android:text="main layar" />

</RelativeLayout>

Java code

//from   www  .ja  v  a 2  s . com
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

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

  public void onLayarClick(View v) {
    if (!ActivityHelper.isLayarAvailable(this)) {
      ActivityHelper.showDownloadDialog(this);
    } else {
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_VIEW);
      Uri uri = Uri.parse("layar://teather/?action=refresh");
      intent.setData(uri);
      startActivity(intent);
    }

  }

}
class ActivityHelper {

  public static boolean isLayarAvailable(Context ctx) {
    PackageManager pm = ctx.getPackageManager();

    try {
      pm.getApplicationInfo("com.layar", 0);
      return true;
    } catch (PackageManager.NameNotFoundException e) {
      return false;
    }

  }

  public static AlertDialog showDownloadDialog(final Context ctx) {
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(ctx);
    downloadDialog.setTitle("Layar is not available");
    downloadDialog
        .setMessage("Do you want to download it from the market?");
    downloadDialog.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialogInterface, int i) {
            Uri uri = Uri.parse("market://details?id=com.layar");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
              ctx.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {
              Toast.makeText(ctx, "Market not installed",
                  Toast.LENGTH_SHORT).show();
            }
          }

        });

    downloadDialog.setNegativeButton("No",
        new DialogInterface.OnClickListener() {

          @Override
          public void onClick(DialogInterface dialogInterface, int i) {
          }

        });

    return downloadDialog.show();
  }
}
Download from market

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download Image from a URL

Network (177/474)
« Previous

Download Image from a URL

Description

The following code shows how to Download Image from a URL.

Example

Manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Main layout xml file

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

  <Button android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Download file"
      android:onClick="startDownload"
      />
   <TextView android:id="@+id/status"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="click to start"
   />
</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
// w ww .ja va2 s  .  c  o m
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.net.URL;

public class MainActivity extends Activity {

    private Runnable imageDownloader = new Runnable() {

        public void run() {
            try {
                URL imageUrl = new URL("http", "android.com", "/images/froyo.png");
                Bitmap image = BitmapFactory.decodeStream(imageUrl.openStream());
                if (image != null) {
                    Log.i("DL", "Successfully retrieved file!");
                } else {
                    Log.i("DL", "Failed decoding file from stream");
                }
            } catch (Exception e) {
                Log.i("DL", "Failed downloading file!");
                e.printStackTrace();
            }
        }
    };

    public void startDownload(View source) {
        new Thread(imageDownloader, "Download thread").start();
        TextView statusText = (TextView) findViewById(R.id.status);
        statusText.setText("Download started...");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Download Image from a URL

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download Image With Message Passing

Network (178/474)
« Previous

Download Image With Message Passing

Description

The following code shows how to Download Image With Message Passing.

Example

Manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="Download file"
      android:onClick="startDownload"
      />
   <TextView android:id="@+id/status"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="click to start"
   />
</LinearLayout>

Main Activity Java code

import java.net.URL;
/*  ww  w  .  j  a va 2 s . c o  m*/
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity implements
         Handler.Callback {

   private Handler handler = new Handler(this);

   private Runnable imageDownloader = new Runnable() {

      private void sendMessage(String what) {
         Bundle bundle = new Bundle();
         bundle.putString("status", what);
         Message message = new Message();
         message.setData(bundle);
         handler.sendMessage(message);
      }

      public void run() {
         sendMessage("Download started");
         try {
            URL imageUrl = new URL("http://www.android.com/images/froyo.png");
            Bitmap image = BitmapFactory.decodeStream(imageUrl.openStream());
            if (image != null) {
               sendMessage("Successfully retrieved file!");
            } else {
               sendMessage("Failed decoding file from stream");
            }
         } catch (Exception e) {
            sendMessage("Failed downloading file!");
            e.printStackTrace();
         }
      }
   };

   public void startDownload(View source) {
      new Thread(imageDownloader, "Download thread").start();
   }

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

   public boolean handleMessage(Message msg) {
      String text = msg.getData().getString("status");
      TextView statusText = (TextView) findViewById(R.id.status);
      statusText.setText(text);
      return true;
   }
}
Download Image With Message Passing

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Download Text Content

Network (179/474)
« Previous

Download Text Content

Description

The following code shows how to Download Text Content.

Example

Add the following statement to the AndroidManifest.xml file:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".NetworkingActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout xml file

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

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*ww w.  j  ava 2 s  . com*/
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends Activity {
    ImageView img;

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;
    }

    private String DownloadText(String URL) {
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e) {
            Log.d("Networking", e.getLocalizedMessage());
            return "";
        }

        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];
        try {
            while ((charRead = isr.read(inputBuffer)) > 0) {
                String readString =
                        String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            Log.d("Networking", e.getLocalizedMessage());
            return "";
        }
        return str;
    }

    private class DownloadTextTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return DownloadText(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadTextTask().execute("http://java2s.com");
    }
}
Download Text Content

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw a Pyramid with Texture in OpenGL

OpenGL (399/474)
« Previous

Draw a Pyramid with Texture in OpenGL

Description

The following code shows how to Draw a Pyramid with Texture in OpenGL.

Example

Main Activity Java code

package com.java2s.myapplication4.app;
// w w w  .  ja  v  a  2  s  .c  o m
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MainActivity extends Activity {

    private GLSurfaceView glView;
    private TexturedPyramid pyramid;
    private Bitmap texture;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        glView = new GLSurfaceView(this);
        glView.setRenderer(new MyOpenGLRenderer());
        setContentView(glView);
    }

    class MyOpenGLRenderer implements Renderer {

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            gl.glViewport(0, 0, width, height);
            gl.glMatrixMode(GL10.GL_PROJECTION);
            gl.glLoadIdentity();
            GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);
            gl.glMatrixMode(GL10.GL_MODELVIEW);
            gl.glLoadIdentity();
        }

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            texture = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            int textureIds[] = new int[1];
            gl.glGenTextures(1, textureIds, 0);
            gl.glBindTexture(GL10.GL_TEXTURE_2D, textureIds[0]);
            GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, texture, 0);
            gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
            gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
            gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
            texture.recycle();
            pyramid = new TexturedPyramid(textureIds[0]);
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            gl.glClearColor(0.0f, 0.0f, 0.0f, 1f);
            gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            gl.glLoadIdentity();
            gl.glTranslatef(0.0f, 0.0f, -5.0f);
            pyramid.draw(gl);
        }
    }
}

class TexturedPyramid {

    private int textureId;
    private FloatBuffer vertexBuffer;
    private static final int VERTEX_SIZE = (3 + 2) * 4;
    private float vertices[] = {

            0.0f, 1.0f, 0.0f, 0.5f, 0.0f, // V1 + mapping
            -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // V2
            0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // V3

            0.0f, 1.0f, 0.0f, 0.5f, 0.0f, // V1
            0.0f, 0.0f, -1.0f, 0.0f, 1.0f, // V3
            1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // V4

            0.0f, 1.0f, 0.0f, 0.5f, 0.0f, // V1
            1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // V4
            -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // V2

    };

    private float rotation = 0.1f;

    public TexturedPyramid(int textureId) {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(TexturedPyramid.VERTEX_SIZE * 3 * 3);
        byteBuffer.order(ByteOrder.nativeOrder());
        vertexBuffer = byteBuffer.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.flip();
        this.textureId = textureId;
    }

    public void draw(GL10 gl) {
        rotation += 1.0f;
        gl.glRotatef(rotation, 1f, 1f, 1f);

        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        vertexBuffer.position(0);
        gl.glVertexPointer(3, GL10.GL_FLOAT, TexturedPyramid.VERTEX_SIZE, vertexBuffer);
        vertexBuffer.position(3);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, TexturedPyramid.VERTEX_SIZE, vertexBuffer);

        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3 * 3);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    }
}
Draw a Pyramid with Texture in OpenGL

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw a Triangle using OpenGL

OpenGL (400/474)
« Previous

Draw a Triangle using OpenGL

Description

The following code shows how to Draw a Triangle using OpenGL.

Example

Main Activity Java code

package com.java2s.myapplication4.app;
//from  www.  j a  v a 2  s  . co  m
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

class Triangle {

    private FloatBuffer vertexBuffer;
    private float vertices[] = {
            100.0f, 150.0f, 0.0f, // V1 - first vertex (x,y,z)
            219.0f, 150.0f, 0.0f, // V2 - second vertex
            160.0f, 279.0f, 0.0f // V3 - third vertex
    };

    public Triangle() {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(3 * 3 * 4);
        byteBuffer.order(ByteOrder.nativeOrder());
        vertexBuffer = byteBuffer.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.flip();
    }

    public void draw(GL10 gl) {
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glColor4f(0.0f, 1.0f, 0.0f, 0.5f);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, vertices.length / 3);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    }
}

public class MainActivity extends Activity {

    private GLSurfaceView glView;
    private Triangle triangle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        glView = new GLSurfaceView(this);
        glView.setRenderer(new MyOpenGLRenderer());
        setContentView(glView);
    }

    class MyOpenGLRenderer implements Renderer {
        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            Log.d("MyOpenGLRenderer", "Surface changed. Width=" + width + " Height=" + height);
            gl.glViewport(0, 0, width, height);
            gl.glMatrixMode(GL10.GL_PROJECTION);
            gl.glLoadIdentity();
            gl.glOrthof(0, 320, 0, 480, 1, -1);
        }

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            Log.d("MyOpenGLRenderer", "Surface created");
            triangle = new Triangle();
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            gl.glClearColor(0.0f, 0.5f, 0.0f, 1f);
            gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            triangle.draw(gl);
        }
    }
}
Draw a Triangle using OpenGL

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw and resize

View (462/474)
« Previous

Draw and resize

Description

The following code shows how to Draw and resize.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

res\drawable\box.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid
        android:color="@android:color/transparent"/>
    <stroke
        android:width="3dp"
        android:color="#F00" />
</shape>

res\layout\activity_main.xml

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Android Recipes" />

    <RadioGroup
        android:id="@+id/container_options"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="#CCC">
        <RadioButton
            android:id="@+id/option_box"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Box" />
        <RadioButton
            android:id="@+id/option_arrow"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Arrow" />
    </RadioGroup>

</LinearLayout>

MainActivity.java

import android.app.Activity;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RadioGroup;
/*  w  w  w .  ja v a2  s  . c om*/
import java.util.ArrayList;

public class MainActivity extends Activity implements View.OnTouchListener {

    private RadioGroup mOptions;

    private ArrayList<Drawable> mMarkers;
    private Drawable mTrackingMarker;
    private Point mTrackingPoint;

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

        //Receive touch events for the view we want to draw on
        findViewById(R.id.textview).setOnTouchListener(this);

        mOptions = (RadioGroup) findViewById(R.id.container_options);

        mMarkers = new ArrayList<Drawable>();
    }

    /*
     * Touch events from the view we are monitoring
     * will be delivered here.
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (mOptions.getCheckedRadioButtonId()) {
            case R.id.option_box:
                handleEvent(R.id.option_box, v, event);
                break;
            case R.id.option_arrow:
                handleEvent(R.id.option_arrow, v, event);
                break;
            default:
                return false;
        }
        return true;
    }

    /*
     * Process touch events when user has selected to draw a box
     */
    private void handleEvent(int optionId, View v, MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Drawable current = markerAt(x, y);
                if (current == null) {
                    //Add a new marker on a new touch
                    switch(optionId) {
                        case R.id.option_box:
                            mTrackingMarker = addBox(v, x, y);
                            mTrackingPoint = new Point(x, y);
                            break;
                        case R.id.option_arrow:
                            mTrackingMarker = addFlag(v, x, y);
                            break;
                    }
                } else {
                    //Remove the existing marker
                    removeMarker(v, current);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                //Update the current marker as we move
                if (mTrackingMarker != null) {
                    switch(optionId) {
                        case R.id.option_box:
                            resizeBox(v, mTrackingMarker, mTrackingPoint, x, y);
                            break;
                        case R.id.option_arrow:
                            offsetFlag(v, mTrackingMarker, x, y);
                            break;
                    }

                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                //Clear state when gesture is over
                mTrackingMarker = null;
                mTrackingPoint = null;
                break;
        }
    }
    private Drawable addBox(View v, int x, int y) {
        Drawable box = getResources().getDrawable(R.drawable.box);
        Rect bounds = new Rect(x, y, x, y);
        box.setBounds(bounds);
        mMarkers.add(box);
        v.getOverlay().add(box);
        return box;
    }
    private void resizeBox(View v, Drawable target, Point trackingPoint, int x, int y) {
        Rect bounds = new Rect(target.getBounds());
        if (x < trackingPoint.x) {
            bounds.left = x;
        } else {
            bounds.right = x;
        }
        if (y < trackingPoint.y) {
            bounds.top = y;
        } else {
            bounds.bottom = y;
        }

        //Update drawable bounds and redraw
        target.setBounds(bounds);
        v.invalidate();
    }

    /*
     * Add a new flag marker at the given coordinate
     */
    private Drawable addFlag(View v, int x, int y) {
        //Make a new marker drawable
        Drawable marker = getResources().getDrawable(R.drawable.flag_arrow);

        //Create bounds to match image size
        Rect bounds = new Rect(0, 0,
                marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
        //Center marker bottom around coordinate
        bounds.offset(x - (bounds.width() /2), y - bounds.height());
        marker.setBounds(bounds);
        //Add to the overlay
        mMarkers.add(marker);
        v.getOverlay().add(marker);

        return marker;
    }

    /*
     * Update the position of an existing flag marker
     */
    private void offsetFlag(View v, Drawable marker, int x, int y) {
        Rect bounds = new Rect(marker.getBounds());
        //Move drawable bounds to the next align with the new coordinate
        bounds.offset(x - bounds.left - (bounds.width() / 2),
                y - bounds.top - bounds.height());
        //Update and redraw
        marker.setBounds(bounds);
        v.invalidate();
    }

    /*
     * Remove the requested marker item
     */
    private void removeMarker(View v, Drawable marker) {
        mMarkers.remove(marker);
        v.getOverlay().remove(marker);
    }

    /*
     * Find the first marker that contains the requested
     * coordinate, if one exists.
     */
    private Drawable markerAt(int x, int y) {
        //Return the first marker found containing the given point
        for (Drawable marker : mMarkers) {
            if (marker.getBounds().contains(x, y)) {
                return marker;
            }
        }

        return null;
    }
}
Draw and resize

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw Bitmap on Canvas

Canvas (252/474)
« Previous

Draw Bitmap on Canvas

Description

The following code shows how to Draw Bitmap on Canvas.

Example

Main Activity Java code

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.widget.ImageView;
//from   ww  w  .j a  v a  2  s . c  om
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView iv = new ImageView(this);

        Bitmap source = BitmapFactory.decodeResource(getResources(), R.drawable.dog);
        Bitmap mask = BitmapFactory.decodeResource(getResources(), R.drawable.triangle);

        Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLACK);

        canvas.drawBitmap(mask, 0, 0, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        paint.setXfermode(null);

        iv.setImageBitmap(result);
        setContentView(iv);
    }
}
Draw Bitmap on Canvas

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw Canvas With Alpha

Canvas (253/474)
« Previous

Draw Canvas With Alpha

Description

The following code shows how to Draw Canvas With Alpha.

Example

Main Activity Java code

//  ww  w.j av a 2s  .c om
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

import java.util.Random;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(new CanvasView(this));
   }

   class CanvasView extends View {
      Paint paint;
      Random random = new Random();

      public CanvasView(Context context) {
         super(context);
      }

      @Override
      protected void onDraw(Canvas canvas) {
         canvas.drawRGB(0, 0, 0);
         for (int i = 0; i < 10; i++) {
            paint = new Paint();
            paint.setARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256));
            canvas.drawLine(random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
                     random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), paint);
            canvas.drawCircle(random.nextInt(canvas.getWidth() - 30), random.nextInt(canvas.getHeight() - 30),
                     random.nextInt(30), paint);
            canvas.drawRect(random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
                     random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), paint);
         }
      }
   }
}
Draw Canvas With Alpha

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw Canvas with Random Color

Canvas (254/474)
« Previous

Draw Canvas with Random Color

Description

The following code shows how to Draw Canvas with Random Color .

Example

Main Activity Java code

//w w  w  .j a v a 2s  . co m

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;

import java.util.Random;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(new CanvasView(this));
   }

   class CanvasView extends View {
      Random random = new Random();

      public CanvasView(Context context) {
         super(context);
      }

      @Override
      protected void onDraw(Canvas canvas) {
         canvas.drawRGB(random.nextInt(256), random.nextInt(256), random.nextInt(256));
      }
   }
}
Draw Canvas with Random Color

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw Image loaded from URL on canvas

Canvas (255/474)
« Previous

Draw Image loaded from URL on canvas

Description

The following code shows how to Draw Image loaded from URL on canvas.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.manning.aip.motivator"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Main"
                  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>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Main layout xml file

<?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:background="#ffffff"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />
</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
//from  w  ww  .ja va2 s.  c o m
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Window;
import android.widget.ImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {

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

        try {
            URL url = new URL("http://www.java2s.com/style/download.png");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(5000);
            Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream());
            conn.disconnect();

            Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888);
            output.eraseColor(Color.BLACK);

            Canvas canvas = new Canvas(output);
            canvas.drawBitmap(kitten, 125, 125, new Paint()); // bitmap, left, top, paint
            canvas.drawBitmap(frame, 0, 0, new Paint());

            Paint textPaint = new Paint();
            textPaint.setColor(Color.WHITE);
            textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
            textPaint.setTextAlign(Align.CENTER);
            textPaint.setAntiAlias(true);
            textPaint.setTextSize(36);
            canvas.drawText("Android", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint);

            ImageView imageView = (ImageView) this.findViewById(R.id.imageView);
            imageView.setImageBitmap(output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw Random Shapes on Canvas

Canvas (256/474)
« Previous

Draw Random Shapes on Canvas

Description

The following code shows how to Draw Random Shapes on Canvas.

Example

Main Activity Java code

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
//from  w ww .ja v a  2 s .  c  o m
import java.util.Random;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(new CanvasView(this));
   }

   class CanvasView extends View {
      Paint paint;
      Random random = new Random();

      public CanvasView(Context context) {
         super(context);
      }

      @Override
      protected void onDraw(Canvas canvas) {
         canvas.drawRGB(0, 0, 0);
         for (int i = 0; i < 10; i++) {
            paint = new Paint();
            paint.setARGB(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
            canvas.drawLine(random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
                     random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), paint);
            canvas.drawCircle(random.nextInt(canvas.getWidth() - 30), random.nextInt(canvas.getHeight() - 30),
                     random.nextInt(30), paint);
            canvas.drawRect(random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
                     random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), paint);
         }
      }
   }
}
Draw Random Shapes on Canvas

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw Shapes, Text and Bitmap

Canvas (257/474)
« Previous

Draw Shapes, Text and Bitmap

Description

The following code shows how to Draw Shapes, Text and Bitmap.

Example

Main Activity Java code

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
/* w  ww.  j a v  a 2  s . c om*/
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ShapesAndTextBitmapView view = new ShapesAndTextBitmapView(this);
      setContentView(view);
   }
}
class ShapesAndTextBitmapView extends View {

   private Paint paint;
   private Bitmap bitmap;

   public ShapesAndTextBitmapView(Context context) {
      super(context);
      bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.copter);
   }

   @Override
   protected void onDraw(Canvas canvas) {
      canvas.drawRGB(0, 0, 0);
      drawShapes(canvas);
      drawBitmap(canvas);
   }

   private void drawShapes(Canvas canvas) {
      int side = canvas.getWidth() / 5;
      paint = new Paint();
      paint.setARGB(255, 255, 0, 0);
      canvas.drawRect(side, canvas.getHeight() - 60 - side, side + side, canvas.getHeight() - 60, paint);
      paint.setARGB(255, 0, 255, 0);
      canvas.drawCircle(side * 2 + side / 2, canvas.getHeight() - 60 - side / 2, side / 2, paint);
      paint.setARGB(255, 0, 0, 255);
      paint.setStyle(Paint.Style.FILL);
      Path triangle = new Path();
      triangle.moveTo(side * 3 + 30, canvas.getHeight() - 60 - side);
      triangle.lineTo(side * 3 + 60, canvas.getHeight() - 60);
      triangle.lineTo(side * 3, canvas.getHeight() - 60);
      triangle.lineTo(side * 3 + 30, canvas.getHeight() - 60 - side);
      canvas.drawPath(triangle, paint);
   }

   private void drawBitmap(Canvas canvas) {
      paint = new Paint();
      canvas.drawBitmap(bitmap, 0, 0, paint);
   }
}
Draw Shapes, Text and Bitmap

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw text on Canvas

Canvas (258/474)
« Previous

Draw text on Canvas

Description

The following code shows how to Draw text on Canvas.

Example

Main layout xml file

<?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:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.widget.ImageView;
/*from   www  .  java2  s.  c  o m*/
public class MainActivity extends Activity {

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

        Bitmap bitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.RGB_565);
        bitmap.eraseColor(Color.WHITE);
        Canvas canvas = new Canvas(bitmap);

        Paint textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(24);
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Align.LEFT);

        canvas.drawText("Hello, Canvas!", 35F, 35F, textPaint);

        ImageView image = (ImageView) this.findViewById(R.id.imageView);
        image.setImageBitmap(bitmap);
    }
}
Draw text on Canvas

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw texture with thread

View (463/474)
« Previous

Draw texture with thread

Description

The following code shows how to Draw texture with thread.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main layout xml file

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/button_transform"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Rotate" />
    <TextureView
        android:id="@+id/surface"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center" />

</FrameLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/* ww w  .  ja  v a2  s .  c  o m*/
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;

public class MainActivity extends Activity implements View.OnClickListener, View.OnTouchListener, TextureView.SurfaceTextureListener {

    private TextureView mSurface;
    private DrawingThread mThread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button_transform).setOnClickListener(this);
        mSurface = (TextureView) findViewById(R.id.surface);
        mSurface.setOnTouchListener(this);
        mSurface.setSurfaceTextureListener(this);
    }

    @Override
    public void onClick(View v) {
        mSurface.animate()
                .rotationBy(180.0f)
                .setDuration(750);
    }

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mThread.addItem((int) event.getX(), (int) event.getY());
        }
        return true;
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
                                          int height) {
        mThread = new DrawingThread(new Surface(surface),
                BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
        mThread.updateSize(width, height);
        mThread.start();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width,
                                            int height) {
        mThread.updateSize(width, height);
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        mThread.quit();
        mThread = null;
        return true;
    }

    private static class DrawingThread extends HandlerThread implements Handler.Callback {
        private static final int MSG_ADD = 100;
        private static final int MSG_MOVE = 101;
        private static final int MSG_CLEAR = 102;

        private int mDrawingWidth, mDrawingHeight;

        private Surface mDrawingSurface;
        private Rect mSurfaceRect;
        private Paint mPaint;

        private Handler mReceiver;
        private Bitmap mIcon;
        private ArrayList<DrawingItem> mLocations;

        private class DrawingItem {
            int x, y;
            boolean horizontal, vertical;

            public DrawingItem(int x, int y, boolean horizontal, boolean vertical) {
                this.x = x;
                this.y = y;
                this.horizontal = horizontal;
                this.vertical = vertical;
            }
        }

        public DrawingThread(Surface surface, Bitmap icon) {
            super("DrawingThread");
            mDrawingSurface = surface;
            mSurfaceRect = new Rect();
            mLocations = new ArrayList<DrawingItem>();
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mIcon = icon;
        }

        @Override
        protected void onLooperPrepared() {
            mReceiver = new Handler(getLooper(), this);
            mReceiver.sendEmptyMessage(MSG_MOVE);
        }

        @Override
        public boolean quit() {
            mReceiver.removeCallbacksAndMessages(null);
            return super.quit();
        }

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ADD:
                    DrawingItem newItem = new DrawingItem(msg.arg1, msg.arg2,
                            Math.round(Math.random()) == 0,
                            Math.round(Math.random()) == 0);
                    mLocations.add(newItem);
                    break;
                case MSG_CLEAR:
                    mLocations.clear();
                    break;
                case MSG_MOVE:
                    try {
                        Canvas c = mDrawingSurface.lockCanvas(mSurfaceRect);
                        if (c == null) {
                            break;
                        }
                        c.drawColor(Color.BLACK);
                        for (DrawingItem item : mLocations) {
                            item.x += (item.horizontal ? 1 : -1);
                            c.drawBitmap(mIcon, item.x, item.y, mPaint);
                        }
                        mDrawingSurface.unlockCanvasAndPost(c);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
            mReceiver.sendEmptyMessage(MSG_MOVE);
            return true;
        }

        public void updateSize(int width, int height) {
            mDrawingWidth = width;
            mDrawingHeight = height;
            mSurfaceRect.set(0, 0, mDrawingWidth, mDrawingHeight);
        }

        public void addItem(int x, int y) {
            Message msg = Message.obtain(mReceiver, MSG_ADD, x, y);
            mReceiver.sendMessage(msg);
        }
        public void clearItems() {
            mReceiver.sendEmptyMessage(MSG_CLEAR);
        }
    }
}
Draw texture with thread

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Draw to SurfaceView with thread

View (464/474)
« Previous

Draw to SurfaceView with thread

Description

The following code shows how to Draw to SurfaceView with thread.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main layout xml file

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button_erase"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Erase" />
    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center" />

</FrameLayout>

Main Activity Java code

import java.util.ArrayList;
//from  w w  w. j  a v a 2  s. co  m
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

public class MainActivity extends Activity implements View.OnClickListener, View.OnTouchListener, SurfaceHolder.Callback {

    private SurfaceView mSurface;
    private DrawingThread mThread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Attach listener to button
        findViewById(R.id.button_erase).setOnClickListener(this);

        //Set up the surface with a touch listener and callback
        mSurface = (SurfaceView) findViewById(R.id.surface);
        mSurface.setOnTouchListener(this);
        mSurface.getHolder().addCallback(this);
    }

    @Override
    public void onClick(View v) {
        mThread.clearItems();
    }

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            mThread.addItem((int) event.getX(), (int) event.getY());
        }
        return true;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mThread = new DrawingThread(holder, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
        mThread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        mThread.updateSize(width, height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mThread.quit();
        mThread = null;
    }

    private static class DrawingThread extends HandlerThread implements Handler.Callback {
        private static final int MSG_ADD = 100;
        private static final int MSG_MOVE = 101;
        private static final int MSG_CLEAR = 102;

        private int mDrawingWidth, mDrawingHeight;

        private SurfaceHolder mDrawingSurface;
        private Paint mPaint;
        private Handler mReceiver;
        private Bitmap mIcon;
        private ArrayList<DrawingItem> mLocations;

        private class DrawingItem {
            //Current location marker
            int x, y;
            //Direction markers for motion
            boolean horizontal, vertical;

            public DrawingItem(int x, int y, boolean horizontal, boolean vertical) {
                this.x = x;
                this.y = y;
                this.horizontal = horizontal;
                this.vertical = vertical;
            }
        }

        public DrawingThread(SurfaceHolder holder, Bitmap icon) {
            super("DrawingThread");
            mDrawingSurface = holder;
            mLocations = new ArrayList<DrawingItem>();
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mIcon = icon;
        }

        @Override
        protected void onLooperPrepared() {
            mReceiver = new Handler(getLooper(), this);
            //Start the rendering
            mReceiver.sendEmptyMessage(MSG_MOVE);
        }

        @Override
        public boolean quit() {
            // Clear all messages before dying
            mReceiver.removeCallbacksAndMessages(null);
            return super.quit();
        }

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_ADD:
                //Create a new item at the touch location, with a randomized start direction
                DrawingItem newItem = new DrawingItem(msg.arg1, msg.arg2,
                        Math.round(Math.random()) == 0,
                        Math.round(Math.random()) == 0);
                mLocations.add(newItem);
                break;
            case MSG_CLEAR:
                //Remove all objects
                mLocations.clear();
                break;
            case MSG_MOVE:
                //Render a frame
                Canvas c = mDrawingSurface.lockCanvas();
                if (c == null) {
                    break;
                }
                //Clear canvas first
                c.drawColor(Color.BLACK);
                //Draw each item
                for (DrawingItem item : mLocations) {
                    //Update location
                    item.x += (item.horizontal ? 5 : -5);
                    if (item.x >= (mDrawingWidth - mIcon.getWidth()) ) item.horizontal = false;
                    if (item.x <= 0) item.horizontal = true;
                    item.y += (item.vertical ? 5 : -5);
                    if (item.y >= (mDrawingHeight - mIcon.getHeight()) ) item.vertical = false;
                    if (item.y <= 0) item.vertical = true;

                    c.drawBitmap(mIcon, item.x, item.y, mPaint);
                }
                mDrawingSurface.unlockCanvasAndPost(c);
                break;
            }
            //Post the next frame
            mReceiver.sendEmptyMessage(MSG_MOVE);
            return true;
        }

        public void updateSize(int width, int height) {
            mDrawingWidth = width;
            mDrawingHeight = height;
        }

        public void addItem(int x, int y) {
            //Pass the location into the Handler using Message arguments
            Message msg = Message.obtain(mReceiver, MSG_ADD, x, y);
            mReceiver.sendMessage(msg);
        }

        public void clearItems() {
            mReceiver.sendEmptyMessage(MSG_CLEAR);
        }
    }
}
Draw to SurfaceView with thread

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Dynamically create an HTML string and load it into the WebView

WebView (469/474)
« Previous

Dynamically create an HTML string and load it into the WebView

Description

The following code shows how to dynamically create an HTML string and load it into the WebView.

Example

Main layout xml file

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

        <WebView android:id="@+id/webview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

      </LinearLayout>

In the MainActivity.java file, add the following statements:

        import android.app.Activity;
        import android.os.Bundle;
        import android.webkit.WebSettings;
        import android.webkit.WebView;
/*  w w  w  .jav  a2  s.co m*/
        public class MainActivity extends Activity {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

              WebView wv = (WebView) findViewById(R.id.webview1);
              final String mimeType = "text/html";
              final String encoding = "UTF-8";
              String html = "<H1>A simple HTML page</H1><body>" +
                  "<p>The quick brown fox jumps over the lazy dog</p>" +
                  "</body>";
              wv.loadDataWithBaseURL("", html, mimeType, encoding, "");

            }
        }
Dynamically create an HTML string and load it into the WebView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Edit Contacts

Contact (92/474)
« Previous

Edit Contacts

Description

The following code shows how to Edit Contacts.

Example

Register permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.contacts"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="5" />

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

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

Main Activity Java code

//from   www  .  j  a  v  a  2 s.c  o  m

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener, DialogInterface.OnClickListener {

    private static final String TEST_EMAIL = "tester@email.com";

    private Cursor mContacts, mEmail;
    private int selectedContactId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };

        mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                projection, ContactsContract.Contacts.IN_VISIBLE_GROUP+" = 1",
                null, ContactsContract.Contacts.DISPLAY_NAME);

        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, mContacts,
                new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                new int[] { android.R.id.text1 });
        setListAdapter(mAdapter);

        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        if (mContacts.moveToPosition(position)) {
            selectedContactId = mContacts.getInt(0); // _ID column

            String[] projection = new String[] { ContactsContract.Data._ID,
                    ContactsContract.CommonDataKinds.Email.DATA };
            mEmail = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    projection,
                    ContactsContract.Data.CONTACT_ID + " = " + selectedContactId, null, null);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Email Addresses");
            builder.setCursor(mEmail, this, ContactsContract.CommonDataKinds.Email.DATA);
            builder.setPositiveButton("Add", this);
            builder.setNegativeButton("Cancel", null);
            builder.create().show();
        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        Cursor raw = getContentResolver().query(
                ContactsContract.RawContacts.CONTENT_URI,
                new String[] { ContactsContract.Contacts._ID },
                ContactsContract.Data.CONTACT_ID + " = " + selectedContactId, null, null);
        if(!raw.moveToFirst()) {
            return;
        }

        int rawContactId = raw.getInt(0);
        ContentValues values = new ContentValues();
        switch(which) {
        case DialogInterface.BUTTON_POSITIVE:
            //User wants to add a new email
            values.put(ContactsContract.CommonDataKinds.Email.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Email.DATA, TEST_EMAIL);
            values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_OTHER);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            break;
        default:
            //User wants to edit selection
            values.put(ContactsContract.CommonDataKinds.Email.DATA, TEST_EMAIL);
            values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_OTHER);
            getContentResolver().update(ContactsContract.Data.CONTENT_URI, values,
                    ContactsContract.Data._ID+" = "+mEmail.getInt(0), null);
            break;
        }

        //Don't need the email cursor anymore
        mEmail.close();
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - EditText AutoCorrect

EditText (289/474)
« Previous

EditText AutoCorrect

Description

The EditText control is a subclass of TextView, and it allows us to do text editing.

One of properties of an EditText is the inputType. You can set the inputType property to textAutoCorrect have the control correct common misspellings.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*from   w w  w. java 2s . c o m*/
    <EditText
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textAutoCorrect" />

</LinearLayout>

Java code

package com.java2s.app;
/*from w  w  w .  j a va  2s. c  om*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - EditText Capitalize

EditText (292/474)
« Previous

EditText Capitalize

Description

You can set EditText to textCapWords to have the control capitalize words.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//  w w  w.j a v a2  s . com
    <EditText
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textCapWords" />

</LinearLayout>

Java code

package com.java2s.app;
// ww w . ja v  a2  s.c  o m
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - EditText password

EditText (290/474)
« Previous

EditText password

Description

We can use EditText to accept password.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/* w w w .  ja va  2 s .  c o  m*/
    <EditText
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />

</LinearLayout>

Java code

package com.java2s.app;
//from   ww w .j  a  v a 2  s  .  c om
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - EditText phone numbers

EditText (291/474)
« Previous

EditText phone numbers

Description

We can set EditText to accept only phone numbers.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
// w ww.  j av a 2  s .  c  om
    <EditText
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="phone" />

</LinearLayout>

Java code

package com.java2s.app;
/*  w  w  w  .  j  a v a 2s  . c  o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}
EditText phone numbers

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Enable filtering support on ListView

ListView (370/474)
« Previous

Enable filtering support on ListView

Description

You can Enable filtering support on ListView.

Example

/*w ww.j  a v a  2s .  c  o  m*/
package com.java2s.myapplication3.app;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity  {
    String[] presidents = {
            "XML",
            "HTML",
            "CSS",
            "Java",
            "Javascript"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListView lstView = getListView();

        lstView.setTextFilterEnabled(true);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, presidents));
    }

    public void onListItemClick(
            ListView parent, View v, int position, long id)
    {
        Toast.makeText (this,
                "You have selected " + presidents [position],
                Toast.LENGTH_SHORT).show();
    }

}
Enable filtering support on ListView

Note

To programmatically get a reference to the ListView object, you use the getListView() method, which fetches the ListActivity's list view.

Filtering allows user to type on the keypad and the ListView will automatically filter the items to match what was typed.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Execute Javascript in WebView

WebView (473/474)
« Previous

Execute Javascript in WebView

Description

The following code shows how to Execute Javascript in WebView.

Example

Main layout xml file

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

Main Activity Java code

package com.java2s.myapplication3.app;
//from w  w  w . ja va 2  s .  c om
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WebView webview = new WebView(this);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(mClient);
        webview.addJavascriptInterface(new MyJavaScriptInterface(), "BRIDGE");

        setContentView(webview);

        webview.loadUrl("file:///android_asset/form.html");
    }

    private static final String JS_SETELEMENT = "javascript:document.getElementById('%s').value='%s'";
    private static final String JS_GETELEMENT = "javascript:window.BRIDGE.storeElement('%s',document.getElementById('%s').value)";
    private static final String ELEMENTID = "emailAddress";

    private WebViewClient mClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            executeJavascript(view,String.format(JS_GETELEMENT, ELEMENTID, ELEMENTID) );
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE);
            executeJavascript(view,String.format(JS_SETELEMENT, ELEMENTID, prefs.getString(ELEMENTID, "")) );
        }
    };

    private void executeJavascript(WebView view, String script) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view.evaluateJavascript(script, null);
        } else {
            view.loadUrl(script);
        }
    }
    class MyJavaScriptInterface {
        @JavascriptInterface
        public void storeElement(String id, String element) {
            SharedPreferences.Editor edit = getPreferences(Activity.MODE_PRIVATE).edit();
            edit.putString(id, element);
            edit.commit();
            if(!TextUtils.isEmpty(element)) {
                Toast.makeText(MainActivity.this, element, Toast.LENGTH_SHORT).show();
            }
        }
    }

}

\assets\form.html

<!DOCTYPE HTML>
<html>
<form name="input" action="form.html" method="get">
Enter Email: <input type="text" id="emailAddress" />
<input type="submit" value="Submit" />
</form>
</html>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Extend DocumentsProvider to provide image

Content Provider (103/474)
« Previous

Extend DocumentsProvider to provide image

Description

The following code shows how to Extend DocumentsProvider to provide image.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Register provider in manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="com.java2s.myapplication3.app.MyProvider"
            android:authorities="com.androidrecipes.sharedocuments.images"
            android:grantUriPermissions="true"
            android:exported="true"
            android:permission="android.permission.MANAGE_DOCUMENTS">
            <!-- Unique filter the system will use to find published providers -->
            <intent-filter>
                <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
            </intent-filter>
        </provider>

    </application>

</manifest>

Java code

//from  w  w w . j  a v a 2 s . c  om

package com.java2s.myapplication3.app;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Point;
import android.net.Uri;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract.Document;
import android.provider.DocumentsContract.Root;
import android.provider.DocumentsProvider;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

public class MyProvider extends DocumentsProvider {
    private static final String TAG = "ImageProvider";

    /* Cached recent selection */
    private static String sLastFilename;
    private static String sLastTitle;

    /* Default projection for a root when none supplied */
    private static final String[] DEFAULT_ROOT_PROJECTION = {
            Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES,
            Root.COLUMN_FLAGS, Root.COLUMN_ICON, Root.COLUMN_TITLE,
            Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID,
            Root.COLUMN_AVAILABLE_BYTES
    };
    /* Default projection for documents when none supplied */
    private static final String[] DEFAULT_DOCUMENT_PROJECTION = {
            Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE,
            Document.COLUMN_DISPLAY_NAME, Document.COLUMN_LAST_MODIFIED,
            Document.COLUMN_FLAGS, Document.COLUMN_SIZE
    };

    private ArrayMap<String, String> mDocuments;

    @Override
    public boolean onCreate() {
        //Dummy data for our documents
        mDocuments = new ArrayMap<String, String>();
        mDocuments.put("logo1.png", "John Doe");
        mDocuments.put("logo2.png", "Jane Doe");
        mDocuments.put("logo3.png", "Jill Doe");

        //Dump asset images onto internal storage
        writeAssets(mDocuments.keySet());
        return true;
    }

    /*
     * Helper method to stream some dummy files out to the
     * internal storage directory
     */
    private void writeAssets(Set<String> filenames) {
        for(String name : filenames) {
            try {
                Log.d("ImageProvider", "Writing "+name+" to storage");
                InputStream in = getContext().getAssets().open(name);
                FileOutputStream out = getContext().openFileOutput(name, Context.MODE_PRIVATE);

                int size;
                byte[] buffer = new byte[1024];
                while ((size = in.read(buffer, 0, 1024)) >= 0) {
                    out.write(buffer, 0, size);
                }
                out.flush();
                out.close();
            } catch (IOException e) {
                Log.w(TAG, e);
            }
        }
    }

    /* Helper method to construct documentId from a file name */
    private String getDocumentId(String filename) {
        return "root:" + filename;
    }

    /*
     * Helper method to extract file name from a documentId.
     * Returns empty string for the "root" document.
     */
    private String getFilename(String documentId) {
        int split = documentId.indexOf(":");
        if (split < 0) {
            return "";
        }
        return documentId.substring(split+1);
    }

    /*
     * Called by the system to determine how many "providers" are
     * hosted here.  It is most common to only return one, via a
     * Cursor that has only one result row.
     */
    @Override
    public Cursor queryRoots(String[] projection) throws FileNotFoundException {
        if (projection == null) {
            projection = DEFAULT_ROOT_PROJECTION;
        }
        MatrixCursor result = new MatrixCursor(projection);
        //Add the single root for this provider
        MatrixCursor.RowBuilder builder = result.newRow();

        builder.add(Root.COLUMN_ROOT_ID, "root");
        builder.add(Root.COLUMN_TITLE, "Android Recipes");
        builder.add(Root.COLUMN_SUMMARY, "Android Recipes Documents Provider");
        builder.add(Root.COLUMN_ICON, R.drawable.ic_launcher);

        builder.add(Root.COLUMN_DOCUMENT_ID, "root:");

        builder.add(Root.COLUMN_FLAGS,
                //Results will only come from the local file system
                Root.FLAG_LOCAL_ONLY
                        //We support showing recently selected items
                        | Root.FLAG_SUPPORTS_RECENTS);
        builder.add(Root.COLUMN_MIME_TYPES, "image/*");
        builder.add(Root.COLUMN_AVAILABLE_BYTES, 0);

        return result;
    }

    /*
     * Called by the system to determine the child items for a given
     * parent.  Will be called for the root, and for each subdirectory
     * defined within.
     */
    @Override
    public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder)
            throws FileNotFoundException {
        if (projection == null) {
            projection = DEFAULT_DOCUMENT_PROJECTION;
        }
        MatrixCursor result = new MatrixCursor(projection);

        try {
            for(String key : mDocuments.keySet()) {
                addImageRow(result, mDocuments.get(key), key);
            }
        } catch (IOException e) {
            return null;
        }

        return result;
    }

    /*
     * Return the same information provided via queryChildDocuments(), but
     * just for the single documentId requested.
     */
    @Override
    public Cursor queryDocument(String documentId, String[] projection)
            throws FileNotFoundException {
        if (projection == null) {
            projection = DEFAULT_DOCUMENT_PROJECTION;
        }

        MatrixCursor result = new MatrixCursor(projection);

        try {
            String filename = getFilename(documentId);
            if (TextUtils.isEmpty(filename)) {
                //This is a query for root
                addRootRow(result);
            } else {
                addImageRow(result, mDocuments.get(filename), filename);
            }
        } catch (IOException e) {
            return null;
        }

        return result;
    }

    /*
     * Called to populate any recently used items from this
     * provider in the Recents picker UI.
     */
    @Override
    public Cursor queryRecentDocuments(String rootId, String[] projection)
            throws FileNotFoundException {
        if (projection == null) {
            projection = DEFAULT_DOCUMENT_PROJECTION;
        }

        MatrixCursor result = new MatrixCursor(projection);

        if (sLastFilename != null) {
            try {
                addImageRow(result, sLastTitle, sLastFilename);
            } catch (IOException e) {
                Log.w(TAG, e);
            }
        }
        Log.d(TAG, "Recents: "+result.getCount());
        //We'll return the last selected result to a recents query
        return result;
    }

    /*
     * Helper method to write the root into the supplied
     * Cursor
     */
    private void addRootRow(MatrixCursor cursor) {
        final MatrixCursor.RowBuilder row = cursor.newRow();

        row.add(Document.COLUMN_DOCUMENT_ID, "root:");
        row.add(Document.COLUMN_DISPLAY_NAME, "Root");
        row.add(Document.COLUMN_SIZE, 0);
        row.add(Document.COLUMN_MIME_TYPE, Document.MIME_TYPE_DIR);

        long installed;
        try {
            installed = getContext().getPackageManager()
                    .getPackageInfo(getContext().getPackageName(), 0)
                    .firstInstallTime;
        } catch (NameNotFoundException e) {
            installed = 0;
        }
        row.add(Document.COLUMN_LAST_MODIFIED, installed);
        row.add(Document.COLUMN_FLAGS, 0);
    }

    /*
     * Helper method to write a specific image file into
     * the supplied Cursor
     */
    private void addImageRow(MatrixCursor cursor, String title, String filename) throws IOException {
        final MatrixCursor.RowBuilder row = cursor.newRow();

        AssetFileDescriptor afd = getContext().getAssets().openFd(filename);

        row.add(Document.COLUMN_DOCUMENT_ID, getDocumentId(filename));
        row.add(Document.COLUMN_DISPLAY_NAME, title);
        row.add(Document.COLUMN_SIZE, afd.getLength());
        row.add(Document.COLUMN_MIME_TYPE, "image/*");

        long installed;
        try {
            installed = getContext().getPackageManager()
                    .getPackageInfo(getContext().getPackageName(), 0)
                    .firstInstallTime;
        } catch (NameNotFoundException e) {
            installed = 0;
        }
        row.add(Document.COLUMN_LAST_MODIFIED, installed);
        row.add(Document.COLUMN_FLAGS, Document.FLAG_SUPPORTS_THUMBNAIL);
    }

    /*
     * Return a reference to an image asset the framework will use
     * in the items list for any document with the FLAG_SUPPORTS_THUMBNAIL
     * flag enabled.  This method is safe to block while downloading content.
     */
    @Override
    public AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint, CancellationSignal signal)
            throws FileNotFoundException {
        //We will load the thumbnail from the version on storage
        String filename = getFilename(documentId);
        //Create a file reference to the image on internal storage
        final File file = new File(getContext().getFilesDir(), filename);
        //Return a file descriptor wrapping the file reference
        final ParcelFileDescriptor pfd =
                ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH);
    }

    /*
     * Return a file descriptor to the document referenced by the supplied
     * documentId.  The client will use this descriptor to read the contents
     * directly.  This method is safe to block while downloading content.
     */
    @Override
    public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal)
            throws FileNotFoundException {
        //We will load the document itself from assets
        try {
            String filename = getFilename(documentId);
            //Return the file descriptor directly from APK assets
            AssetFileDescriptor afd = getContext().getAssets().openFd(filename);

            //Save this as the last selected document
            sLastFilename = filename;
            sLastTitle = mDocuments.get(filename);

            return afd.getParcelFileDescriptor();
        } catch (IOException e) {
            Log.w(TAG, e);
            return null;
        }
    }

    /*
     * This method is invoked when openDocument() receives a file descriptor
     * from assets.  Documents opened from standard files will not invoke
     * this method.
     */
    @Override
    public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
        //Last segment of Uri is the documentId
        String filename = getFilename(uri.getLastPathSegment());

        AssetManager manager = getContext().getAssets();
        try {
            //Return the appropriate asset for the requested item
            AssetFileDescriptor afd = manager.openFd(filename);

            //Save this as the last selected document
            sLastFilename = filename;
            sLastTitle = mDocuments.get(filename);

            return afd;
        } catch (IOException e) {
            Log.w(TAG, e);
            return null;
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Extend TextView with custom font

TextView (430/474)
« Previous

Extend TextView with custom font

Description

The following code shows how to extend TextView with custom font.

Example

main.xml for layout

<?xml version="1.0" encoding="utf-8"?>
<!--/*  w  w  w  .  j  av a2 s .  c  o  m*/
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <com.manning.androidhacks.hack011.view.LedTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="88:88:88"
        android:textColor="#3300ff00"
        android:textSize="80sp" />

    <com.manning.androidhacks.hack011.view.LedTextView
        android:id="@+id/main_clock_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:shadowColor="#00ff00"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="10"
        android:textColor="#00ff00"
        android:textSize="80sp" />

</merge>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning//from w w  w.java  2s. c  o m
 * See the file license.txt for copying permission.
 ******************************************************************************/
package com.manning.androidhacks.hack011;

import java.util.Date;

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

public class MainActivity extends Activity {

  private static final String DATE_FORMAT = "%02d:%02d:%02d";
  private static final int REFRESH_DELAY = 500;

  private final Handler mHandler = new Handler();
  private final Runnable mTimeRefresher = new Runnable() {
    @Override
    public void run() {
      final Date d = new Date();
      mTextView.setText(String.format(DATE_FORMAT, d.getHours(),
          d.getMinutes(), d.getSeconds()));
      mHandler.postDelayed(this, REFRESH_DELAY);
    }
  };

  private TextView mTextView;

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

    mTextView = (TextView) findViewById(R.id.main_clock_time);
  }

  @Override
  protected void onResume() {
    super.onResume();
    mHandler.post(mTimeRefresher);
  }

  @Override
  protected void onStop() {
    super.onStop();
    mHandler.removeCallbacks(mTimeRefresher);
  }
}

Custom TextView

/*******************************************************************************
 * Copyright (c) 2012 Manning/*w w  w .ja v  a  2  s.c o  m*/
 * See the file license.txt for copying permission.
 ******************************************************************************/
package com.manning.androidhacks.hack011.view;

import java.io.File;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class LedTextView extends TextView {

  private static final String FONTS_FOLDER = "fonts";
  private static final String FONT_DIGITAL_7 = FONTS_FOLDER
      + File.separator + "digital-7.ttf";

  public LedTextView(Context context) {
    super(context);
    init(context);
  }

  public LedTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
  }

  public LedTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context);
  }

  private void init(Context context) {
    AssetManager assets = context.getAssets();
    final Typeface font = Typeface.createFromAsset(assets,
        FONT_DIGITAL_7);
    setTypeface(font);
  }

}

Download

hack11.zip

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Extend View to create custom view

View (458/474)
« Previous

Extend View to create custom view

Description

The following code shows how to Extend View to create custom view.

Example

//w  ww. j  av  a  2 s.c om
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

package com.java2s.myapplication3.app;

import android.content.Context;
import android.graphics.Canvas;
import android.view.View;

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

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class MainActivity extends Activity {

    private DrawView mDrawView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Display display = getWindowManager().getDefaultDisplay();
        mDrawView = new DrawView(this);
        mDrawView.height = display.getHeight();
        mDrawView.width = display.getWidth();

        setContentView(mDrawView);
    }
}

class Rectangle extends View {
    public static final int MAX_SIZE = 40;
    private static final int ALPHA = 255;
    private int mCoordX = 0;
    private int mCoordY = 0;
    private int mRealSize = 40;
    private int mSpeedX = 3;
    private int mSpeedY = 3;

    private boolean goRight = true;
    private boolean goDown = true;
    private DrawView mDrawView;

    private Paint mInnerPaint;
    private RectF mDrawRect;

    public Rectangle(Context context, DrawView drawView) {
        super(context);
        mDrawView = drawView;

        mInnerPaint = new Paint();

        mDrawRect = new RectF();

    /* Red is default */
        mInnerPaint.setARGB(ALPHA, 255, 0, 0);
        mInnerPaint.setAntiAlias(true);
    }

    public void setARGB(int a, int r, int g, int b) {
        mInnerPaint.setARGB(a, r, g, b);
    }

    public void setX(int newValue) {
        mCoordX = newValue;
    }

    public void setY(int newValue) {
        mCoordY = newValue;
    }

    public void move() {
        moveTo(mSpeedX, mSpeedY);
    }

    private void moveTo(int goX, int goY) {

        // check the borders, and set the direction if a border has reached
        if (mCoordX > (mDrawView.width - MAX_SIZE)) {
            goRight = false;
        }

        if (mCoordX < 0) {
            goRight = true;
        }

        if (mCoordY > (mDrawView.height - MAX_SIZE)) {
            goDown = false;
        }
        if (mCoordY < 0) {
            goDown = true;
        }

        // move the x and y
        if (goRight) {
            mCoordX += goX;
        } else {
            mCoordX -= goX;
        }
        if (goDown) {
            mCoordY += goY;
        } else {
            mCoordY -= goY;
        }

    }

    public int getSpeedX() {
        return mSpeedX;
    }

    public void setSpeedX(int speedX) {
        mSpeedX = speedX;
    }

    public int getmSpeedY() {
        return mSpeedY;
    }

    public void setSpeedY(int speedY) {
        mSpeedY = speedY;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mDrawRect.set(mCoordX, mCoordY, mCoordX + mRealSize, mCoordY
                + mRealSize);
        canvas.drawRoundRect(mDrawRect, 0, 0, mInnerPaint);

    }

    public void setSize(int newSize) {
        mRealSize = newSize;
    }

    public int getSize() {
        return mRealSize;
    }
}

class DrawView extends View {
    private Rectangle mRectangle;
    public int width;
    public int height;

    public DrawView(Context context) {
        super(context);

        mRectangle = new Rectangle(context, this);
        mRectangle.setARGB(255, 255, 0, 0);
        mRectangle.setSpeedX(3);
        mRectangle.setSpeedY(3);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        invalidate();

        mRectangle.move();
        mRectangle.onDraw(canvas);
    }

}
Extend View to create custom view

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Extends ArrayAdapter to create Iconic Adapter for ListView

ListView (373/474)
« Previous

Extends ArrayAdapter to create Iconic Adapter for ListView

Description

The following code shows how to extend ArrayAdapter to create Iconic Adapter for ListView.

Example

Layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

layout/row.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="horizontal"
>
  <ImageView
    android:id="@+id/icon"
    android:layout_width="22px"
    android:paddingLeft="2px"
    android:paddingRight="2px"
    android:paddingTop="2px"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher"
  />
  <TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="40sp"
  />
</LinearLayout>

Java code

/*from w  w w  .j  ava2s . c  o m*/
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue",
          "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new IconicAdapter(this));
    selection=(TextView)findViewById(R.id.selection);
  }

  public void onListItemClick(ListView parent, View v,
                              int position, long id) {
     selection.setText(items[position]);
  }

  class IconicAdapter extends ArrayAdapter {
    Activity context;

    IconicAdapter(Activity context) {
      super(context, R.layout.row, items);

      this.context=context;
    }

    public View getView(int position, View convertView,
                        ViewGroup parent) {
      LayoutInflater inflater=context.getLayoutInflater();
      View row=inflater.inflate(R.layout.row, null);
      TextView label=(TextView)row.findViewById(R.id.label);

      label.setText(items[position]);

      if (items[position].length()>4) {
        ImageView icon=(ImageView)row.findViewById(R.id.icon);

        icon.setImageResource(R.drawable.delete);
      }

      return(row);
    }
  }
}
Extends ArrayAdapter to create Iconic Adapter for ListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - extends IntentService to create your own service

Service (211/474)
« Previous

extends IntentService to create your own service

Description

The following code shows how to extends IntentService to create your own service.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.java2s.myapplication3.app.MyService" />
    </application>

</manifest>

res\layout\main.xml

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

MainActivity.java

package com.java2s.myapplication3.app;
//  w  ww .java  2s  .co m
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        logEvent("CREATE");
    }

    @Override
    public void onStart() {
        super.onStart();
        logEvent("START");
    }

    @Override
    public void onResume() {
        super.onResume();
        logEvent("RESUME");
    }

    @Override
    public void onPause() {
        super.onPause();
        logWarning("PAUSE");
    }

    @Override
    public void onStop() {
        super.onStop();
        logWarning("STOP");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        logWarning("DESTROY");
    }

    private void logEvent(String event) {
        Intent intent = new Intent(this, MyService.class);
        intent.setAction(MyService.ACTION_EVENT);
        intent.putExtra(MyService.EXTRA_NAME, event);

        startService(intent);
    }

    private void logWarning(String event) {
        Intent intent = new Intent(this, MyService.class);
        intent.setAction(MyService.ACTION_WARNING);
        intent.putExtra(MyService.EXTRA_NAME, event);

        startService(intent);
    }
}

OperationsManager.java

package com.java2s.myapplication3.app;
//  w w w.  j av  a2  s  . c  om
import android.app.IntentService;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class MyService extends IntentService {

    public static final String ACTION_EVENT = "ACTION_EVENT";
    public static final String ACTION_WARNING = "ACTION_WARNING";
    public static final String ACTION_ERROR = "ACTION_ERROR";
    public static final String EXTRA_NAME = "eventName";

    private static final String LOGTAG = "EventLogger";

    private IntentFilter matcher;

    public MyService() {
        super("OperationsManager");
        matcher = new IntentFilter();
        matcher.addAction(ACTION_EVENT);
        matcher.addAction(ACTION_WARNING);
        matcher.addAction(ACTION_ERROR);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //Check for a valid request
        if(!matcher.matchAction(intent.getAction())) {
            Toast.makeText(this, "OperationsManager: Invalid Request", Toast.LENGTH_SHORT).show();
            return;
        }

        if(TextUtils.equals(intent.getAction(), ACTION_EVENT)) {
            logEvent(intent.getStringExtra(EXTRA_NAME));
        }
        if(TextUtils.equals(intent.getAction(), ACTION_WARNING)) {
            logWarning(intent.getStringExtra(EXTRA_NAME));
        }
        if(TextUtils.equals(intent.getAction(), ACTION_ERROR)) {
            logError(intent.getStringExtra(EXTRA_NAME));
        }
    }

    private void logEvent(String name) {
        try {
            //Simulate a long network operation by sleeping
            Thread.sleep(5000);
            Log.i(LOGTAG, name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void logWarning(String name) {
        try {
            //Simulate a long network operation by sleeping
            Thread.sleep(5000);
            Log.w(LOGTAG, name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void logError(String name) {
        try {
            //Simulate a long network operation by sleeping
            Thread.sleep(5000);
            Log.e(LOGTAG, name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - extends WebViewClient

WebView (470/474)
« Previous

extends WebViewClient

Description

The following code shows how to extends WebViewClient.

Example

Add permission to manifest file

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

Layout xml

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

Java code

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.Date;
/*from  www . j  a va 2  s  .com*/
public class MainActivity extends Activity {
  WebView browser;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    browser=(WebView)findViewById(R.id.webkit);
    browser.setWebViewClient(new Callback());

    loadTime();
  }

  void loadTime() {
    String page="<html><body><a href=\"clock\">"
            +new Date().toString()
            +"</a></body></html>";
    browser.loadDataWithBaseURL("x-data://base", page,"text/html", "UTF-8",null);
  }

  private class Callback extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      loadTime();

      return(true);
    }
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Filtering

Content Provider (104/474)
« Previous

Filtering

Description

The third and fourth parameters of the managedQuery() method and fourth and fifth parameters for the CursorLoader class enable you to specify a SQL WHERE clause to filter the result of the query.

Example

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

<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:stackFromBottom="false"
    android:transcriptMode="normal" />

<TextView
    android:id="@+id/contactName"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/contactID"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//from   w w w .ja  v a2s. co m
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Uri allContacts = Uri.parse("content://contacts/people");

        Cursor c;
        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            c = managedQuery(allContacts, null,
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?%Lee'", null, null);
        } else {
            //Honeycomb and later
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    null,
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?%Lee'",
                    null,
                    null);
            c = cursorLoader.loadInBackground();
        }

        String[] columns = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID};

        int[] views = new int[]{R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter;

        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            adapter = new SimpleCursorAdapter(
                    this, R.layout.main, c, columns, views);
        } else {
            //Honeycomb and later
            adapter = new SimpleCursorAdapter(
                    this, R.layout.main, c, columns, views,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        }

        this.setListAdapter(adapter);
    }
}

Add the following statements to the AndroidManifest.xml file:

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

     <uses-sdk android:minSdkVersion="14" />
     <uses-permission android:name="android.permission.READ_CONTACTS"/>

     <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name" >
       <activity
           android:label="@string/app_name"
           android:name=".ProviderActivity" >
           <intent-filter >
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>

Note

You can also put the search string into the next argument of the method/constructor, like this:

Cursor c;//from ww  w . jav a 2 s .c  o  m
if (android.os.Build.VERSION.SDK_INT <11) {
    //before Honeycomb
    c = managedQuery(allContacts, projection,
            ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
            new String[] {"%Lee"}, null);
} else {
    //Honeycomb and later
    CursorLoader cursorLoader = new CursorLoader(
            this,
            allContacts,
            projection,
            ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
         new String[] {"%Lee"},
          null);
  c = cursorLoader.loadInBackground();
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Flip ViewFlipper with animation

View (456/474)
« Previous

Flip ViewFlipper with animation

Description

The following code shows how to Flip ViewFlipper with animation.

Example

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

res/anim/push_left_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
  <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>

res/anim/push_left_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="300"/>
  <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>

Java code

/***//from  w  w  w.  j a  v  a  2  s  . co  m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ViewFlipper;

public class MainActivity extends Activity {
  static String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
                          "consectetuer", "adipiscing", "elit",
                          "morbi", "vel", "ligula", "vitae",
                          "arcu", "aliquet", "mollis", "etiam",
                          "vel", "erat", "placerat", "ante",
                          "porttitor", "sodales", "pellentesque",
                          "augue", "purus"};
  ViewFlipper flipper;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    flipper=(ViewFlipper)findViewById(R.id.details);

    flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_in));
    flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_left_out));

    for (String item : items) {
      Button btn=new Button(this);

      btn.setText(item);

      flipper.addView(btn,
                      new ViewGroup.LayoutParams(
                              ViewGroup.LayoutParams.FILL_PARENT,
                              ViewGroup.LayoutParams.FILL_PARENT));
    }

    flipper.setFlipInterval(2000);
    flipper.startFlipping();
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Gather Contact addresses from address table

Contact (88/474)
« Previous

Gather Contact addresses from address table

Description

The following code shows how to Gather Contact addresses from address table.

Example

Main Activity Java code

import android.app.AlertDialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
/* w  w  w  .j  a  v a2s.c  o m*/
public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    Cursor mContacts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);

        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, mContacts,
                new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                new int[] { android.R.id.text1 });
        setListAdapter(mAdapter);
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        if (mContacts.moveToPosition(position)) {
            int selectedId = mContacts.getInt(0); // _ID column
            Cursor address = getContentResolver().query(
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                    new String[] { ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS },
                    ContactsContract.Data.CONTACT_ID + " = " + selectedId, null, null);
            StringBuilder sb = new StringBuilder();
            sb.append(address.getCount() + " Addresses\n");
            if (address.moveToFirst()) {
                do {
                    sb.append("Address:\n" + address.getString(0));
                } while (address.moveToNext());
                sb.append('\n');
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(mContacts.getString(1)); // Display name
            builder.setMessage(sb.toString());
            builder.setPositiveButton("OK", null);
            builder.create().show();

            address.close();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Gather Contact email data from email table

Contact (90/474)
« Previous

Gather Contact email data from email table

Description

The following code shows how to Gather Contact email data from email table.

Example

Main Activity Java code

package com.java2s.myapplication3.app;
/*from   ww  w . java 2s  .c  o m*/
import android.app.AlertDialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    Cursor mContacts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, mContacts,
                new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                new int[] { android.R.id.text1 });
        setListAdapter(mAdapter);
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        if (mContacts.moveToPosition(position)) {
            int selectedId = mContacts.getInt(0); // _ID column

            Cursor email = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    new String[] { ContactsContract.CommonDataKinds.Email.DATA },
                    ContactsContract.Data.CONTACT_ID + " = " + selectedId, null, null);

            StringBuilder sb = new StringBuilder();
            sb.append(email.getCount() + " Emails\n");
            if (email.moveToFirst()) {
                do {
                    sb.append("Email: " + email.getString(0));
                    sb.append('\n');
                } while (email.moveToNext());
                sb.append('\n');
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(mContacts.getString(1)); // Display name
            builder.setMessage(sb.toString());
            builder.setPositiveButton("OK", null);
            builder.create().show();
            email.close();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Gather Contact phone data from phone table

Contact (91/474)
« Previous

Gather Contact phone data from phone table

Description

The following code shows how to Gather Contact phone data from phone table.

Example

Main Activity Java code

import android.app.AlertDialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
//from w ww .  j  av  a 2  s . c  o  m
public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener {

    Cursor mContacts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        mContacts = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                projection, null, null, ContactsContract.Contacts.DISPLAY_NAME);
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, mContacts,
                new String[] { ContactsContract.Contacts.DISPLAY_NAME },
                new int[] { android.R.id.text1 });
        setListAdapter(mAdapter);
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        if (mContacts.moveToPosition(position)) {
            int selectedId = mContacts.getInt(0); // _ID column
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER },
                    ContactsContract.Data.CONTACT_ID + " = " + selectedId, null, null);
            StringBuilder sb = new StringBuilder();
            sb.append(phone.getCount() + " Phone Numbers\n");
            if (phone.moveToFirst()) {
                do {
                    sb.append("Phone: " + phone.getString(0));
                    sb.append('\n');
                } while (phone.moveToNext());
                sb.append('\n');
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(mContacts.getString(1)); // Display name
            builder.setMessage(sb.toString());
            builder.setPositiveButton("OK", null);
            builder.create().show();

            phone.close();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get an array of all int type data matching the conditions

Database (117/474)
« Previous

Get an array of all int type data matching the conditions

Description

The following code shows how to get an array of all int type data matching the conditions.

Example

/*from   w ww . j  a va  2s .  co  m*/
import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();

  /** Get an array of all int type data matching the conditions **/
  public static int[] getAllInts(SQLiteDatabase db, String table, String column) {
    Cursor c = db.query(table, new String[] { column }, null, null, null, null, column);
    if (!c.moveToFirst()) {
      Log.d(TAG, "Tried to load a int[], but there are none in " + table + "-" + column);
      c.close();
      return null;
    }
    int[] toReturn = new int[c.getCount()];
    for (int i = 0; i < c.getCount(); i++) {
      toReturn[i] = c.getInt(c.getColumnIndex(column));
      c.moveToNext();
    }
    c.close();
    return toReturn;
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get an array of long type values matching the condition

Database (118/474)
« Previous

Get an array of long type values matching the condition

Description

The following code shows how to get an array of long type values matching the condition.

Example

import org.xmlpull.v1.XmlPullParser;
//  w  w w . j ava 2  s. c o m
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();

  /** Get an array of long type values matching the condition**/
  public static long[] getAllLongs(SQLiteDatabase db, String table, String column) {
    Cursor c = db.query(table, new String[] { column }, null, null, null, null, column);
    if (!c.moveToFirst()) {
      Log.d(TAG, "Tried to load a long[], but there are none in " + table + "-" + column);
      c.close();
      return null;
    }
    long[] toReturn = new long[c.getCount()];
    for (int i = 0; i < c.getCount(); i++) {
      toReturn[i] = c.getLong(c.getColumnIndex(column));
      c.moveToNext();
    }
    c.close();
    return toReturn;
  }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get and set SharedPreferences

Preference (195/474)
« Previous

Get and set SharedPreferences

Description

The following code shows how to Get and set SharedPreferences.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="I'm App1!"
    />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
// www  . j  a va 2  s .  c o m
public class MainActivity extends Activity {

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

      SharedPreferences prefs = getSharedPreferences("app1prefs", MODE_PRIVATE);
      String value = "Hello from App1 preference file!";
      prefs.edit().putString("shared_value", value).commit();
   }

   @Override
   public String toString() {
      return "Hello from App1 toString()!";
   }
}
Get and set SharedPreferences

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get Feedback after Sending a Message

SMS (215/474)
« Previous

Get Feedback after Sending a Message

Description

To Get Feedback after Sending a Message, you can create two PendingIntent objects to monitor the status of the SMS message-sending process.

The following code shows how to Get Feedback after Sending a Message.

Example

package com.java2s.myapplication3.app;
/*www  .  ja  v  a2 s .  com*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";
    PendingIntent sentPI, deliveredPI;
    BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;

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

        sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

        deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);
    }

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

        smsSentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };

        //create the BroadcastReceiver when the SMS is delivered
        smsDeliveredReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };

        //register the two BroadcastReceivers
        registerReceiver(smsDeliveredReceiver, new IntentFilter(DELIVERED));
        registerReceiver(smsSentReceiver, new IntentFilter(SENT));
    }

    @Override
    public void onPause() {
        super.onPause();
        //unregister the two BroadcastReceivers
        unregisterReceiver(smsSentReceiver);
        unregisterReceiver(smsDeliveredReceiver);
    }

    public void onClick(View v) {
        sendSMS("5556", "Hello my friends!");
    }

    //sends an SMS message to another device
    private void sendSMS(String phoneNumber, String message) {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get information from LocationProvider

Location (160/474)
« Previous

Get information from LocationProvider

Description

The following code shows how to Get information from LocationProvider.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Main layout xml file

<?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:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/detail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="30dp"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </ScrollView>
</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
//from w w w.  j a  v a2 s .  c  o  m
import android.app.Activity;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Printer;
import android.util.StringBuilderPrinter;
import android.widget.TextView;

import java.util.ArrayList;

// "network" provider will always return null for getLastKnownLocation
// if settings->location and security->Use wireless networks is NOT CHECKED

public class MainActivity extends Activity {

    private LocationManager locationMgr;

    private TextView title;
    private TextView detail;

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

        locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        title = (TextView) findViewById(R.id.title);
        detail = (TextView) findViewById(R.id.detail);
    }

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

        String providerName = getIntent().getStringExtra("PROVIDER_NAME");
        Location lastLocation = locationMgr.getLastKnownLocation(providerName);
        LocationProvider provider = locationMgr.getProvider(providerName);

        StringBuilder sb = new StringBuilder();

        sb.append("location manager data");
        if (lastLocation != null) {
            sb.append("\n");
            Printer printer = new StringBuilderPrinter(sb);
            lastLocation.dump(printer, "last location: ");
        } else {
            sb.append("\nlast location: null\n");
        }
        sb.append("\nprovider properties");
        sb.append("\naccuracy: " + provider.getAccuracy());
        sb.append("\npower requirement: " + provider.getPowerRequirement());
        sb.append("\nhas monetary cost: " + provider.hasMonetaryCost());
        sb.append("\nsupports altitude: " + provider.supportsAltitude());
        sb.append("\nsupports bearing: " + provider.supportsBearing());
        sb.append("\nsupports speed: " + provider.supportsSpeed());
        sb.append("\nrequires cell: " + provider.requiresCell());
        sb.append("\nrequires network: " + provider.requiresNetwork());

        if (providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
            GpsStatus gpsStatus = locationMgr.getGpsStatus(null);
            sb.append("\ngps status");
            sb.append("\ntime to first fix: " + gpsStatus.getTimeToFirstFix());
            sb.append("\nmax satellites: " + gpsStatus.getMaxSatellites());
            ArrayList<GpsSatellite> satellites = new ArrayList<GpsSatellite>();
            for (GpsSatellite satellite : gpsStatus.getSatellites()) {
                satellites.add(satellite);
            }
            sb.append("\ncurrent satellites: " + satellites.size());
            if (satellites.size() > 0) {
                for (GpsSatellite satellite : satellites) {
                    sb.append("\nsatellite: " + satellite.getPrn());
                    sb.append("\n   azimuth " + satellite.getAzimuth());
                    sb.append("\n   elevation " + satellite.getElevation());
                    sb.append("\n   signal to noise ratio " + satellite.getSnr());
                }
            }
        }
        title.setText("Provider: " + providerName);
        detail.setText(sb.toString());
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get location with GPS

Location (161/474)
« Previous

Get location with GPS

Description

The following code shows how to Get location with GPS.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Main layout xml file

<?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:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView
                android:id="@+id/detail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="30dp"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="2dp"
                android:layout_marginTop="30dp"
                android:text="GPS Events:"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/gps_events"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="1dp"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="2dp"
                android:layout_marginTop="10dp"
                android:text="GPS Satellite Status:"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/satellite_status"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="1dp"
                android:textAppearance="?android:attr/textAppearanceSmall" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*w  w w .java2 s  .  c  o m*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity {

    public static final String LOC_DATA = "LOC_DATA";

    private LocationManager locationMgr;
    private GpsListener gpsListener;
    private GpsStatus gpsStatus;
    private Handler handler;

    private TextView title;
    private TextView detail;
    private TextView gpsEvents;
    private TextView satelliteStatus;

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

        title = (TextView) findViewById(R.id.title);
        detail = (TextView) findViewById(R.id.detail);
        gpsEvents = (TextView) findViewById(R.id.gps_events);
        satelliteStatus = (TextView) findViewById(R.id.satellite_status);

        title.setText("Get current location via GPS");
        detail.setText("Attempting to get current location...\n     (may take a few seconds)");

        locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        gpsListener = new GpsListener();

        handler = new Handler() {
            public void handleMessage(Message m) {
                Log.d("log", "Handler returned with message: " + m.toString());
                if (m.what == LocationHelper.MESSAGE_CODE_LOCATION_FOUND) {
                    detail.setText("HANDLER RETURNED\nlat:" + m.arg1 + "\nlon:" + m.arg2);
                } else if (m.what == LocationHelper.MESSAGE_CODE_LOCATION_NULL) {
                    detail.setText("HANDLER RETURNED\nunable to get location");
                } else if (m.what == LocationHelper.MESSAGE_CODE_PROVIDER_NOT_PRESENT) {
                    detail.setText("HANDLER RETURNED\nprovider not present");
                }
            }
        };
    }

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

        // determine if GPS is enabled or not, if not prompt user to enable it
        if (!locationMgr.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("GPS is not enabled")
                    .setMessage("Would you like to go the location settings and enable GPS?").setCancelable(true)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                    finish();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            LocationHelper locationHelper = new LocationHelper(locationMgr, handler, "log");
            locationHelper.getCurrentLocation(30);
        }

        locationMgr.addGpsStatusListener(gpsListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationMgr.removeGpsStatusListener(gpsListener);
    }
    // you can also use a GpsListener to be notified when the GPS is started/stopped, and when first "fix" is obtained
    private class GpsListener implements GpsStatus.Listener {
        public void onGpsStatusChanged(int event) {
            Log.d("GpsListener", "Status changed to " + event);
            switch (event) {
                case GpsStatus.GPS_EVENT_STARTED:
                    gpsEvents.setText("GPS_EVENT_STARTED");
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    gpsEvents.setText("GPS_EVENT_STOPPED");
                    break;
                // GPS_EVENT_SATELLITE_STATUS will be called frequently
                // all satellites in use will invoke it, don't rely on it alone
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    // this is *very* chatty, only very advanced use cases should need this (avoid it if you don't need it)
                    gpsStatus = locationMgr.getGpsStatus(gpsStatus);
                    StringBuilder sb = new StringBuilder();
                    for (GpsSatellite sat : gpsStatus.getSatellites()) {
                        sb.append("Satellite N:" + sat.getPrn() + " AZ:" + sat.getAzimuth() + " EL:" + sat.getElevation()
                                + " S/N:" + sat.getSnr() + "\n");
                    }
                    satelliteStatus.setText(sb.toString());
                    break;
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    gpsEvents.setText("GPS_EVENT_FIRST_FIX");
                    break;
            }
        }
    }
}

/**
 * Helper class to encapsulate some of the common code needed to determine the
 * current location using FINE (GPS) provider.
 * <p/>
 * If the most recent location is available for the FINE provider, and it is relatively
 * recent (within FIX_RECENT_BUFFER_TIME -- currently 30 seconds), it is returned back to
 * the caller using a Message indicating the results.
 * <p/>
 * IF the most recent location is either not available, or too old to be used, the
 * a LocationListener is kicked off for a specified duration. Once the LocationListener
 * either gets a good Location update, or the time is elapsed, a Message is sent back
 * to the caller indicating the results.
 * <p/>
 * Example usage from an Activity:
 * <p/>
 * <pre>
 *
 *     Handler handler = new Handler() {
 *        public void handleMessage(Message m) {
 *           Log.d(LOG_TAG, "Handler returned with message: " + m.toString());
 *           if (m.what == LocationHelper.MESSAGE_CODE_LOCATION_FOUND) {
 *              Toast.makeText(Activity.this, "HANDLER RETURNED -- lat:" + m.arg1 + " lon:" + m.arg2, Toast.LENGTH_SHORT)
 *                       .show();
 *           } else if (m.what == LocationHelper.MESSAGE_CODE_LOCATION_NULL) {
 *              Toast.makeText(Activity.this, "HANDLER RETURNED -- unable to get location", Toast.LENGTH_SHORT).show();
 *           } else if (m.what == LocationHelper.MESSAGE_CODE_PROVIDER_NOT_PRESENT) {
 *              Toast.makeText(Activity.this, "HANDLER RETURNED -- provider not present", Toast.LENGTH_SHORT).show();
 *           }
 *        }
 *     };
 *
 *     LocationHelper helper = new LocationHelper(locationManager, handler, LOG_TAG);
 *     helper.getCurrentLocation(handler);
 * </pre>
 *
 * @author ccollins
 */
class LocationHelper {

    public static final int MESSAGE_CODE_LOCATION_FOUND = 1;
    public static final int MESSAGE_CODE_LOCATION_NULL = 2;
    public static final int MESSAGE_CODE_PROVIDER_NOT_PRESENT = 3;

    private static final int FIX_RECENT_BUFFER_TIME = 30000;

    private LocationManager locationMgr;
    private LocationListener locationListener;
    private Handler handler;
    private Runnable handlerCallback;
    private String providerName;
    private String logTag;

    /**
     * Construct with a LocationManager, and a Handler to pass back Messages via.
     *
     * @param locationMgr
     * @param handler
     */
    public LocationHelper(LocationManager locationMgr, Handler handler, String logTag) {
        this.locationMgr = locationMgr;
        this.locationListener = new LocationListenerImpl();
        this.handler = handler;
        this.handlerCallback = new Thread() {
            public void run() {
                endListenForLocation(null);
            }
        };

        Criteria criteria = new Criteria();
        // use Criteria to get provider (and could use COARSE, but doesn't work in emulator)
        // (FINE will use EITHER network/gps, whichever is the best enabled match, except in emulator must be gps)
        // (NOTE: network won't work unless enabled - Settings->Location & Security Settings->Use wireless networks)
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        this.providerName = locationMgr.getBestProvider(criteria, true);

        this.logTag = logTag;
    }

    /**
     * Invoke the process of getting the current Location.
     * Expect Messages to be returned via the Handler passed in at construction with results.
     *
     * @param durationSeconds amount of time to poll for location updates
     */
    public void getCurrentLocation(int durationSeconds) {

        if (this.providerName == null) {
            // return 2/0/0 if provider is not enabled
            Log.d(logTag, "Location provideName null, provider is not enabled or not present.");
            sendLocationToHandler(MESSAGE_CODE_PROVIDER_NOT_PRESENT, 0, 0);
            return;
        }

        // first check last KNOWN location (and if the fix is recent enough, use it)
        // NOTE -- this does NOT WORK in the Emulator
        // (if you send a DDMS "manual" time or geo fix, you get correct DATE,
        // but fix time starts at 00:00 and seems to increment by 1 second each time sent)
        // to test this section (getLastLocation being recent enough), you need to use a real device
        Location lastKnown = locationMgr.getLastKnownLocation(providerName);
        if (lastKnown != null && lastKnown.getTime() >= (System.currentTimeMillis() - FIX_RECENT_BUFFER_TIME)) {
            Log.d(logTag, "Last known location recent, using it: " + lastKnown.toString());
            // return lastKnown lat/long on Message via Handler
            sendLocationToHandler(MESSAGE_CODE_LOCATION_FOUND, (int) (lastKnown.getLatitude() * 1e6),
                    (int) (lastKnown.getLongitude() * 1e6));
        } else {
            // last known is relatively old, or doesn't exist, use a LocationListener
            // and wait for a location update for X seconds
            Log.d(logTag, "Last location NOT recent, setting up location listener to get newer update.");
            listenForLocation(providerName, durationSeconds);
        }
    }

    private void sendLocationToHandler(int msgId, int lat, int lon) {
        Message msg = Message.obtain(handler, msgId, lat, lon);
        handler.sendMessage(msg);
    }

    private void listenForLocation(String providerName, int durationSeconds) {
        locationMgr.requestLocationUpdates(providerName, 0, 0, locationListener);
        handler.postDelayed(handlerCallback, durationSeconds * 1000);
    }

    private void endListenForLocation(Location loc) {
        locationMgr.removeUpdates(locationListener);
        handler.removeCallbacks(handlerCallback);
        if (loc != null) {
            sendLocationToHandler(MESSAGE_CODE_LOCATION_FOUND, (int) (loc.getLatitude() * 1e6), (int) (loc.getLongitude() * 1e6));
        } else {
            sendLocationToHandler(MESSAGE_CODE_LOCATION_NULL, 0, 0);
        }
    }

    private class LocationListenerImpl implements LocationListener {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d(logTag, "Location status changed to:" + status);
            switch (status) {
                case LocationProvider.AVAILABLE:
                    break;
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    break;
                case LocationProvider.OUT_OF_SERVICE:
                    endListenForLocation(null);
            }
        }

        @Override
        public void onLocationChanged(Location loc) {
            if (loc == null) {
                return;
            }
            Log.d(logTag, "Location changed to:" + loc.toString());
            endListenForLocation(loc);
        }

        @Override
        public void onProviderDisabled(String provider) {
            endListenForLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }
    }
}
Get location with GPS

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get maximum value in database for given condition

Database (119/474)
« Previous

Get maximum value in database for given condition

Description

The following code shows to get maximum value in database for given condition.

Example

import org.xmlpull.v1.XmlPullParser;
//  w  w  w . j  a v a2  s.c  om
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();
  /** Get maximum value in database for given condition **/
  public static int getMax(SQLiteDatabase db, String table, String column, String whereClause, String[] whereArgs) {
    Cursor cursor = db.query(table, new String[] { column }, whereClause, whereArgs, null, null, column + " ASC");
    if (cursor.moveToFirst()) {
      int maxValue = cursor.getInt(cursor.getColumnIndex(column));
      return maxValue;
    } else {
      cursor.close();
      return -1;
    }
  }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get the id of the first row whose column matches conditions

Database (120/474)
« Previous

Get the id of the first row whose column matches conditions

Description

The following code shows how to get the id of the first row whose column matches conditions.

Example

import org.xmlpull.v1.XmlPullParser;
//from  w  w w .ja v  a2  s . c  o  m
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DbUtils {

  private SQLiteDatabase mDb;
  private Context mContext;

  private static final String TAG = DbUtils.class.getSimpleName();

  /** Get the id of the first row whose column matches conditions **/
  public static long getId(SQLiteDatabase db, String table, String column, String toMatch) {
    String[] selectionArgs = new String[] { toMatch };
    Cursor cursor = db.rawQuery("SELECT id FROM " + table + " where " + column + "=? LIMIT 1", selectionArgs);

    long id = -1;

    if (cursor.moveToFirst()) {
      id = cursor.getLong(cursor.getColumnIndex("id"));
    }
    cursor.close();
    return id;
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get to know AndroidManifest

Hello Android (5/474)
« Previous

Get to know AndroidManifest

Description

Each Android project has a manifest file.

Example

The following code has an example of AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.app" >

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

Note

The AndroidManifest.xml file contains detailed information about the application:

It defines the package name of the application as com.java2s.HelloWorld.

The version code of the application is 1 setting via the android:versionCode attribute. This value identifies the version number of your application. It can be used to programmatically determine whether an application needs to be upgraded.

The version name of the application is 1.0 set via the android:versionName attribute. This string value is mainly used for display to the user. You should use the format <major>.<minor>.<point> for this value.

The android:minSdkVersion attribute of the <uses-sdk> element specifies the minimum version of the OS on which the application will run.

The application uses the image named ic_launcher.png located in the drawable folders.

The name of this application is the string named app_name defined in the strings.xml file.

There is one activity in the application represented by the HelloWorldActivity.java file. The label displayed for this activity is the same as the application name.

Within the definition for this activity, there is an element named <intent-filter>:

  • The action for the intent filter is named android.intent.action.MAIN.
  • And it indicates that this activity serves as the entry point for the application.
  • The category for the intent-filter is named android.intent.category.LAUNCHER. And it indicates that the application can be launched from the device's launcher icon.

Every activity you have in your application must be declared in your AndroidManifest.xml file.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get to know ContentProviders

Content Provider (95/474)
« Previous

Get to know ContentProviders

Description

Android uses content providers for abstracting data into services.

Content providers play a significant role in sharing data between applications.

Content providers makes data sources look like REST-enabled data providers, such as web sites.

To retrieve data from a content provider or save data into a content provider, you will need to use a set of REST-like URIs.

Example

For example, if you were to retrieve a set of books from a content provider that is an encapsulation of a book database, you would need to use a URI like this:

content://com.android.book.BookProvider/books

To retrieve a specific book from the book database, you would need to use a URI like this:

content://com.android.book.BookProvider/books/101

Any application on the device can make use of these URIs to access and manipulate data.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Get to Know the Android Fundamental Components

Description

We need to understand views, activities, fragments, intents, content providers, services, and the AndroidManifest.xml file when you build applications for Android.

View

Views are user interface (UI) elements that form the basic building blocks of a user interface.

A view can be a button, a label, a text field, or many other UI elements.

Views are also used as containers for views, which means there's usually a hierarchy of views in the UI.

Activity

An activity is a UI concept that usually represents a single screen.

It generally contains one or more views.

Fragment

Fragments are like sub-activities, and an activity can display one or more fragments on the screen at the same time.

When a screen is small, an activity is more likely to contain just one fragment, and that fragment can be the same one used within larger screens.

Intent

An intent generically defines an "intention" to do some work.

Intents encapsulate several concepts. We can use intents to perform the following tasks:

  • Broadcast a message.
  • Start a service.
  • Launch an activity.
  • Display a web page or a list of contacts.
  • Dial a phone number or answer a phone call.

Intents are not always initiated by your application.

Intents are also used by the system to notify your application of specific events, such as the arrival of a text message.

Intents can be explicit or implicit. If you simply say that you want to display a URL, the system decides what component will fulfill the intention.

We can also provide specific information about what should handle the intention.

Intents loosely couple the action and action handler.

Content Provider

Android defines a standard way for applications to share data without exposing the underlying storage.

Through content providers, you can expose your data and have your applications use data from other applications.

Service

Services in Android resemble services you see in Windows or other platforms.

Services are background processes that can run for a long time.

Android defines two types of services:

  • local services and
  • remote services.

Local services are only accessible by the application that is hosting the service.

Remote services are services that are meant to be accessed remotely by other applications running on the device.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get web settings from WebView

WebView (471/474)
« Previous

Get web settings from WebView

Description

The WebView enables you to embed a web browser in your activity.

The following code shows how to get web settings from WebView.

Example

In the AndroidManifest.xml file, add the following permission:

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

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

            <application
                android:icon="@drawable/ic_launcher"
                android:label="@string/app_name" >
                <activity
                  android:label="@string/app_name"
                  android:name=".WebViewActivity" >
                  <intent-filter >
                      <action android:name="android.intent.action.MAIN" />

                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
          </application>

      </manifest>

Main layout xml file

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

        <WebView android:id="@+id/webview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

      </LinearLayout>

In the MainActivity.java file, add the following statements:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
/*w w  w. j  a  va 2  s. com*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        WebView wv = (WebView) findViewById(R.id.webview1);

        WebSettings webSettings = wv.getSettings();
        webSettings.setBuiltInZoomControls(true);
        wv.loadUrl("http://java2s.com/");
    }
}
Get web settings from WebView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Get your location

Location (162/474)
« Previous

Get your location

Description

The following code shows how to Get your location.

Example

Register permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Main Layout xml file

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

Main activity Java code

package com.java2s.myapplication3.app;
//from  www  .  jav  a  2 s  .c  om
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;

public class MainActivity extends Activity {

    private LocationManager mManager;
    private Location mCurrentLocation;

    private TextView mLocationView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocationView = new TextView(this);
        setContentView(mLocationView);
        mManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
    @Override
    public void onResume() {
        super.onResume();
        if(!mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Location Manager");
            builder.setMessage("We would like to use your location, "
                    + "but GPS is currently disabled.\n"
                    + "Would you like to change these settings now?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Launch settings, allowing user to make a change
                    Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(i);
                }
            });
            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //No location service, no Activity
                    finish();
                }
            });
            builder.create().show();
        }

        mCurrentLocation = mManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        updateDisplay();

        int minTime = 5000;
        float minDistance = 0;
        mManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, mListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        mManager.removeUpdates(mListener);
    }

    private void updateDisplay() {
        if(mCurrentLocation == null) {
            mLocationView.setText("Determining Your Location...");
        } else {
            mLocationView.setText(String.format("Your Location:\n%.2f, %.2f",
                    mCurrentLocation.getLatitude(),
                    mCurrentLocation.getLongitude()));
        }
    }

    private LocationListener mListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            mCurrentLocation = location;
            updateDisplay();
        }

        @Override
        public void onProviderDisabled(String provider) { }

        @Override
        public void onProviderEnabled(String provider) { }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) { }

    };
}
Get your location

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Handle AsyncTask interruption during configuration change

Activity (68/474)
« Previous

Handle AsyncTask interruption during configuration change

Description

The following code shows how to Handle AsyncTask interruption during configuration change.

Example

Main layout xml file

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

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
/*from   www.j a v a2s.  c  o  m*/
import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;
public class MainActivity extends Activity {

   private Worker worker;

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

      worker = (Worker) getLastNonConfigurationInstance();
      if (worker == null) {
         worker = new Worker();
         worker.execute();
      }
      worker.connectContext(this);
   }

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

   @Override
   public Object onRetainNonConfigurationInstance() {
      return worker;
   }
}
class Worker extends AsyncTask<Void, Void, String> {

   private Activity context;

   public void connectContext(Activity context) {
      this.context = context;
   }

   public void disconnectContext() {
      this.context = null;
   }

   @Override
   protected String doInBackground(Void... params) {
      try {
         Thread.sleep(3000);
      } catch (InterruptedException e) {
      }
      return "Work done!";
   }

   @Override
   protected void onPostExecute(String result) {
      if (context != null) {
         Toast.makeText(context, result, Toast.LENGTH_LONG).show();
      }
   }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Handle custom Gesture

Gesture (316/474)
« Previous

Handle custom Gesture

Description

The following code shows how to Handle custom Gesture.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

package com.java2s.myapplication3.app;
/*from w  ww. j a  va 2 s  . c  om*/
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.FrameLayout;
import android.widget.Scroller;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PanGestureScrollView scrollView = new PanGestureScrollView(this);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        for(int i=0; i < 5; i++) {
            ImageView iv = new ImageButton(this);
            iv.setImageResource(R.drawable.ic_launcher);
            layout.addView(iv, new LinearLayout.LayoutParams(1000, 500));
        }

        scrollView.addView(layout);
        setContentView(scrollView);
    }
}

class PanGestureScrollView extends FrameLayout {

    private GestureDetector mDetector;
    private Scroller mScroller;

    /* Positions of the last motion event */
    private float mInitialX, mInitialY;
    /* Drag threshold */
    private int mTouchSlop;

    public PanGestureScrollView(Context context) {
        super(context);
        init(context);
    }

    public PanGestureScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PanGestureScrollView(Context context, AttributeSet attrs,
                                int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mDetector = new GestureDetector(context, mListener);
        mScroller = new Scroller(context);
        // Get system constants for touch thresholds
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    /*
     * Override the measureChild... implementations to guarantee that the child
     * view gets measured to be as large as it wants to be. The default
     * implementation will force some children to be only as large as this view.
     */
    @Override
    protected void measureChild(View child, int parentWidthMeasureSpec,
                                int parentHeightMeasureSpec) {
        int childWidthMeasureSpec;
        int childHeightMeasureSpec;

        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    @Override
    protected void measureChildWithMargins(View child,
                                           int parentWidthMeasureSpec, int widthUsed,
                                           int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child
                .getLayoutParams();

        final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    // Listener to handle all the touch events
    private SimpleOnGestureListener mListener = new SimpleOnGestureListener() {
        public boolean onDown(MotionEvent e) {
            // Cancel any current fling
            if (!mScroller.isFinished()) {
                mScroller.abortAnimation();
            }
            return true;
        }

        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            // Call a helper method to start the scroller animation
            fling((int) -velocityX / 3, (int) -velocityY / 3);
            return true;
        }

        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            // Any view can be scrolled by simply calling its scrollBy() method
            scrollBy((int) distanceX, (int) distanceY);
            return true;
        }
    };

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            // This is called at drawing time by ViewGroup. We use
            // this method to keep the fling animation going through
            // to completion.
            int oldX = getScrollX();
            int oldY = getScrollY();
            int x = mScroller.getCurrX();
            int y = mScroller.getCurrY();

            if (getChildCount() > 0) {
                View child = getChildAt(0);
                x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(),
                        child.getWidth());
                y = clamp(y,
                        getHeight() - getPaddingBottom() - getPaddingTop(),
                        child.getHeight());
                if (x != oldX || y != oldY) {
                    scrollTo(x, y);
                }
            }

            // Keep on drawing until the animation has finished.
            postInvalidate();
        }
    }

    // Override scrollTo to do bounds checks on any scrolling request
    @Override
    public void scrollTo(int x, int y) {
        // we rely on the fact the View.scrollBy calls scrollTo.
        if (getChildCount() > 0) {
            View child = getChildAt(0);
            x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(),
                    child.getWidth());
            y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(),
                    child.getHeight());
            if (x != getScrollX() || y != getScrollY()) {
                super.scrollTo(x, y);
            }
        }
    }

    /*
     * Monitor touch events passed down to the children and intercept as soon as
     * it is determined we are dragging
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mInitialX = event.getX();
                mInitialY = event.getY();
                // Feed the down event to the detector so it has
                // context when/if dragging begins
                mDetector.onTouchEvent(event);
                break;
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                final float y = event.getY();
                final int yDiff = (int) Math.abs(y - mInitialY);
                final int xDiff = (int) Math.abs(x - mInitialX);
                // Verify that either difference is enough to be a drag
                if (yDiff > mTouchSlop || xDiff > mTouchSlop) {
                    // Start capturing events
                    return true;
                }
                break;
        }

        return super.onInterceptTouchEvent(event);
    }

    /*
     * Feed all touch events we receive to the detector for processing.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mDetector.onTouchEvent(event);
    }

    /*
     * Utility method to initialize the Scroller and start redrawing
     */
    public void fling(int velocityX, int velocityY) {
        if (getChildCount() > 0) {
            int height = getHeight() - getPaddingBottom() - getPaddingTop();
            int width = getWidth() - getPaddingLeft() - getPaddingRight();
            int bottom = getChildAt(0).getHeight();
            int right = getChildAt(0).getWidth();

            mScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY,
                    0, Math.max(0, right - width), 0,
                    Math.max(0, bottom - height));

            invalidate();
        }
    }

    /*
     * Utility method to assist in doing bounds checking
     */
    private int clamp(int n, int my, int child) {
        if (my >= child || n < 0) {
            /*
             * my >= child is this case: |--------------- me ---------------|
             * |------ child ------| or |--------------- me ---------------|
             * |------ child ------| or |--------------- me ---------------|
             * |------ child ------|
             *
             * n < 0 is this case: |------ me ------| |-------- child --------|
             * |-- mScrollX --|
             */
            return 0;
        }
        if ((my + n) > child) {
            /*
             * this case: |------ me ------| |------ child ------| |-- mScrollX
             * --|
             */
            return child - my;
        }
        return n;
    }
}
Handle custom Gesture

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Handle key down event from Activity

Activity (73/474)
« Previous

Handle key down event from Activity

Description

To demonstrate how activities interact with the user, the following example overrides some of the methods defined in the activity's base class.

Example

<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:layout_width="214dp"
        android:layout_height="wrap_content"
        android:text="Your Name" />
    <EditText
        android:id="@+id/txt1"
        android:layout_width="214dp"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btn1"
        android:layout_width="106dp"
        android:layout_height="wrap_content"
        android:text="OK" />
    <Button
        android:id="@+id/btn2"
        android:layout_width="106dp"
        android:layout_height="wrap_content"
        android:text="Cancel" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*w  ww.ja va2s  . co m*/

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                Toast.makeText (getBaseContext(),
                        "Center was clicked",
                        Toast.LENGTH_LONG).show();
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                Toast.makeText (getBaseContext(),
                        "Left arrow was clicked",
                        Toast.LENGTH_LONG).show();
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                Toast.makeText (getBaseContext(),
                        "Right arrow was clicked",
                        Toast.LENGTH_LONG).show();
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                Toast.makeText (getBaseContext(),
                        "Up arrow was clicked",
                        Toast.LENGTH_LONG).show();

                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                Toast.makeText (getBaseContext(),
                        "Down arrow was clicked",
                        Toast.LENGTH_LONG).show();
                break;
        }
        return false;
    }
}
Handle key down event from Activity

Note

When pressing any keys on your device, the view with focus will try to handle the event.

If you press the up or down directional arrow key, the EditText view does not handle this, and instead passes the event to the activity.

The onKeyDown() method returns a boolean result. Returning true tells the system that you are done with the event and the system should not proceed further with it.

For example,

@Override// www .  j  av  a  2 s  .  c o m
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    switch (keyCode)
    {
        case KeyEvent.KEYCODE_DPAD_CENTER:
            Toast.makeText(getBaseContext(),
                    "Center was clicked",
                    Toast.LENGTH_LONG).show();
            //break;
            return true;
        case KeyEvent.KEYCODE_DPAD_LEFT:
            Toast.makeText(getBaseContext(),
                    "Left arrow was clicked",
                    Toast.LENGTH_LONG).show();
            //break;
            return true;
        ...
    }
    return false;
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Handle Options Item Selected Event

Menu (394/474)
« Previous

Handle Options Item Selected Event

Description

The following code shows how to Handle Options Item Selected Event.

Example

Main layout xml file

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

  <ImageButton android:id="@+id/button_one"
          android:layout_width="wrap_content"
         android:layout_height="wrap_content"
          android:src="@drawable/button1"
          android:paddingTop="5px"
          android:background="#00000000">
  </ImageButton>

  <TextView  android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sample Text"
        android:textColor="#CCCC77"
        android:padding="12dip">
  </TextView>

  <ImageView  android:id="@+id/ImageView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image1">
  </ImageView>

</LinearLayout>

Menu xml file

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

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/buttonone"
          android:icon="@drawable/image1icon"
          android:title="@string/showimage1" />

    <item android:id="@+id/buttontwo"
          android:icon="@drawable/image2icon"
          android:title="@string/showimage2" />

    <item android:id="@+id/buttonthree"
          android:icon="@drawable/menu3icon"
          android:title="@string/showwhite" />

    <item android:id="@+id/buttonfour"
          android:icon="@drawable/menu4icon"
          android:title="@string/showblack" />

    <item android:id="@+id/buttonfive"
          android:icon="@drawable/menu5icon"
          android:title="@string/showalert" />

</menu>

Main Activity Java code

/*from  ww w  .ja va 2s .c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
      LinearLayout bkgr = (LinearLayout)findViewById(R.id.uilayout);
      final ImageView image = (ImageView)findViewById(R.id.ImageView01);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Pick an Image!")
               .setMessage("Please Select Image One or Image Two:")
               .setCancelable(false)

               .setPositiveButton("IMAGE 1", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        image.setImageResource(R.drawable.image1);
                   }
               })

               .setNegativeButton("IMAGE 2", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        image.setImageResource(R.drawable.image2);
                   }
               });

        switch (item.getItemId()) {
        case R.id.buttonone:
          image.setImageResource(R.drawable.image1);
            return true;
        case R.id.buttontwo:
          image.setImageResource(R.drawable.image2);
            return true;
        case R.id.buttonthree:
          bkgr.setBackgroundResource(R.color.background2);
            return true;
        case R.id.buttonfour:
          bkgr.setBackgroundResource(R.color.background);
            return true;
        case R.id.buttonfive:
            builder.show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Hide Activity Title

Activity (70/474)
« Previous

Hide Activity Title

Description

You can hide the title of an activity.

Example

Use the requestWindowFeature() method and pass it the Window.FEATURE_NO_TITLE.

package com.java2s.app;
/*from   w ww.  j  av  a 2  s  . com*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //---hides the title bar---
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);
        Log.d(tag, "In the onCreate() event");
    }
}
Hide Activity Title

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Horizontal LinearLayout

Layout (345/474)
« Previous

Horizontal LinearLayout

Description

If you change the orientation of the LinearLayout to horizontal, you need to change the width of each view to 0 dp.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Button"
    android:layout_gravity="left"
    android:layout_weight="1" />

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Button"
    android:layout_gravity="center_horizontal"
    android:layout_weight="2" />

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Button"
    android:layout_gravity="right"
    android:layout_weight="3" />
</LinearLayout>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - HTML encode and decode

Resources (26/474)
« Previous

HTML encode and decode

Description

The following code shows how to use the utilities calss for HTML encode and decode.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <Button android:id="@+id/format"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="OK"
      />
    <EditText android:id="@+id/name"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      />
  </LinearLayout>
  <TextView android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="funky_format">My name is &lt;b&gt;%1$s&lt;/b&gt;</string>
</resources>

Java code

/***//w w  w . j a va2s .c  o m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
  EditText name;
  TextView result;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    name=(EditText)findViewById(R.id.name);
    result=(TextView)findViewById(R.id.result);

    Button btn=(Button)findViewById(R.id.format);

    btn.setOnClickListener(new Button.OnClickListener() {
      public void onClick(View v) {
        applyFormat();
      }
    });
  }
  private void applyFormat() {
    String format=getString(R.string.funky_format);
    String simpleResult=String.format(format,TextUtils.htmlEncode(name.getText().toString()));
    result.setText(Html.fromHtml(simpleResult));
  }
}

Note

We use the TextUtils.htmlEncode method to do the html encoding.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - HTML strings

Resources (25/474)
« Previous

HTML strings

Description

Android allows child XML elements such as <b>, <i>, and other simple text-formatting HTML within the <string> node.

Example

You can use this compound HTML string to style the text before painting in a text view.

The following XML string resource file needs to be in the /res/values subdirectory.

<resources>
    <string name="simple_string">simple string</string>
     <string name="tagged_string">
         Hello <b><i>Android</i></b>, You are bold.
     </string>
</resources>

The following java code shows how to use the html-formatted string.

String simpleString = activity.getString(R.string.simple_string);
textView.setText(simpleString);//  w  w  w  .  j  a  va  2 s. c o m

String htmlTaggedString = activity.getString(R.string.tagged_string);

Spanned textSpan = android.text.Html.fromHtml(htmlTaggedString);

textView.setText(textSpan);

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Image Resources

Resources (33/474)
« Previous

Image Resources

Description

Android generates resource IDs for image files placed in the /res/drawable subdirectory.

The supported image types include .gif, .jpg, and .png. Each image file in this directory generates a unique ID from its base file name.

If the image file name is sample_image.jpg, then the resource ID generated is R.drawable.sample_image.

You will get an error for two file names with the same base file name. The subdirectories underneath /res/drawable are ignored.

Example

The following code shows how to use the image resource in XML layout definitions.

<Button
      android:id="@+id/button1"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Dial"
      android:background="@drawable/sample_image"
/>

The following code shows how to retrieve an image in Java and set it to a UI object like a button.

BitmapDrawable d = activity.getResources().getDrawable(R.drawable.sample_image);
button.setBackgroundDrawable(d);/*from  w w  w .  ja  v  a  2  s  .c om*/

//or you can set the background directly from the Resource Id
button.setBackgroundResource(R.drawable.sample_image);

Android also supports a special type of image called a stretchable image.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageButton with transparent background

Button (247/474)
« Previous

ImageButton with transparent background

Description

You can specify a transparent background for the image button.

The result will be a clickable image that acts like a button but can look like whatever you want it to look like.

Just set android:background="@null" for the image button.

Example

<?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">
/* w  ww  .  ja  v  a  2s .  co m*/
<ImageButton
    android:id="@+id/image3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null" />
</LinearLayout>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageSwitcher

GridView (321/474)
« Previous

ImageSwitcher

Description

To apply some animation to the image when it transitions from one image to another, you need to use the ImageSwitcher together with the Gallery view.

Example

Modify the activity_main.xml file by adding the following statements:

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Images of Android" />

    <Gallery
        android:id="@+id/gallery1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ImageSwitcher
        android:id="@+id/switcher1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />

</LinearLayout>

Save the following to res/values/attrs.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="Gallery1">
       <attr name="android:galleryItemBackground" />
   </declare-styleable>
</resources>

Add the following statements to the MainActivity.java file:

package com.java2s.myapplication3.app;
/*w  w  w .j  a  va  2s  .c  om*/
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class MainActivity extends Activity implements ViewFactory {
    Integer[] imageIDs = {
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher
    };

    private ImageSwitcher imageSwitcher;

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

        imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1);
        imageSwitcher.setFactory(this);
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));

        Gallery gallery = (Gallery) findViewById(R.id.gallery1);
        gallery.setAdapter(new ImageAdapter(this));
        gallery.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
                                    View v, int position, long id)
            {
                imageSwitcher.setImageResource(imageIDs[position]);
            }
        });
    }

    public View makeView()
    {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundColor(0xFF000000);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setLayoutParams(new
                ImageSwitcher.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));
        return imageView;
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private int itemBackground;

        public ImageAdapter(Context c)
        {
            context = c;
            //setting the style
        //    TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
        //    itemBackground = a.getResourceId(
         //           R.styleable.Gallery1_android_galleryItemBackground, 0);
       //     a.recycle();
        }

        //returns the number of images
        public int getCount()
        {
            return imageIDs.length;
        }

        //returns the item
        public Object getItem(int position)
        {
            return position;
        }

        //returns the ID of an item
        public long getItemId(int position)
        {
            return position;
        }

        //returns an ImageView view
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView = new ImageView(context);

            imageView.setImageResource(imageIDs[position]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
            imageView.setBackgroundResource(itemBackground);

            return imageView;
        }
    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageView and BitmapFactory

ImageView (328/474)
« Previous

ImageView and BitmapFactory

Description

We can use BitmapFactory to load image for ImageView.

Example

<?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">
/*w w w  .ja va 2  s. co m*/
    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

The following Java code uses BitmapFactory to load image.

package com.java2s.app;
/* w w  w  . j  a  v a 2s. c o  m*/
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imgView = (ImageView)findViewById(R.id.image3);

        imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher));

    }

}
ImageView and BitmapFactory

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageView and color

ImageView (329/474)
« Previous

ImageView and color

Description

You can even specify just a color, and the ImageView will display that color.

Example

<?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">
// www  .  j  a  va 2 s .c om
    <ImageView
        android:id="@+id/image2"
        android:layout_width="125dip"
        android:layout_height="25dip"
        android:src="#555555" />
</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//from www . j a v a  2  s .  com
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

    }

}
ImageView and color

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageView and drawable resource

ImageView (330/474)
« Previous

ImageView and drawable resource

Description

ImageView is used to display an image, where the image can come from a file, a content provider, or a resource such as a drawable.

Example

<?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">
/*  w w  w . j a  v  a2 s  .  c  om*/
    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
</LinearLayout>
ImageView and drawable resource

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageView size and scale

ImageView (326/474)
« Previous

ImageView size and scale

Description

The following XML not only specifies the source of the image file but also sets the maximum dimensions of the image on the screen and define what to do if the image is larger than our maximum size.

In this case, we tell the ImageView to center and scale the image so it fits inside the size we specified.

Example

//from   w  w  w.  j a  v a  2 s  .  c  o m
<?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">

    <ImageView
        android:id="@+id/image4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxHeight="50dip"
        android:maxWidth="35dip"
        android:scaleType="centerInside"
        android:src="@drawable/ic_launcher" />
</LinearLayout>
ImageView size and scale

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ImageView XML and Java Code

ImageView (324/474)
« Previous

ImageView XML and Java Code

Description

The following code shows some XML examples of ImageViews, followed by some code that shows how to create an ImageView.

Example

<?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">
/*from   w w  w  . j a  va 2 s  .  c  o m*/
    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

The following Java code sets the image from resource.

package com.java2s.app;
/*from   ww w  .j ava 2 s . c  o  m*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imgView = (ImageView) findViewById(R.id.image3);

        imgView.setImageResource(R.drawable.ic_launcher);
    }

}
ImageView XML and Java Code

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - implement TextWatcher interface from Activity class

Event (302/474)
« Previous

implement TextWatcher interface from Activity class

Description

The following code shows how to implement TextWatcher interface from Activity class.

Example

Main layout xml file

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

Main activity Java code

package com.java2s.myapplication3.app;
/*  w w w.ja  va  2 s  .c  om*/
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class MainActivity extends Activity implements TextWatcher {

    EditText text;
    int textCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Create an EditText widget and add the watcher
        text = new EditText(this);
        text.addTextChangedListener(this);

        setContentView(text);
    }

    /* TextWatcher Implementation Methods */
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    public void onTextChanged(CharSequence s, int start, int before, int end) {
        textCount = text.getText().length();
        setTitle(String.valueOf(textCount));
    }

    public void afterTextChanged(Editable s) { }

}
implement TextWatcher interface from Activity class

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Implement View.OnClickListener

Button (244/474)
« Previous

Implement View.OnClickListener

Description

The following code shows how to implement View.OnClickListener.

Example

//  w  ww . jav a2s .co  m
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/button"
        android:text="OK"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>

Java code

//from  w  w  w  .  j av  a  2  s  . com

package com.java2s.app;

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

import java.util.Date;

public class MainActivity extends Activity implements View.OnClickListener {
    Button btn;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(this);
        updateTime();
    }

    public void onClick(View view) {
        updateTime();
    }

    private void updateTime() {
        btn.setText(new Date().toString());
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - implements RadioGroup .OnCheckedChangeListener

RadioButton (412/474)
« Previous

implements RadioGroup .OnCheckedChangeListener

Description

The following code shows how to implements RadioGroup.OnCheckedChangeListener.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout/*from  w  ww .j a  v a2s  .  com*/
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <RadioGroup android:id="@+id/orientation"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5px">
        <RadioButton
            android:id="@+id/horizontal"
            android:text="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <RadioButton
            android:id="@+id/vertical"
            android:text="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </RadioGroup>
    <RadioGroup android:id="@+id/gravity"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5px">
        <RadioButton
            android:id="@+id/left"
            android:text="left"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <RadioButton
            android:id="@+id/center"
            android:text="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <RadioButton
            android:id="@+id/right"
            android:text="right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </RadioGroup>
</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//w  w  w  .  ja  v a  2 s.  c om
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.text.TextWatcher;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.EditText;

public class MainActivity extends Activity
        implements RadioGroup.OnCheckedChangeListener {
    RadioGroup orientation;
    RadioGroup gravity;

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

        orientation=(RadioGroup)findViewById(R.id.orientation);
        orientation.setOnCheckedChangeListener(this);
        gravity=(RadioGroup)findViewById(R.id.gravity);
        gravity.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (group==orientation) {
            if (checkedId==R.id.horizontal) {
                orientation.setOrientation(LinearLayout.HORIZONTAL);
            }
            else {
                orientation.setOrientation(LinearLayout.VERTICAL);
            }
        }
        else if (group==gravity) {
            if (checkedId==R.id.left) {
                gravity.setGravity(Gravity.LEFT);
            }
            else if (checkedId==R.id.center) {
                gravity.setGravity(Gravity.CENTER_HORIZONTAL);
            }
            else if (checkedId==R.id.right) {
                gravity.setGravity(Gravity.RIGHT);
            }
        }
    }
}
implements RadioGroup .OnCheckedChangeListener

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android Tutorial

Android

Android Basics

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS

Android UI

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
Home »
Android »

Android Basics
Android UI
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Intent Composition

Intent (127/474)
« Previous

Intent Composition

Description

An intent has fours parts:

  • name,
  • data
  • type
  • category

Note

In Android, intents usually come in pairs: action and data.

The action describes what is to be performed, such as editing an item, viewing the content of an item, and so on.

The data specifies what is affected, such as a person in the Contacts database.

The data is specified as an Uri object.

Some examples of action are as follows:

  • ACTION_VIEW
  • ACTION_DIAL
  • ACTION_PICK

Some examples of data include the following:

  • www.java2s.com
  • tel:+9991231234
  • geo:37.999900,-122.999970
  • content://contacts

The action and data pair describes the operation to be performed.
For example, to dial a phone number, you would use the pair ACTION_DIAL/tel:+999234567.

To display a list of contacts stored in your phone, you use the pair ACTION_VIEW/content://contacts.

To pick a contact from the list of contacts, you use the pair ACTION_PICK/content://contacts.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Intent to call a number

Intent (134/474)
« Previous

Intent to call a number

Description

An application to call a telephone number.

Example

package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
//from ww  w .j  av a 2s .c om
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel:+651234567"));
                startActivity(i);
            }
        });

        setContentView(parentContainer);
    }
}

The code above generates the following result.

Intent to call a number

Note

You dial a specific number by passing in the telephone number in the data portion:

Intent i = new Intent(android.content.Intent.ACTION_DIAL,Uri.parse ("tel:+651234567"));
startActivity(i);

The dialer will display the number to be called. The user must still press the dial button to dial the number.

If you want to directly call the number without user intervention, change the action as follows:

Intent i = new Intent(android.content.Intent.ACTION_CALL,Uri.parse ("tel:+651234567"));
startActivity(i);

If you want your application to directly call the specified number, you need to add the android.permission.CALL_PHONE permission to your application.

To display the dialer without specifying any number, simply omit the data portion, like this:

Intent i = new Intent(android.content.Intent.ACTION_DIAL);
startActivity(i);

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Intent to open browser

Intent (136/474)
« Previous

Intent to open browser

Description

We can use Intent to to open a browser window.

Example

package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
//w  ww . j av a2  s.  co m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("Press");

        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("http://www.java2s.com"));
                startActivity(i);
            }
        });

        setContentView(parentContainer);
    }
}
Intent to open browser

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Intent to open Dialer

Intent (135/474)
« Previous

Intent to open Dialer

Description

An application to present a phone dialer so the user can enter the numbers and make a call through the UI

Example

package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
//  w w  w.jav  a 2  s.c  o m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(android.content.Intent.ACTION_DIAL);
                startActivity(i);
            }
        });

        setContentView(parentContainer);
    }
}
Intent to open Dialer

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Intent to show a map

Intent (137/474)
« Previous

Intent to show a map

Description

An application to show a map.

Example

package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
//from   w  ww .j ava  2s  .c o m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new
                        Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("geo:37.827500,-122.481670"));
                startActivity(i);
            }
        });

        setContentView(parentContainer);
    }
}

Note

In order to display the Maps application, you need to run the application on an AVD that supports the Google APIs.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Intent Web Search with keyword

Intent (146/474)
« Previous

Intent Web Search with keyword

Description

The following code shows how to do Intent Web Search with keyword.

Example

Main Activity Java code

/*  w  w w .ja va  2s  .c o  m*/
import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.view.Menu;

public class MainActivity extends Activity {

    private Intent browserIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        browserIntent = new Intent();
        //browserIntent.setAction(Intent.ACTION_VIEW);
        //browserIntent.setData(Uri.parse("http://www.google.com"));
        browserIntent.setAction(Intent.ACTION_WEB_SEARCH);
        browserIntent.putExtra(SearchManager.QUERY, "puppies");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Browser").setIntent(browserIntent);
        return true;
    }

}
Intent Web Search with keyword

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Interactions between Fragments

Fragment (308/474)
« Previous

Interactions between Fragments

Description

We can make fragments to communicate with one another and exchange data.

Example

The following code shows how one fragment can access the views contained within another fragment.

In the res/layout folder, add a new file and name it fragment1.xml. Populate it with the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout//  w w  w  .  ja  v  a  2  s .com
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00" >
<TextView
    android:id="@+id/lblFragment1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="This is fragment #1"
    android:textColor="#000000"
    android:textSize="25sp" />
</LinearLayout>

Also in the res/layout folder, add another new file and name it fragment2.xml. Populate it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout//  www  .ja  v  a 2  s  .c  o  m
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFE00" >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="This is fragment #2"
    android:textColor="#000000"
    android:textSize="25sp" />

<Button
    android:id="@+id/btnGetText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get text in Fragment #1"
    android:textColor="#000000"
    android:onClick="onClick" />

</LinearLayout>

In activity_main.xml, add the following code:

<?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="horizontal" >
//  w  w  w  .  ja  v  a  2 s  .c om
      <fragment
          android:name="com.java2s.myapplication3.app.Fragment1"
          android:id="@+id/fragment1"
          android:layout_weight="1"
          android:layout_width="0px"
          android:layout_height="match_parent" />
      <fragment
          android:name="com.java2s.myapplication3.app.Fragment2"
          android:id="@+id/fragment2"
          android:layout_weight="1"
          android:layout_width="0px"
          android:layout_height="match_parent" />

</LinearLayout>

Modify the MainActivity.java file as follows:

public class MainActivity extends Activity {
   @Override//w  ww  . j  av a2  s .c  o m
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
   }
}

Under the com.java2s.Fragments package name, add two Java class files and name them Fragment1.java and Fragment2.java

Add the following code to Fragment1.java:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
//from   w  ww .  j av a  2 s .  c  o m
public class Fragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) {
        //Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);
    }
}

Add the following code to Fragment2.java:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/* w  w w.  j a v  a 2s . c  o m*/
public class Fragment2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(
            R.layout.fragment2, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        Button btnGetText = (Button)
            getActivity().findViewById(R.id.btnGetText);
        btnGetText.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TextView lbl = (TextView)
                    getActivity().findViewById(R.id.lblFragment1);
                Toast.makeText (getActivity(), lbl.getText(),
                    Toast.LENGTH_SHORT).show();
            }
        });
    }

}

Note

Debug the application on the Android emulator.

In the second fragment on the right, click the button. You should see the Toast class displaying the text "This is fragment #1".

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Introduction to Android Dababase

Description

Android uses the SQLite database system.

The database that you create for an application is only accessible to itself; other applications will not be able to access it.

For Android, the SQLite database that you create programmatically in an application is always stored in the /data/data/package_name/databases folder.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Java format string

Resources (24/474)
« Previous

Java format string

Description

The Android string resource definitions allow standard Java string-formatting sequences.

Example

The following code defines Java format string which we can use in the Java code.

This XML string resource file needs to be in the /res/values subdirectory.

<resources>
    <string name="simple_string">simple string</string>
    <string name="java_format_string">
           Hi %2$s Java format string. %1$s again
     </string>
</resources>

The following code shows how to use Java format string in Java code.

String simpleString = activity.getString(R.string.simple_string);
textView.setText(simpleString);//from   w  w w. jav a 2s.  com

String javaFormatString = activity.getString(R.string.java_format_string);

String substitutedString = String.format(javaFormatString, "Hello" , "Android");

textView.setText(substitutedString);

Note

java_format_string is defined in the resource xml file. We use the Activity.getString to load the string to Java code.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Key Android Resources List

Description

The following list has some of the key resources.

Color

Resource Type: Colors
Location: /res/values/any-file

String

Resource Type: Strings
Location: /res/values/any-file

String arrays

Resource Type: String arrays
Location: /res/values/any-file

Plurals

Resource Type: Plurals
Location: /res/values/any-file

Dimensions

Resource Type: Dimensions
Location: /res/values/any-file

Images

Resource Type: Images
Location: /res/drawable/multiple-files

Color drawables

Resource Type:Color drawables
Location: /res/values/any-file or /res/drawable/multiple-files

Arbitrary XML files

Resource Type: Arbitrary XML files
Location: /res/xml/*.xml

Arbitrary raw resources

Resource Type:Arbitrary raw resources
Location:/res/raw/*.*

Arbitrary raw assets

Resource Type:Arbitrary raw assets
Location:/assets/*.*/*.*

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Layout Resources

Resources (35/474)
« Previous

Layout Resources

Description

In Android, the view for a screen is often loaded from an XML file. These XML files are called layout resources.

Example

The following shows an example of a Layout File

<?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/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/b1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>

Note

Each file in the /res/layout/ subdirectory generates a unique constant based on the name of the file with extension excluded.

With layouts, what matters is the number of files. With string resources, what matters is the number of individual string resources inside the files.

For example, if you have two files under /res/layout/ called file1.xml and file2.xml, then in R.java you have the following entries.

public static final class layout {
    //.... any other files
    public static final int file1=0x7f030000;
    public static final int file2=0x7f030001;
    //..../*from   w w w.j av a2  s .co m*/
}

Reference

The views defined in these layout files, such as a TextView, are accessible in Java code through their resource IDs generated in R.java:

TextView tv = (TextView)this.findViewById(R.id.text1);
tv.setText("Try this text instead");

The constant R.id.text1 corresponds to the ID defined for the TextView. The ID for the TextView in the layout file is as follows:

<TextView android:id="@+id/text1"
..
</TextView>

The value for the id attribute indicates that a constant called text1 is used to uniquely identify this view.

The plus sign (+) in @+id/text1 means the ID text1 will be created if it doesn't exist already.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - layout_weight and layout_gravity

Layout (340/474)
« Previous

layout_weight and layout_gravity

Description

In LinearLayout, you can apply the layout_weight and layout_gravity attributes to views contained within it:

Example

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

    <Button
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="left"
        android:layout_weight="1" />

    <Button
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:text="Button"
              android:layout_gravity="center"
              android:layout_weight="2" />

    <Button
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="right"
        android:layout_weight="3" />

</LinearLayout>
layout_weight and layout_gravity

Note

The layout_gravity attribute indicates the positions the views should gravitate towards.

The layout_weight attribute specifies the distribution of available space.

In the preceding example, the three buttons occupy about

  • 16.6% (1/(1+2+3) * 100),
  • 33.3% (2/(1+2+3) * 100), and
  • 50% (3/(1+2+3) *100)

of the available height, respectively.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Life Cycle of a Fragment Example

Fragment (310/474)
« Previous

Life Cycle of a Fragment Example

Description

Fragments have their own life cycle.

Example

The following code examines the various states experienced by a fragment.

In the res/layout folder, add a new file and name it fragment1.xml. Populate it with the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout/*  ww w.  j  a v a2  s. co m*/
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="This is fragment #1"
    android:textColor="#000000"
    android:textSize="25sp" />
</LinearLayout>

Also in the res/layout folder, add another new file and name it fragment2.xml. Populate it as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout//from   w  ww . j a  v  a  2 s.c  o m
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFE00"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="This is fragment #2"
    android:textColor="#000000"
    android:textSize="25sp" />
</LinearLayout>

In activity_main.xml, add the following code:

<?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="horizontal" >
/* w  w w .  j  ava2s  .  c  o  m*/
    <fragment
        android:name="com.java2s.Fragments.Fragment1"
        android:id="@+id/fragment1"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />
    <fragment
        android:name="com.java2s.Fragments.Fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>

Under the com.java2s.Fragments package name, add two Java class files and name them Fragment1.java and Fragment2.java

Add the following code to Fragment1.java:

/*from   w w w  .  j av a2 s. c  om*/
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {

    Log.d("Fragment 1", "onCreateView");

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment1, container, false);
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.d("Fragment 1", "onAttach");
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("Fragment 1", "onCreate");
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.d("Fragment 1", "onActivityCreated");
  }

  @Override
  public void onStart() {
    super.onStart();
    Log.d("Fragment 1", "onStart");
  }

  @Override
  public void onResume() {
    super.onResume();
    Log.d("Fragment 1", "onResume");
  }

  @Override
  public void onPause() {
    super.onPause();
    Log.d("Fragment 1", "onPause");
  }

  @Override
  public void onStop() {
    super.onStop();
    Log.d("Fragment 1", "onStop");
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    Log.d("Fragment 1", "onDestroyView");
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d("Fragment 1", "onDestroy");
  }

  @Override
  public void onDetach() {
    super.onDetach();
    Log.d("Fragment 1", "onDetach");
  }

}

Add the following code to Fragment2.java:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
//from ww  w .j  a v a2  s. c om
public class Fragment2 extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment2, container, false);
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Life Cycle of a Fragment methods

Fragment (309/474)
« Previous

Life Cycle of a Fragment methods

Description

When a fragment is being created, it goes through the following states:

  • onAttach()
  • onCreate()
  • onCreateView()
  • onActivityCreated()

When the fragment becomes visible, it goes through these states:

  • onStart()
  • onResume()

When the fragment goes into the background mode, it goes through these states:

  • onPause()
  • onStop()

When the fragment is destroyed (when the hosting activity is destroyed), it goes through the following states:

  • onPause()
  • onStop()
  • onDestroyView()
  • onDestroy()
  • onDetach()

You can restore an instance of a fragment using a Bundle object, in the following states:

  • onCreate()
  • onCreateView()
  • onActivityCreated()

We can save a fragment's state in the onSaveInstanceState() method.

Difference

Most of the states experienced by a fragment are similar to those of activities. A few new states are specific to fragments:

  • onAttached() is called when the fragment has been associated with the activity
  • onCreateView() is called to create the view for the fragment
  • onActivityCreated() is called when the activity's onCreate() method has been returned
  • onDestroyView() is called when the fragment's view is being removed
  • onDetach() is called when the fragment is detached from the activity

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Link activity with UI

Activity (55/474)
« Previous

Link activity with UI

Description

An activity displays the user interface of your application, which may contain widgets such as buttons, labels, textboxes, and so on.

Typically, you define your UI using an XML file, for example the main.xml file located in the res/layout folder of your project.

<?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:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="hello" />

</LinearLayout>

During runtime, you load the XML UI in the onCreate() method handler in your Activity class, using the setContentView() method of the Activity class:

@Override//from ww  w  .java 2 s .  co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

During compilation, each element in the XML file is compiled into its equivalent Android GUI class, with attributes represented by methods.

The Android system then creates the UI of the activity when it is loaded.

The code above generates the following result.

Link activity with UI

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Listen to list item clicked event for ListView

ListView (376/474)
« Previous

Listen to list item clicked event for ListView

Description

The following code shows how to Listen to list item clicked event for ListView.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
//w  w  w. j av a 2  s  .c  o  m
public class MainActivity extends ListActivity {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_1,
                        items));
    selection=(TextView)findViewById(R.id.selection);
  }

  public void onListItemClick(ListView parent, View v, int position,
                                long id) {
     selection.setText(items[position]);
  }
}
Listen to list item clicked event for ListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Listen to selection event from Spinner

Spinner (417/474)
« Previous

Listen to selection event from Spinner

Description

The following code shows how to listen to selection event from Spinner.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <Spinner android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
  />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
//www. j  a  va2s. c  om
public class MainActivity extends Activity
  implements AdapterView.OnItemSelectedListener {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);

    Spinner spin=(Spinner)findViewById(R.id.spinner);
    spin.setOnItemSelectedListener(this);

    ArrayAdapter<String> aa=new ArrayAdapter<String>(this,
                              android.R.layout.simple_spinner_item,
                              items);
    aa.setDropDownViewResource(
      android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(aa);
  }

  public void onItemSelected(AdapterView<?> parent,View v, int position, long id) {
    selection.setText(items[position]);
  }

  public void onNothingSelected(AdapterView<?> parent) {
    selection.setText("");
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Listen to selection event from Spinner

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Listen to sensor change event

Sensor (199/474)
« Previous

Listen to sensor change event

Description

The following code shows how to Listen to sensor change event.

Example

Main layout activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TableLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="0,1,2">
    <TableRow
      android:layout_weight="1">
      <View
        android:id="@+id/top"
        android:layout_column="1"
      />
    </TableRow>
    <TableRow
      android:layout_weight="1">
      <View
        android:id="@+id/left"
        android:layout_column="0"
      />
      <View
        android:id="@+id/right"
        android:layout_column="2"
      />
    </TableRow>
    <TableRow
      android:layout_weight="1">
      <View
        android:id="@+id/bottom"
        android:layout_column="1"
      />
    </TableRow>
  </TableLayout>
  <TextView
    android:id="@+id/values"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
  />
</RelativeLayout>

Java code

package com.java2s.myapplication3.app;
//from   w w w. j a  v a2s  . c  om
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private TextView valueView;
    private View mTop, mBottom, mLeft, mRight;

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

        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        valueView = (TextView)findViewById(R.id.values);
        mTop = findViewById(R.id.top);
        mBottom = findViewById(R.id.bottom);
        mLeft = findViewById(R.id.left);
        mRight = findViewById(R.id.right);
    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) { }

    public void onSensorChanged(SensorEvent event) {
        final float[] values = event.values;
        float x = values[0]/10;
        float y = values[1]/10;
        int scaleFactor;

        if(x > 0) {
            scaleFactor = (int)Math.min(x*255, 255);
            mRight.setBackgroundColor(Color.TRANSPARENT);
            mLeft.setBackgroundColor(Color.argb(scaleFactor, 255, 0, 0));
        } else {
            scaleFactor = (int)Math.min(Math.abs(x)*255, 255);
            mRight.setBackgroundColor(Color.argb(scaleFactor, 255, 0, 0));
            mLeft.setBackgroundColor(Color.TRANSPARENT);
        }

        if(y > 0) {
            scaleFactor = (int)Math.min(y*255, 255);
            mTop.setBackgroundColor(Color.TRANSPARENT);
            mBottom.setBackgroundColor(Color.argb(scaleFactor, 255, 0, 0));
        } else {
            scaleFactor = (int)Math.min(Math.abs(y)*255, 255);
            mTop.setBackgroundColor(Color.argb(scaleFactor, 255, 0, 0));
            mBottom.setBackgroundColor(Color.TRANSPARENT);
        }
        //Display the raw values
        valueView.setText(String.format("X: %1$1.2f, Y: %2$1.2f, Z: %3$1.2f",
                values[0], values[1], values[2]));
    }
}
Listen to sensor change event

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Listen to text changed event for AutoCompleteTextView

TextView (434/474)
« Previous

Listen to text changed event for AutoCompleteTextView

Description

The following code show how to Listen to text changed event for AutoCompleteTextView

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <AutoCompleteTextView android:id="@+id/edit"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:completionThreshold="3"/>
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class MainActivity extends Activity
  implements TextWatcher {
  TextView selection;
  AutoCompleteTextView edit;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);
    edit=(AutoCompleteTextView)findViewById(R.id.edit);
    edit.addTextChangedListener(this);

    edit.setAdapter(new ArrayAdapter<String>(this,
                          android.R.layout.simple_dropdown_item_1line,
                          items));
  }

  public void onTextChanged(CharSequence s, int start, int before,
                              int count) {
    selection.setText(edit.getText());
  }

  public void beforeTextChanged(CharSequence s, int start,int count, int after) {

  }

  public void afterTextChanged(Editable s) {

  }
}
Listen to text changed event for AutoCompleteTextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ListView with custom Row

ListView (371/474)
« Previous

ListView with custom Row

Description

The following code shows how to ListView with custom Row.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

        <EditText android:id="@+id/main_edittext"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:hint="Write a number"
            android:inputType="number"
            android:singleLine="true"/>

        <Button android:id="@+id/main_add"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:text="Add"
            android:onClick="addNumber"/>
    </LinearLayout>

    <ListView android:id="@+id/main_listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

res/layout/number_row.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@+id/numbers_row_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"/>

    <Button android:id="@+id/numbers_row_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remove"/>

</LinearLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning//  w w w. j av a 2s  .  c o m
 * See the file license.txt for copying permission.
 ******************************************************************************/

import java.util.ArrayList;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements
    NumbersAdapterDelegate {
  private static final String TAG = MainActivity.class
      .getCanonicalName();

  private ListView mListView;
  private ArrayList<Integer> mNumbers;
  private NumbersAdapter mAdapter;
  private EditText mEditText;

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

    mEditText = (EditText) findViewById(R.id.main_edittext);
    mListView = (ListView) findViewById(R.id.main_listview);
    mNumbers = new ArrayList<Integer>();
    mAdapter = new NumbersAdapter(this, mNumbers);
    mListView.setAdapter(mAdapter);
  }

  @Override
  protected void onResume() {
    super.onResume();
    mAdapter.setDelegate(this);
  }

  @Override
  protected void onPause() {
    super.onPause();
    mAdapter.setDelegate(null);
  }

  @Override
  public void removeItem(Integer value) {
    mNumbers.remove(value);
    Toast
        .makeText(this, "Removed object: " + value, Toast.LENGTH_SHORT)
        .show();
    mAdapter.notifyDataSetChanged();
  }

  public void addNumber(View v) {
    String value = mEditText.getText().toString().trim();
    try {
      mNumbers.add(Integer.valueOf(value));
      mEditText.setText("");
      mAdapter.notifyDataSetChanged();
    } catch (NumberFormatException e) {
      Log.e(TAG, "Couldn't convert to integer the string: " + value);
    }
  }
}
interface NumbersAdapterDelegate {
    void removeItem(Integer value);
}
class NumbersAdapter extends ArrayAdapter<Integer> {
  private LayoutInflater mInflator;
  private NumbersAdapterDelegate mDelegate;

  public NumbersAdapter(Context context, List<Integer> objects) {
    super(context, 0, objects);
    mInflator = LayoutInflater.from(context);
  }

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

    if (null == cv) {
      cv = mInflator.inflate(R.layout.number_row, parent, false);
    }

    final Integer value = getItem(position);
    TextView tv = (TextView) cv.findViewById(R.id.numbers_row_text);
    tv.setText(value.toString());

    View button = cv.findViewById(R.id.numbers_row_button);
    button.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        if (null != mDelegate) {
          mDelegate.removeItem(value);
        }
      }
    });

    return cv;
  }

  public void setDelegate(NumbersAdapterDelegate delegate) {
    mDelegate = delegate;
  }

}
ListView with custom Row

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ListView with TextView as cell renderer

ListView (372/474)
« Previous

ListView with TextView as cell renderer

Description

The following code shows how to create a ListView with TextView as cell renderer.

Example

res/values/string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="footer">This is a demo of the ListView. Click and hold on to one of the items above to show the context menu.</string>
    <string name="app_name">ListViewDemo</string>
  <string-array name="countries">
    <item>Sweden</item>
    <item>Norway</item>
    <item>Finland</item>
    <item>Denmark</item>
    <item>Germany</item>
    <item>Poland</item>
    <item>Netherlands</item>
    <item>Belgium</item>
  </string-array>
  <string-array name="menu">
    <item>Edit</item>
    <item>Delete</item>
    <item>Send</item>
  </string-array>
</resources>

Main layout file

<?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"
    >
    <ListView
    android:id="@+id/list"
      android:layout_width="fill_parent"
      android:layout_height="0px"
      android:layout_weight="1"
      />
  <TextView
    android:id="@+id/footer"
      android:layout_width="fill_parent"
      android:layout_height="60dip"
      android:text="@string/footer"
      android:padding="4dip"
      android:background="#FF666666"
      />
</LinearLayout>

res/layout/listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textSize="24dip"
  android:padding="8dip"
  >
</TextView>

Java code

import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ListViewDemoActivity extends Activity {
  private String[] Countries;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Countries = getResources().getStringArray(R.array.countries);
        Arrays.sort(Countries);

    ListView list = (ListView)findViewById(R.id.list);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, Countries);
    list.setAdapter(adapter);
    registerForContextMenu(list);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
      if (v.getId()==R.id.list) {
          AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle(Countries[info.position]);
        String[] menuItems = getResources().getStringArray(R.array.menu);
        for (int i = 0; i<menuItems.length; i++) {
          menu.add(Menu.NONE, i, i, menuItems[i]);
      }
      }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
      int menuItemIndex = item.getItemId();
    String[] menuItems = getResources().getStringArray(R.array.menu);
    String menuItemName = menuItems[menuItemIndex];
      String listItemName = Countries[info.position];

      TextView text = (TextView)findViewById(R.id.footer);
      text.setText(String.format("Selected %s for item %s", menuItemName, listItemName));
      return true;
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load a URL with WebView

WebView (467/474)
« Previous

Load a URL with WebView

Description

The following code shows how to load a URL with WebView.

Example

Add Internet to uses-permission in manifest xml file.

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

Layout xml

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

Java code

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
// w  ww  .j a va  2 s  .  c  o  m
public class MainActivity extends Activity {
  WebView browser;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    browser=(WebView)findViewById(R.id.webkit);

    browser.loadUrl("http://java2s.com");
  }
}
Load a URL with WebView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load an HTML file located in the assets folder

Resources (44/474)
« Previous

Load an HTML file located in the assets folder

Description

The following code shows how to load an HTML file located in the assets folder.

Example

Main layout xml file

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

  <WebView android:id="@+id/webview1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

</LinearLayout>

In the MainActivity.java file, add the following statements:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
//from  w w w .  j av  a 2s  .  co m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        WebView wv = (WebView) findViewById(R.id.webview1);
        wv.loadUrl("file:///android_asset/Index.html");

    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load and parse raw xml file

Resources (41/474)
« Previous

Load and parse raw xml file

Description

The following code shows how to Load and parse raw xml file.

Example

Layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
  />
</LinearLayout>

res/raw/words.xml

<words>
  <word value="lorem" />
  <word value="ipsum" />
  <word value="dolor" />
  <word value="sit" />
  <word value="amet" />
  <word value="consectetuer" />
  <word value="adipiscing" />
  <word value="elit" />
  <word value="morbi" />
  <word value="vel" />
  <word value="ligula" />
  <word value="vitae" />
  <word value="arcu" />
  <word value="aliquet" />
  <word value="mollis" />
  <word value="etiam" />
  <word value="vel" />
  <word value="erat" />
  <word value="placerat" />
  <word value="ante" />
  <word value="porttitor" />
  <word value="sodales" />
  <word value="pellentesque" />
  <word value="augue" />
  <word value="purus" />
</words>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
//from   w ww .j  a  v a 2  s. c o  m
public class MainActivity extends ListActivity {
  TextView selection;
  ArrayList<String> items=new ArrayList<String>();

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);

    try {
      InputStream in=getResources().openRawResource(R.raw.words);
      DocumentBuilder builder=DocumentBuilderFactory
                                .newInstance()
                                .newDocumentBuilder();
      Document doc=builder.parse(in, null);
      NodeList words=doc.getElementsByTagName("word");

      for (int i=0;i<words.getLength();i++) {
        items.add(((Element)words.item(i)).getAttribute("value"));
      }

      in.close();
    }
    catch (Throwable t) {
      Toast
        .makeText(this, "Exception: "+t.toString(), 2000)
        .show();
    }

    setListAdapter(new ArrayAdapter<String>(this,
                                  android.R.layout.simple_list_item_1,
                                  items));
  }

  public void onListItemClick(ListView parent, View v, int position,
                  long id) {
    selection.setText(items.get(position).toString());
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load data from Database to ListView

Database (122/474)
« Previous

Load data from Database to ListView

Description

The following code shows how to Load data from Database to ListView.

Example

Main layout activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <EditText
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <Button
    android:id="@+id/add"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Add New Person"
  />
  <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
</LinearLayout>

Main activity Java code

package com.java2s.myapplication3.app;
//from  w w w  .j a  v  a 2  s  .c om
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MainActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    EditText mText;
    Button mAdd;
    ListView mList;

    MyDbHelper mHelper;
    SQLiteDatabase mDb;
    Cursor mCursor;
    SimpleCursorAdapter mAdapter;

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

        mText = (EditText)findViewById(R.id.name);
        mAdd = (Button)findViewById(R.id.add);
        mAdd.setOnClickListener(this);
        mList = (ListView)findViewById(R.id.list);
        mList.setOnItemClickListener(this);

        mHelper = new MyDbHelper(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mDb = mHelper.getWritableDatabase();
        String[] columns = new String[] {"_id", MyDbHelper.COL_NAME, MyDbHelper.COL_DATE};
        mCursor = mDb.query(MyDbHelper.TABLE_NAME, columns, null, null, null, null, null, null);

        String[] headers = new String[] {MyDbHelper.COL_NAME, MyDbHelper.COL_DATE};
        mAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item,
                mCursor, headers, new int[]{android.R.id.text1, android.R.id.text2});
        mList.setAdapter(mAdapter);
    }

    @Override
    public void onPause() {
        super.onPause();
        mDb.close();
        mCursor.close();
    }

    @Override
    public void onClick(View v) {
        ContentValues cv = new ContentValues(2);
        cv.put(MyDbHelper.COL_NAME, mText.getText().toString());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cv.put(MyDbHelper.COL_DATE, dateFormat.format(new Date())); //Insert 'now' as the date
        mDb.insert(MyDbHelper.TABLE_NAME, null, cv);

        mCursor.requery();
        mAdapter.notifyDataSetChanged();

        mText.setText(null);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

        mCursor.moveToPosition(position);

        String rowId = mCursor.getString(0); //Column 0 of the cursor is the id
        mDb.delete(MyDbHelper.TABLE_NAME, "_id = ?", new String[]{rowId});

        mCursor.requery();
        mAdapter.notifyDataSetChanged();
    }
}

class MyDbHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "mydb";
    private static final int DB_VERSION = 1;

    public static final String TABLE_NAME = "people";
    public static final String COL_NAME = "pName";
    public static final String COL_DATE = "pDate";
    private static final String STRING_CREATE =
            "CREATE TABLE "+TABLE_NAME+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                    +COL_NAME+" TEXT, "+COL_DATE+" DATE);";

    public MyDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(STRING_CREATE);

        ContentValues cv = new ContentValues(2);
        cv.put(COL_NAME, "Jack");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cv.put(COL_DATE, dateFormat.format(new Date())); //Insert 'now' as the date
        db.insert(TABLE_NAME, null, cv);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);
    }
}
Load data from Database to ListView

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load Image from sdcard

ImageView (331/474)
« Previous

Load Image from sdcard

Description

We can Load Image from sdcard and use them in ImageView.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/*  w  w w. j a v a  2  s.  com*/
    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The following Java code sets the image from resource.

package com.java2s.app;
/* ww  w. j  ava  2  s  . c o  m*/
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imgView = (ImageView)findViewById(R.id.image3);

        imgView.setImageDrawable(Drawable.createFromPath("/mnt/sdcard/myImage.jpg") );
    }

}

Example 2

The following setter method takes the URI of an image file and uses that as the image source.

package com.java2s.app;
/*w  w  w  . j a  v  a2 s  .  c om*/
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imgView = (ImageView) findViewById(R.id.image3);

        imgView.setImageURI(Uri.parse("file://mnt/sdcard/myImage.jpg"));
    }

}

This method is really only intended to be used for local images on the device, not for images that you might find through HTTP.

To use Internet-based images as the source for your ImageView, you'd most likely use BitmapFactory and an InputStream.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load items in the strings xml File to ListView

ListView (374/474)
« Previous

Load items in the strings xml File to ListView

Description

The following code shows how to Load items in the strings xml File to ListView.

Example

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, BasicViews5Activity!</string>
    <string name="app_name">BasicViews5</string>
    <string-array name="presidents_array">
        <item>Dwight D. Eisenhower</item>
        <item>John F. Kennedy</item>
        <item>Lyndon B. Johnson</item>
        <item>Richard Nixon</item>
        <item>Gerald Ford</item>
        <item>Jimmy Carter</item>
        <item>Ronald Reagan</item>
        <item>George H. W. Bush</item>
        <item>Bill Clinton</item>
        <item>George W. Bush</item>
          <item>Barack Obama</item>
   </string-array>
</resources>

Java code

// w  ww  .ja va 2  s  . com
package com.java2s.myapplication3.app;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity  {
    String[]  presidents;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        presidents = getResources().getStringArray(R.array.presidents_array);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_checked, presidents));
    }

    public void onListItemClick(
            ListView parent, View v, int position, long id)
    {
        Toast.makeText (this,
                "You have selected " + presidents [position],
                Toast.LENGTH_SHORT).show();
    }

}
Load items in the strings xml File to ListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load static html code in WebView

WebView (468/474)
« Previous

Load static html code in WebView

Description

The following code shows how to load static html code in WebView.

Example

Layout xml

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

Java code

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
/*from   w ww . ja v a 2s . co  m*/
public class MainActivity extends Activity {
  WebView browser;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    browser=(WebView)findViewById(R.id.webkit);

    browser.loadData("<html><body>Hello, world!</body></html>",
              "text/html", "UTF-8");
  }
}
Load static html code in WebView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Load the file from the external storage

Resources (45/474)
« Previous

Load the file from the external storage

Description

The following code shows how to Load the file from the external storage.

Example

Main layout file

<?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:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Please enter some text" />

 <EditText
     android:id="@+id/txtText1"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

 <Button
     android:id="@+id/btnSave"
     android:text="Save"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:onClick="onClickSave" />

 <Button
     android:id="@+id/btnLoad"
     android:text="Load"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:onClick="onClickLoad" />

</LinearLayout>

MainActivity.java file

package com.java2s.myapplication3.app;
//  ww  w . j  ava2  s  .  co  m
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends Activity {
    EditText textBox;
    static final int READ_BLOCK_SIZE = 100;

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

        textBox = (EditText) findViewById(R.id.txtText1);
    }

    public void onClickLoad(View view) {
        try {
            //SD Storage
            File sdCard = Environment.getExternalStorageDirectory();
            File directory = new File(sdCard.getAbsolutePath() +
                    "/MyFiles");
            File file = new File(directory, "textfile.txt");
            FileInputStream fIn = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fIn);
            char[] inputBuffer = new char[READ_BLOCK_SIZE];
            String s = "";

            int charRead;
            while ((charRead = isr.read(inputBuffer)) > 0) {
                String readString =
                        String.copyValueOf(inputBuffer, 0,
                                charRead);
                s += readString;

                inputBuffer = new char[READ_BLOCK_SIZE];
            }
            textBox.setText(s);
            Toast.makeText(getBaseContext(),
                    "File loaded successfully!",
                    Toast.LENGTH_SHORT).show();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    public void onClickSave(View view) {
        String str = textBox.getText().toString();
        try {
            //SD Card Storage
            File sdCard = Environment.getExternalStorageDirectory();
            File directory = new File(sdCard.getAbsolutePath() +
                    "/MyFiles");
            directory.mkdirs();
            File file = new File(directory, "textfile.txt");
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter osw = new
                    OutputStreamWriter(fOut);

            osw.write(str);
            osw.flush();
            osw.close();

            Toast.makeText(getBaseContext(),
                    "File saved successfully!",
                    Toast.LENGTH_SHORT).show();

            textBox.setText("");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

}

Note

In order to write to the external storage, you need to add the WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml file:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".FilesActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Choose the Best Storage Option

There are three main ways to save data in your Android applications:

  • SharedPreferences object,
  • internal storage, and
  • external storage.

Here are some guidelines:

  • To store name/value pairs, use the SharedPreferences object.
  • To store ad-hoc data, then using the internal storage.
  • To share your application data with other users, store your files on the SD card.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Log message

Hello Android (9/474)
« Previous

Log message

Description

The following code shows how to Log message.

Example

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
//  w  w  w . ja  v a 2 s  . c o  m
public class MainActivity extends Activity {

  private static final String LOG_TAG = "MainActivity";

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

    Log.d(LOG_TAG, "Log should be deleted");
  }
}

Note

The code above uses the Log.d method to log debug information.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Log Screen Orientation Changes

Activity (64/474)
« Previous

Log Screen Orientation Changes

Description

The following code finds out what happens to an activity's state when the device changes orientation.

Example

The following demonstrates the behavior of an activity when the device changes orientation.

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

<EditText
    android:id="@+id/txtField1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
//from  ww w  .  j  a v  a 2  s.  c o m
public class MainActivity extends Activity {
    @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     Log.d("StateInfo", "onCreate");
 }

 @Override
 public void onStart() {
     Log.d("StateInfo", "onStart");
     super.onStart();
 }

 @Override
 public void onResume() {
     Log.d("StateInfo", "onResume");
     super.onResume();
 }

 @Override
 public void onPause() {
     Log.d("StateInfo", "onPause");
     super.onPause();
 }

 @Override
 public void onStop() {
     Log.d("StateInfo", "onStop");
     super.onStop();
 }

 @Override
 public void onDestroy() {
     Log.d("StateInfo", "onDestroy");
     super.onDestroy();
 }

 @Override
 public void onRestart() {
     Log.d("StateInfo", "onRestart");
     super.onRestart();
 }
}
Log Screen Orientation Changes

Note

You need to ensure that you take the necessary steps to preserve the state of your activity before it changes orientation.

For any activity, you should save whatever state you need to save in the onPause() method, which is fired every time the activity changes orientation.

Important

Only views that are named via the android:id attribute in an activity will have their state persisted when the activity they are contained in is destroyed.

For example, the user may change orientation while entering some text into an EditText view. Any text inside the EditText view will be persisted and restored automatically. If you do not name the EditText view using the android:id attribute, the activity will not be able to persist the text currently contained within it.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Make application icon clickable on the Action Bar

Action Bar (232/474)
« Previous

Make application icon clickable on the Action Bar

Description

To make the application icon clickable, you need to call the setDisplayHomeAsUpEnabled() method:

@Override/*from  ww  w  .  j a v  a  2s  . c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

}

When the application icon is clicked, the onOptionsItemSelected() method is called.

To identify the application icon being called, you check the item ID against the android.R.id.home constant:

private boolean MenuChoice(MenuItem item)
{/*www  . ja  v a 2 s .  c  o  m*/
   switch (item.getItemId()) {
     case  android.R.id.home:
           Toast.makeText (this,"You clicked on the Application icon",Toast.LENGTH_LONG).show();
           return true;
     case 0:
           Toast.makeText (this, "You clicked on Item 1",Toast.LENGTH_LONG).show();
           return true;
     case 1:
            //...
   }
   return false;
}

We can use application icon to return to the main activity. To do this, we can create an Intent object and set it using the Intent.FLAG_ACTIVITY_CLEAR_TOP flag:

case  /*  w  ww . ja va2s  . c  om*/
  android.R.id.home :
    Toast.makeText (this,"You clicked on the Application icon",Toast.LENGTH_LONG).show();
    Intent i = new Intent(this, MyActionBarActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    return true;

The Intent.FLAG_ACTIVITY_CLEAR_TOP flag ensures that the series of activities in the back stack is cleared.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Make Canvas FullScreen

Canvas (259/474)
« Previous

Make Canvas FullScreen

Description

The following code shows how to Make Canvas FullScreen.

Example

Main Activity Java code

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
//from w w  w  .j  a va 2s. com
import java.util.Random;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

      setContentView(new CanvasView(this));
   }

   class CanvasView extends View {
      Random random = new Random();

      public CanvasView(Context context) {
         super(context);
      }

      @Override
      protected void onDraw(Canvas canvas) {
         canvas.drawRGB(random.nextInt(256), random.nextInt(256), random.nextInt(256));
      }
   }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Manipulate Image

ImageView (333/474)
« Previous

Manipulate Image

Description

The following code shows how to Manipulate Image.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*">
    <TableRow>
        <ImageView
            android:id="@+id/image_normal"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:scaleType="fitCenter" />
        <ImageView
            android:id="@+id/image_blurred"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:scaleType="fitCenter" />
    </TableRow>

    <TableRow>
        <ImageView
            android:id="@+id/image_greyscale"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:scaleType="fitCenter" />
        <ImageView
            android:id="@+id/image_sharpen"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:scaleType="fitCenter" />
    </TableRow>

    <TableRow>
        <ImageView
            android:id="@+id/image_edge"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:scaleType="fitCenter" />
        <ImageView
            android:id="@+id/image_emboss"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:scaleType="fitCenter" />
    </TableRow>

</TableLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
// w w  w.j  ava 2s . c o m
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.renderscript.ScriptIntrinsicColorMatrix;
import android.renderscript.ScriptIntrinsicConvolve3x3;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private enum ConvolutionFilter {
        SHARPEN, LIGHTEN, DARKEN, EDGE_DETECT, EMBOSS
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bitmap inBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        Bitmap outBitmap = inBitmap.copy(inBitmap.getConfig(), true);
        setImageInView(outBitmap.copy(outBitmap.getConfig(), false), R.id.image_normal);
        final RenderScript rs = RenderScript.create(this);
        final Allocation input = Allocation.createFromBitmap(rs, inBitmap,
                Allocation.MipmapControl.MIPMAP_NONE,
                Allocation.USAGE_SCRIPT);
        final Allocation output = Allocation.createTyped(rs, input.getType());

        final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setRadius(4f);
        script.setInput(input);
        script.forEach(output);
        output.copyTo(outBitmap);
        setImageInView(outBitmap.copy(outBitmap.getConfig(), false), R.id.image_blurred);

        final ScriptIntrinsicColorMatrix scriptColor = ScriptIntrinsicColorMatrix.create(rs, Element.U8_4(rs));
        scriptColor.setGreyscale();
        scriptColor.forEach(input, output);
        output.copyTo(outBitmap);
        setImageInView(outBitmap.copy(outBitmap.getConfig(), false), R.id.image_greyscale);

        ScriptIntrinsicConvolve3x3 scriptC = ScriptIntrinsicConvolve3x3.create(rs, Element.U8_4(rs));
        scriptC.setCoefficients(getCoefficients(ConvolutionFilter.SHARPEN));
        scriptC.setInput(input);
        scriptC.forEach(output);
        output.copyTo(outBitmap);
        setImageInView(outBitmap.copy(outBitmap.getConfig(), false), R.id.image_sharpen);

        scriptC = ScriptIntrinsicConvolve3x3.create(rs, Element.U8_4(rs));
        scriptC.setCoefficients(getCoefficients(ConvolutionFilter.EDGE_DETECT));
        scriptC.setInput(input);
        scriptC.forEach(output);
        output.copyTo(outBitmap);
        setImageInView(outBitmap.copy(outBitmap.getConfig(), false), R.id.image_edge);

        scriptC = ScriptIntrinsicConvolve3x3.create(rs, Element.U8_4(rs));
        scriptC.setCoefficients(getCoefficients(ConvolutionFilter.EMBOSS));
        scriptC.setInput(input);
        scriptC.forEach(output);
        output.copyTo(outBitmap);
        setImageInView(outBitmap.copy(outBitmap.getConfig(), false), R.id.image_emboss);

        rs.destroy();
    }

    private void setImageInView(Bitmap bm, int viewId) {
        ImageView normalImage = (ImageView) findViewById(viewId);
        normalImage.setImageBitmap(bm);
    }
    private float[] getCoefficients(ConvolutionFilter filter) {
        switch (filter) {
            case SHARPEN:
                return new float[] {
                        0f, -1f, 0f,
                        -1f, 5f, -1f,
                        0f, -1f, 0f
                };
            case LIGHTEN:
                return new float[] {
                        0f, 0f, 0f,
                        0f, 1.5f, 0f,
                        0f, 0f, 0f
                };
            case DARKEN:
                return new float[] {
                        0f, 0f, 0f,
                        0f, 0.5f, 0f,
                        0f, 0f, 0f
                };
            case EDGE_DETECT:
                return new float[] {
                        0f, 1f, 0f,
                        1f, -3f, 1f,
                        0f, 1f, 0f
                };
            case EMBOSS:
                return new float[] {
                        -2f, -1f, 0f,
                        -1f, 1f, 1f,
                        0f, 1f, 2f
                };
            default:
                return null;
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Multiple lines and single line

EditText (293/474)
« Previous

Multiple lines and single line

Description

You could force the user to a single line by setting the singleLine property to true.

So if you want the old default behavior of multiline typing, you need to specify inputType with textMultiLine.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
// w  w w  .ja  v a  2 s.  c om
    <EditText
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine" />

</LinearLayout>

Java code

package com.java2s.app;
//  w w  w .j  a v a 2 s.c om
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}
Multiple lines and single line

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Open Activities Using Intents

Intent (138/474)
« Previous

Open Activities Using Intents

Description

An Android application can contain zero or more activities.

In Android, you navigate between activities through what is known as an intent.

Example

Set up the manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.app" >
/*from   w  w w .  j  a  v  a2 s .  co m*/
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.app.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:label="Second Activity"
            android:name=".SecondActivity" >
            <intent-filter >
                <action android:name="com.java2s.SecondActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Second Activity

package com.java2s.app;
/*from w  w  w. j  a  v  a  2 s.  c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

public class SecondActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        parentContainer.addView(button);
        button.setText("Second");

        setContentView(parentContainer);

    }
}

Main activity to load the second activity:

package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
//w w w .ja  v a2 s. c o m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("Open");
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent("com.java2s.SecondActivity"));
            }
        });

        setContentView(parentContainer);
    }
}
Open Activities Using Intents

Note

The intent filter name for the new activity is com.java2s.SecondActivity.

Other activities that wish to call this activity will invoke it via this name.

The category for the intent filter is android.intent.category.DEFAULT. So that this activity can be started by another activity using the startActivity() method.

Activities in Android can be invoked by any application running on the device.

To invoke is defined within the same project, you can rewrite the preceding example like this:

startActivity(new Intent(this, SecondActivity.class));

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Options Menu

Menu (395/474)
« Previous

Options Menu

Description

The following code shows how to display the options menu when the user presses the MENU key on the Android device.

Example

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Please enter some text" />

    <EditText
        android:id="@+id/txtText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSave"
        android:text="Save"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickSave" />

    <Button
        android:id="@+id/btnLoad"
        android:text="Load"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickLoad" />

</LinearLayout>

Add the following statements in bold to the MenusActivity.java file:

package com.java2s.myapplication3.app;
/* ww  w  . j a v a 2 s  .  c om*/

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice(item);
    }
    private void CreateMenu(Menu menu)
    {
        MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
        {
            mnu1.setAlphabeticShortcut( 'a');
            mnu1.setIcon(R.drawable.ic_launcher);
        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
        {
            mnu2.setAlphabeticShortcut( 'b');
            mnu2.setIcon(R.drawable.ic_launcher);
        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
        {
            mnu3.setAlphabeticShortcut( 'c');
            mnu3.setIcon(R.drawable.ic_launcher);
        }
        MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
        {
            mnu4.setAlphabeticShortcut( 'd');
        }
        menu.add(0, 4, 4, "Item 5");
        menu.add(0, 5, 5, "Item 6");
        menu.add(0, 6, 6, "Item 7");
    }

    private boolean MenuChoice(MenuItem item)
    {
        switch (item.getItemId()) {
            case 0:
                Toast.makeText (this, "You clicked on Item 1",
                        Toast.LENGTH_LONG).show();
                return true;
            case 1:
                Toast.makeText (this, "You clicked on Item 2",
                        Toast.LENGTH_LONG).show();
                return true;
            case 2:
                Toast.makeText (this, "You clicked on Item 3",
                        Toast.LENGTH_LONG).show();
                return true;
            case 3:
                Toast.makeText (this, "You clicked on Item 4",
                        Toast.LENGTH_LONG).show();
                return true;
            case 4:
                Toast.makeText (this, "You clicked on Item 5",
                        Toast.LENGTH_LONG).show();
                return true;
            case 5:
                Toast.makeText (this, "You clicked on Item 6",
                        Toast.LENGTH_LONG).show();
                return true;
            case 6:
                Toast.makeText (this, "You clicked on Item 7",
                        Toast.LENGTH_LONG).show();
                return true;
        }
        return false;
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Parse JSON Data

Resources (48/474)
« Previous

Parse JSON Data

Description

The following code shows how to Parse JSON Data.

Example

\res\layout\main.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/line1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/line2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/line3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*w ww  .j  a  v a  2s .  c  o  m*/

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONException;

public class MainActivity extends Activity {
    private static final String JSON_STRING =
            "{'person':{'name':'XML','age':3,'children':["
                    + "{'name':'CSS','age':5},"
                    + "{'name':'HTML','age':7},"
                    + "{'name':'Javascript','age':9}"
                    + "] } }";

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

        TextView line1 = (TextView)findViewById(R.id.line1);
        TextView line2 = (TextView)findViewById(R.id.line2);
        TextView line3 = (TextView)findViewById(R.id.line3);
        try {
            JSONObject person = (new JSONObject(JSON_STRING)).getJSONObject("person");
            String name = person.getString("name");
            line1.setText("This person's name is " + name);
            line2.setText(name + " is " + person.getInt("age") + " years old.");
            line3.setText(name + " has " + person.getJSONArray("children").length()
                    + " children.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
Parse JSON Data

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Parse xml resource

Resources (39/474)
« Previous

Parse xml resource

Description

The following code shows how to Parse xml resource.

Example

Main activity xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
  />
</LinearLayout>

res/xml/words.cml

<words>
  <word value="lorem" />
  <word value="ipsum" />
  <word value="dolor" />
  <word value="sit" />
  <word value="amet" />
  <word value="consectetuer" />
  <word value="adipiscing" />
  <word value="elit" />
  <word value="morbi" />
  <word value="vel" />
  <word value="ligula" />
  <word value="vitae" />
  <word value="arcu" />
  <word value="aliquet" />
  <word value="mollis" />
  <word value="etiam" />
  <word value="vel" />
  <word value="erat" />
  <word value="placerat" />
  <word value="ante" />
  <word value="porttitor" />
  <word value="sodales" />
  <word value="pellentesque" />
  <word value="augue" />
  <word value="purus" />
</words>

Java code

/***/*w ww  .j av  a 2 s. com*/
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class MainActivity extends ListActivity {
  TextView selection;
  ArrayList<String> items=new ArrayList<String>();

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);

    try {
      XmlPullParser xpp=getResources().getXml(R.xml.words);

      while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
        if (xpp.getEventType()==XmlPullParser.START_TAG) {
          if (xpp.getName().equals("word")) {
            items.add(xpp.getAttributeValue(0));
          }
        }

        xpp.next();
      }
    }
    catch (Throwable t) {
      Toast
        .makeText(this, "Request failed: "+t.toString(), 4000)
        .show();
    }

    setListAdapter(new ArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1,
                            items));
  }

  public void onListItemClick(ListView parent, View v, int position,
                  long id) {
    selection.setText(items.get(position).toString());
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Partial wake

Service (210/474)
« Previous

Partial wake

Description

The following code shows how to use server to react power Partial wake event.

Example

Add permission for WAKE_LOCK

<?xml version="1.0" encoding="utf-8"?>
<manifest ...
    <application android:label="@string/app_name" >
        <activity ...
        </activity>
        <service android:enabled="true"
                 android:name=".TheService">
        </service>
    </application>
    <uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>

Layout xml

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

Main activity Java vode

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
/*ww  w  .  ja  va2  s  .co m*/
public class MainActivity extends Activity {
    public static final String TAG = ServiceLockTest.class.getName();

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

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

        startService(new Intent(this, TheService.class));
    }
}

Service Java code

import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager.WakeLock;
import android.os.PowerManager;
import android.os.Process;
import android.util.Log;
/*  ww w  . j a  v  a  2  s. c om*/
public class TheService extends Service implements SensorEventListener {
    public static final String TAG = TheService.class.getName();
    public static final int SCREEN_OFF_RECEIVER_DELAY = 500;

    private SensorManager mSensorManager = null;
    private WakeLock mWakeLock = null;

    /*
     * Register this as a sensor event listener.
     */
    private void registerListener() {
        mSensorManager.registerListener(this,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    /*
     * Un-register this as a sensor event listener.
     */
    private void unregisterListener() {
        mSensorManager.unregisterListener(this);
    }

    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive("+intent+")");

            if (!intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                return;
            }

            Runnable runnable = new Runnable() {
                public void run() {
                    Log.i(TAG, "Runnable executing.");
                    unregisterListener();
                    registerListener();
                }
            };

            new Handler().postDelayed(runnable, SCREEN_OFF_RECEIVER_DELAY);
        }
    };

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        Log.i(TAG, "onAccuracyChanged().");
    }

    public void onSensorChanged(SensorEvent event) {
        Log.i(TAG, "onSensorChanged().");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        PowerManager manager =
            (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(mReceiver);
        unregisterListener();
        mWakeLock.release();
        stopForeground(true);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        startForeground(Process.myPid(), new Notification());
        registerListener();
        mWakeLock.acquire();

        return START_STICKY;
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Pass data from Activity To Service

Service (206/474)
« Previous

Pass data from Activity To Service

Description

The following code shows how to Pass data from Activity To Service.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
/*from w w w .  j a  v a 2  s .  co m*/
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    int counter = 0;
    URL[] urls;
    static final int UPDATE_INTERVAL = 1000;
    private Timer timer = new Timer();
    private final IBinder binder = new MyBinder();

    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText (this, "Service Started", Toast.LENGTH_LONG).show();
        try {
            DownloadFile(new URL("http://java2s.com"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText (this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
//from w  w w .  j  av a 2s  .  c  o  m

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;

import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity {
    IntentFilter intentFilter;
    MyService serviceBinder;
    Intent i;
    private ServiceConnection connection = new ServiceConnection() {
        public void onServiceConnected(
                ComponentName className, IBinder service) {
            serviceBinder = ((MyService.MyBinder)service).getService();
            try {
                URL[] urls = new URL[] {
                        new URL("http://www.java2s.com/somefiles.pdf"),
                        new URL("http://www.java2s.net/somefiles.pdf")};
                serviceBinder.urls = urls;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            startService(i);
        }
        public void onServiceDisconnected(ComponentName className) {
            serviceBinder = null;
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onResume() {
        super.onResume();
        //intent to filter for file downloaded intent
        intentFilter = new IntentFilter();
        intentFilter.addAction("FILE_DOWNLOADED_ACTION");

        //register the receiver
        registerReceiver(intentReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        //unregister the receiver
        unregisterReceiver(intentReceiver);
    }

    public void startService(View view) {
        i = new Intent(MainActivity.this, MyService.class);
        bindService(i, connection, Context.BIND_AUTO_CREATE);
    }

    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText (getBaseContext(), "File downloaded!",
                    Toast.LENGTH_LONG).show();
        }
    };

}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Pass Data Using an Intent Object

Intent (128/474)
« Previous

Pass Data Using an Intent Object

Description

The following shows you the various ways in which you can pass data between activities.

Example

Set up the manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.app" >
// w  ww  . ja  v  a2 s . c  o  m
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.app.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:label="Second Activity"
            android:name=".SecondActivity" >
            <intent-filter >
                <action android:name="com.java2s.SecondActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Populate the SecondActivity.java file as follows:

package com.java2s.app;
//from   w w w . ja  v  a  2s  . co  m
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class SecondActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Toast.makeText(this, getIntent().getStringExtra("str1"), Toast.LENGTH_SHORT).show();

        Toast.makeText (this,Integer.toString(
                        getIntent().getIntExtra("age1", 0)),
                Toast.LENGTH_SHORT).show();

        Bundle bundle = getIntent().getExtras();

        Toast.makeText (this, bundle.getString("str2"),
                Toast.LENGTH_SHORT).show();

        Toast.makeText (this,Integer.toString(bundle.getInt("age2")),
                Toast.LENGTH_SHORT).show();
    }

    public void onClick(View view) {
        Intent i = new Intent();
        i.putExtra("age3", 45);

        i.setData(Uri.parse("Something passed back to main activity"));

        setResult(RESULT_OK, i);

        finish();
    }

}
Add the following statements to the MainActivity.java file:

 package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
// ww w.j  ava  2  s  . c om
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("Open");
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent("com.java2s.SecondActivity");
                i.putExtra("str1", "This is a string");
                i.putExtra("age1", 25);

                Bundle extras = new Bundle();
                extras.putString("str2", "This is another string");
                extras.putInt("age2", 35);

                i.putExtras(extras);

                startActivityForResult(i, 1);

            }
        });

        setContentView(parentContainer);
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Toast.makeText (this, Integer.toString(
                            data.getIntExtra("age3", 0)),
                    Toast.LENGTH_SHORT).show();
            Toast.makeText (this, data.getData().toString(),
                    Toast.LENGTH_SHORT).show();
        }
    }

}
Pass Data Using an Intent Object

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Perform Long-Running Tasks in a Service

Service (207/474)
« Previous

Perform Long-Running Tasks in a Service

Description

The following code shows how to Perform Long-Running Tasks in a Service. You will simulate the service of downloading a file from the Internet.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
// ww  w  .ja  va 2 s  . co m
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            int result = DownloadFile(new URL("http://www.your server.com/somefile.pdf"));
            Toast.makeText (getBaseContext(),
                    "Downloaded " + result + " bytes",
                    Toast.LENGTH_LONG).show();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText (this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/*from w  ww .  jav  a  2  s  . c o m*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
           startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

The activity is frozen for a few seconds before the Toast class displays the "Downloaded 100 bytes" message.

Note 2

The service runs on the same thread as your activity. In this case, because the service is suspended for five seconds, so is the activity.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Perform Repeated Tasks in a Service

Service (208/474)
« Previous

Perform Repeated Tasks in a Service

Description

Repeated Tasks are tasks we runs persistently in the background. For example, you may write an alarm clock service.

We can use the Timer class within your service to execute a block of code at a regular time interval.

The following code shows how to Perform Repeated Tasks in a Service.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
//from w ww  .  j a  v a  2  s  .co  m
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {
    int counter = 0;
    static final int UPDATE_INTERVAL = 1000;
    private Timer timer = new Timer();

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        doSomethingRepeatedly();
        return START_STICKY;
    }

    private void doSomethingRepeatedly() {
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                Log.d("MyService", String.valueOf(++counter));
            }
        }, 0, UPDATE_INTERVAL);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }

        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
//from   www.  j  ava  2s  . c  o m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
           startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Pick a picture

Intent (139/474)
« Previous

Pick a picture

Description

The following code shows how to pick a picture.

Example

<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="onTakePicture"
        android:text="take picture" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="onPickPicture"
        android:text="pick picture" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="onPickBoth"
        android:text="pick or take" />

</LinearLayout>

Java code

//from w  w  w .j a v  a  2  s  .  c  om
/*******************************************************************************
 * Copyright (c) 2012 Manning
 * See the file license.txt for copying permission.
 ******************************************************************************/

package com.java2s.myapplication3.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int PICK_PICTURE = 10;
    private static final int TAKE_PICTURE = 11;
    private static final int PICK_OR_TAKE_PICTURE = 12;

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

    public void onTakePicture(View v) {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Intent chooserIntent = Intent.createChooser(takePhotoIntent,
                "pick_picture");
        startActivityForResult(chooserIntent, TAKE_PICTURE);
    }

    public void onPickPicture(View v) {
        Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
        pickIntent.setType("image/*");
        Intent chooserIntent = Intent.createChooser(pickIntent,
                "take_picture");
        startActivityForResult(chooserIntent, PICK_PICTURE);
    }

    public void onPickBoth(View v) {
        Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
        pickIntent.setType("image/*");

        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        Intent chooserIntent = Intent.createChooser(pickIntent,
                "pick_both");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                new Intent[] { takePhotoIntent });

        startActivityForResult(chooserIntent, PICK_OR_TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (resultCode != RESULT_OK) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        Toast.makeText(this,
                "onActivityResult with req code: " + requestCode,
                Toast.LENGTH_SHORT).show();
    }
}
Pick a picture

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Pick an item from a data source

Contact (85/474)
« Previous

Pick an item from a data source

Description

The following code shows how to Pick an item from a data source.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <EditText android:id="@+id/type"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:cursorVisible="true"
    android:editable="true"
    android:singleLine="true"
    android:text="content://contacts/people"
  />
  <Button
    android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Gimme!"
    android:layout_weight="1"
  />
</LinearLayout>

Java code

/***// w  w  w .j av  a  2 s .  c  o m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
  static final int PICK_REQUEST=1337;
  private EditText type;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    type=(EditText)findViewById(R.id.type);

    Button btn=(Button)findViewById(R.id.pick);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                    Uri.parse(type.getText().toString()));

        startActivityForResult(i, PICK_REQUEST);
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
          startActivity(new Intent(Intent.ACTION_VIEW,
                                    data.getData()));
      }
    }
  }
}
Pick an item from a data source

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Play mp3 file from raw folder

Media (166/474)
« Previous

Play mp3 file from raw folder

Description

The following code shows how to Play mp3 file from raw folder.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/root"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Now Playing..."
  />
  <ImageView
    android:id="@+id/coverImage"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="centerInside"
  />
</LinearLayout>

Main activity Java code

package com.java2s.myapplication3.app;
//w w  w.  j a va  2  s  .c  o m
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener {

    Button mPlay;
    MediaPlayer mPlayer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mPlay = new Button(this);
        mPlay.setText("Play Sound");
        mPlay.setOnClickListener(playListener);

        setContentView(R.layout.activity_main);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mPlayer != null) {
            mPlayer.release();
        }
    }

    private View.OnClickListener playListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(mPlayer == null) {
                try {
                    mPlayer = MediaPlayer.create(MainActivity.this, R.raw.sound);
                    mPlayer.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                mPlayer.stop();
                mPlayer.release();
                mPlayer = null;
            }
        }
    };

    @Override
    public void onCompletion(MediaPlayer mp) {
        mPlayer.release();
        mPlayer = null;
    }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Play mp3 file loaded from a URL

Media (167/474)
« Previous

Play mp3 file loaded from a URL

Description

The following code shows how to Play mp3 file loaded from a URL.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/root"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Now Playing..."
  />
  <ImageView
    android:id="@+id/coverImage"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="centerInside"
  />
</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//from   ww w . java2  s  .c  om
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.MediaController;

public class MainActivity extends Activity implements MediaController.MediaPlayerControl, MediaPlayer.OnBufferingUpdateListener {

    MediaController mController;
    MediaPlayer mPlayer;
    ImageView coverImage;

    int bufferPercent = 0;

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

        coverImage = (ImageView)findViewById(R.id.coverImage);

        mController = new MediaController(this);
        mController.setAnchorView(findViewById(R.id.root));
    }

    @Override
    public void onResume() {
        super.onResume();
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(this, Uri.parse("http://www.your server host.com/your file.mp3"));
            mPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        coverImage.setImageResource(R.drawable.ic_launcher);

        mController.setMediaPlayer(this);
        mController.setEnabled(true);
    }

    @Override
    public void onPause() {
        super.onPause();
        mPlayer.release();
        mPlayer = null;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mController.show();
        return super.onTouchEvent(event);
    }

    //MediaPlayerControl Methods
    @Override
    public int getBufferPercentage() {
        return bufferPercent;
    }

    @Override
    public int getCurrentPosition() {
        return mPlayer.getCurrentPosition();
    }

    @Override
    public int getDuration() {
        return mPlayer.getDuration();
    }

    @Override
    public boolean isPlaying() {
        return mPlayer.isPlaying();
    }

    @Override
    public void pause() {
        mPlayer.pause();
    }

    @Override
    public void seekTo(int pos) {
        mPlayer.seekTo(pos);
    }

    @Override
    public void start() {
        mPlayer.start();
    }

    //BufferUpdateListener Methods
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        bufferPercent = percent;
    }

    //Android 2.0+ Target Callbacks
    public boolean canPause() {
        return true;
    }

    public boolean canSeekBackward() {
        return true;
    }

    public boolean canSeekForward() {
        return true;
    }

    @Override
    public int getAudioSessionId() {
        return 0;
    }
}
Play mp3 file loaded from a URL

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Play mp4 file in external storage

Media (168/474)
« Previous

Play mp4 file in external storage

Description

The following code shows how to Play mp4 file in external storage.

Example

package com.java2s.myapplication3.app;
//from  w  w  w  .ja  va  2 s .  com
import java.io.File;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

    VideoView videoView;
    MediaController controller;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Wire components to the view
        videoView = new VideoView(this);

        videoView.setVideoURI( Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"MysticHigh.mp4")) );
        controller = new MediaController(this);
        videoView.setMediaController(controller);
        videoView.start();

        setContentView(videoView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        videoView.stopPlayback();
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Play ogg file

Media (169/474)
« Previous

Play ogg file

Description

The following code shows how to Play ogg file.

Example

Main layout activity_main.xml file

<?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" >
    <Button
        android:id="@+id/button_beep1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play Beep 1" />
    <Button
        android:id="@+id/button_beep2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play Beep 2" />
        <Button
        android:id="@+id/button_beep3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Play Beep 3" />
</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*from ww w .j av a  2 s.  c  om*/
import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {

    private AudioManager mAudioManager;
    private SoundPool mSoundPool;
    private SparseIntArray mSoundMap;

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

        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        //Set up pool to only play one sound at a time over the
        // standard speaker output.
        mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

        findViewById(R.id.button_beep1).setOnClickListener(this);
        findViewById(R.id.button_beep2).setOnClickListener(this);
        findViewById(R.id.button_beep3).setOnClickListener(this);

        //Load each sound and save their streamId into a map
        mSoundMap = new SparseIntArray();
        AssetManager manager = getAssets();
        try {
            int streamId;
            streamId = mSoundPool.load(manager.openFd("Beep1.ogg"), 1);
            mSoundMap.put(R.id.button_beep1, streamId);

            streamId = mSoundPool.load(manager.openFd("Beep2.ogg"), 1);
            mSoundMap.put(R.id.button_beep2, streamId);

            streamId = mSoundPool.load(manager.openFd("Beep3.ogg"), 1);
            mSoundMap.put(R.id.button_beep3, streamId);
        } catch (IOException e) {
            Toast.makeText(this, "Error Loading Sound Effects", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSoundPool.release();
        mSoundPool = null;
    }

    @Override
    public void onClick(View v) {
        int streamId = mSoundMap.get(v.getId());
        if (streamId > 0) {
            float streamVolumeCurrent = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            float streamVolumeMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            float volume = streamVolumeCurrent / streamVolumeMax;

            mSoundPool.play(streamId, volume, volume, 1, 0, 1.0f);
        }
    }
}
Play ogg file

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Plurals Resource

Resources (23/474)
« Previous

Plurals Resource

Description

The resource plurals has a list of strings for expressing a numerical quantity in various ways.

For example:

  • There is 1 student.
  • There are 2 students.
  • There are 20 students.

Android allows you to represent this variation as a plurals resource.

Example

The following example shows how you would represent these two variations based on quantity in a resource file.

<resources...>
   <plurals name="my_text">
      <item quantity="one">There is 1 student</item>
      <item quantity="other">There are %d students</item>
   </plurals>
</resources>

The first parameter to the getQuantityString() method is the plurals resource ID. The second parameter selects the string to be used.

When the value of the quantity is 1, you use the string as is. When the value is not 1, you must supply a third parameter whose value is to be placed where %d is.

Resources res = your-activity.getResources();
String s1 = res.getQuantityString(R.plurals.my_text, 0,0);
String s2 = res.getQuantityString(R.plurals.my_text, 1,1);
String s3 = res.getQuantityString(R.plurals.my_text, 2,2);
String s4 = res.getQuantityString(R.plurals.my_text, 10,10);

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Post from TextView

TextView (432/474)
« Previous

Post from TextView

Description

The following code shows how to post Runnable from TextView.

Example

Layout xml

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

    <TextView android:id="@+id/my_text_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, MainActivity!"/>

</LinearLayout>

Java code

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

public class MainActivity extends Activity {
  private TextView mTextView;

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

    mTextView = (TextView) findViewById(R.id.my_text_view);

    mTextView.post(new Runnable() {

      @Override
      public void run() {
        String size = String.format("TextView's width: %d, height: %d",
            mTextView.getWidth(), mTextView.getHeight());
        Toast.makeText(MainActivity.this, size, Toast.LENGTH_SHORT).show();

      }
    });
  }
}
Post from TextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Print out the content provider result using the Cursor object

Content Provider (108/474)
« Previous

Print out the content provider result using the Cursor object

Description

The following code shows how to Print out the content provider result using the Cursor object.

Example

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

<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:stackFromBottom="false"
    android:transcriptMode="normal" />

<TextView
    android:id="@+id/contactName"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/contactID"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//from  w w  w  .ja va  2s. co m

import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

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

        Uri allContacts = Uri.parse ("content://contacts/people");

        Cursor c;
        if (android.os.Build.VERSION.SDK_INT <11) {
            //before Honeycomb
            c = managedQuery(allContacts, null, null, null, null);
        } else {
            //Honeycomb and later
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    null,
                    null,
                    null ,
                    null);
            c = cursorLoader.loadInBackground();
        }

        String[] columns = new String[] {
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID};

        int[] views = new int[] {R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter;

        if (android.os.Build.VERSION.SDK_INT <11) {
            //before Honeycomb
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views);
        } else {
            //Honeycomb and later
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        }

        this.setListAdapter(adapter);
        PrintContacts(c);
    }

    private void PrintContacts(Cursor c)
    {
        if (c.moveToFirst()) {
            do{
                String contactID = c.getString(c.getColumnIndex(
                        ContactsContract.Contacts._ID));
                String contactDisplayName =
                        c.getString(c.getColumnIndex(
                                ContactsContract.Contacts.DISPLAY_NAME));
            } while (c.moveToNext());
        }
   }
}

Add the following statements to the AndroidManifest.xml file:

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

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>

    <application
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name" >
      <activity
          android:label="@string/app_name"
          android:name=".ProviderActivity" >
          <intent-filter >
              <action android:name="android.intent.action.MAIN" />

              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>
  </application>
</manifest>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Producer and Consumer with Handler

Thread (442/474)
« Previous

Producer and Consumer with Handler

Description

The following code shows how to Producer and Consumer with Handler.

Example

Main Activity Java code

import java.util.Random;
/*w w  w  .  jav  a  2s.com*/
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class MainActivity extends Activity {

   private Handler handler;

   private class Consumer extends Thread {

      @Override
      public void run() {

         Looper.prepare();

         handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
               int number = msg.what;
               if (number % 2 == 0) {
                  Log.d("Consumer", number + " is divisible by 2");
               } else {
                  Log.d("Consumer", number + " is not divisible by 2");
               }
            }
         };

         Looper.loop();
      }
   }

   private class Producer extends Thread {

      public Producer(String name) {
         super(name);
      }

      @Override
      public void run() {
         Random random = new Random();
         while (true) {
            int number = random.nextInt(100);
            Log.d("Producer " + getName(), Integer.toString(number));
            handler.sendEmptyMessage(number);
            try {
               Thread.sleep(500);
            } catch (InterruptedException e) {
            }
         }
      }
   }

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      new Consumer().start();
      new Producer("A").start();
      new Producer("B").start();
   }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Programmatically Retrieving and Modifying the Preferences Values

Preference (192/474)
« Previous

Programmatically Retrieving and Modifying the Preferences Values

Description

To make use of the preferences in your application, you use the SharedPreferences class.

The following code shows how to programmatically Retrieving and Modifying the Preferences Values.

Example

package com.java2s.myapplication3.app;
//w ww .jav a  2  s  . c  o  m
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences appPrefs =
                getSharedPreferences("com.java2s.UsingPreferences_preferences",
                        MODE_PRIVATE);
        DisplayText(appPrefs.getString("editTextPref", ""));

        appPrefs = getSharedPreferences("com.java2s.UsingPreferences_preferences",
                MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = appPrefs.edit();
        prefsEditor.putString("editTextPref", "new value");
        prefsEditor.commit();
    }

    private void DisplayText(String str) {
        Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    }
}

Note

Here is the code to create the Preference.

Create a file at res/xml/myapppreferences.xml and populate the myapppreferences.xml file as follows:

         <?xml version="1.0" encoding="utf-8"?>
         <PreferenceScreen
             xmlns:android="http://schemas.android.com/apk/res/android">
             <PreferenceCategory android:title="Category 1">
                 <CheckBoxPreference
                     android:title="Checkbox"
                     android:defaultValue="false"
                     android:summary="True or False"
                     android:key="checkboxPref" />
                 </PreferenceCategory>
             <PreferenceCategory android:title="Category 2">
                 <EditTextPreference
                     android:summary="Enter a string"
                     android:defaultValue="[Enter a string here]"
                     android:title="Edit Text"
                     android:key="editTextPref" />
                 <RingtonePreference
                     android:summary="Select a ringtone"
                     android:title="Ringtones"
                     android:key="ringtonePref" />
                 <PreferenceScreen
                     android:title="Second Preference Screen"
                  android:summary= "Click here to go to the second Preference Screen"
                  android:key="secondPrefScreenPref" >
                  <EditTextPreference
                      android:summary="Enter a string"
                      android:title="Edit Text (second Screen)"
                      android:key="secondEditTextPref" />
              </PreferenceScreen>
          </PreferenceCategory>
      </PreferenceScreen>

Java code

      import android.os.Bundle;
      import android.preference.PreferenceActivity;
/*from w  ww  .j a v  a 2s.  c  o m*/
      public class AppPreferenceActivity extends PreferenceActivity {
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              //load the preferences from an XML file
              addPreferencesFromResource(R.xml.myapppreferences);
          }
      }

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Projections in Contact Content Provider

Content Provider (105/474)
« Previous

Projections in Contact Content Provider

Description

The second parameter of the managedQuery() method and third parameter for the CursorLoader class controls how many columns are returned by the query.

This parameter is known as the projection. Earlier, you specified null:

Example

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

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:stackFromBottom="false"
    android:transcriptMode="normal" />

<TextView
    android:id="@+id/contactName"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/contactID"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
//from ww  w. j  a v a  2 s .  c om
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

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

        Uri allContacts = Uri.parse("content://contacts/people");

        String[] projection = new String[]
                {ContactsContract.Contacts._ID,
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.Contacts.HAS_PHONE_NUMBER};

        Cursor c;
        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            c = managedQuery(allContacts, projection, null, null, null);
        } else {
            //Honeycomb and later
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    projection,
                    null,
                    null,
                    null);
            c = cursorLoader.loadInBackground();
        }

        String[] columns = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID};

        int[] views = new int[]{R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter;

        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views);
        } else {
            //Honeycomb and later
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        }

        this.setListAdapter(adapter);
    }

    private void PrintContacts(Cursor c) {
        if (c.moveToFirst()) {
            do {
                String contactID = c.getString(c.getColumnIndex(
                        ContactsContract.Contacts._ID));
                String contactDisplayName =
                        c.getString(c.getColumnIndex(
                                ContactsContract.Contacts.DISPLAY_NAME));

            } while (c.moveToNext());
        }
    }

}

Add the following statements to the AndroidManifest.xml file:

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

     <uses-sdk android:minSdkVersion="14" />
     <uses-permission android:name="android.permission.READ_CONTACTS"/>

     <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name" >
       <activity
           android:label="@string/app_name"
           android:name=".ProviderActivity" >
           <intent-filter >
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Provide extra layout xml file for Tablet

Layout (362/474)
« Previous

Provide extra layout xml file for Tablet

Description

The following code shows how to Provide extra layout xml file for Tablet.

Example

res\layout\main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- DEFAULT LAYOUT -->
<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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This is the default layout" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button One" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button Two" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button Three" />
</LinearLayout>

\res\layout\main_tablet.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- TABLET LAYOUT -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <!-- Group of user buttons taking 25% of screen width -->
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="This is the layout for TABLETS" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button One" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button Two" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button Three" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button Four" />
    </LinearLayout>
    <!-- Extra view to show detail content -->
    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:text="Detail View"
        android:background="#CCC"/>
</LinearLayout>

MainActivity.java

//ww  w.j  av  a2 s .co m
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
Provide extra layout xml file for Tablet

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Provide layout for landscape

Layout (341/474)
« Previous

Provide layout for landscape

Description

The following code shows how to Provide layout for landscape.

Example

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

res/layout-land/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

Java code

/* Copyright (c) 2008-2009 -- CommonsWare, LLC
//from   ww  w  . ja  va2 s  .com
   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.
*/
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class MainActivity extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;

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

    Button btn=(Button)findViewById(R.id.pick);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                    Uri.parse("content://contacts/people"));

        startActivityForResult(i, PICK_REQUEST);
      }
    });

    viewButton=(Button)findViewById(R.id.view);

    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });

    restoreMe();

    viewButton.setEnabled(contact!=null);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }

  @Override
  public Object onRetainNonConfigurationInstance() {
    return(contact);
  }

  private void restoreMe() {
    contact=null;

    if (getLastNonConfigurationInstance()!=null) {
      contact=(Uri)getLastNonConfigurationInstance();
    }
  }
}
Provide layout for landscape

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Put long-running service to a separate Thread

Service (209/474)
« Previous

Put long-running service to a separate Thread

Description

The service runs on the same thread as your activity.

For a long-running service, it is important that you put all long-running code into a separate thread so that it does not tie up the application that calls it.

The following code shows how to Put long-running service to a separate Thread.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
//ww w  .j  ava 2s.  com
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            new DoBackgroundTask().execute(new URL("http://www.java2s.net/somefiles.pdf"));

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }

    private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
        protected Long doInBackground(URL... urls) {
            int count = urls.length;
            long totalBytesDownloaded = 0;
            for (int i = 0; i < count; i++) {
                totalBytesDownloaded += DownloadFile(urls[i]);
                publishProgress((int) (((i+1) / (float) count) * 100));
            }
            return totalBytesDownloaded;
        }

        protected void onProgressUpdate(Integer... progress) {
            Toast.makeText (getBaseContext(),String.valueOf(progress[0]) + "% downloaded",Toast.LENGTH_LONG).show();
        }

        protected void onPostExecute(Long result) {
            Toast.makeText (getBaseContext(),
                    "Downloaded " + result + " bytes",
                    Toast.LENGTH_LONG).show();
            stopSelf();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText (this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
//from   w  w w .  j  ava 2  s .c  o  m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
           startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Put TableLayout into a LinearLayout

Layout (352/474)
« Previous

Put TableLayout into a LinearLayout

Description

The following code show to use put a TableLayout into a LinearLayout.

Example

// ww w.j av a 2  s.  c o m
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TableLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1,2"
  >
    <TableRow>
      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="2dip"
        android:paddingRight="4dip"
        android:text="Location:"
      />
      <EditText android:id="@+id/lat"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cursorVisible="true"
        android:editable="true"
        android:singleLine="true"
        android:layout_weight="1"
      />
      <EditText android:id="@+id/lon"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cursorVisible="true"
        android:editable="true"
        android:singleLine="true"
        android:layout_weight="1"
      />
    </TableRow>
  </TableLayout>
  <Button android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Show Me!"
  />
</LinearLayout>

Java code

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/* www  .j a va 2 s . c o  m*/
public class LaunchDemo extends Activity {
  private EditText lat;
  private EditText lon;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    Button btn=(Button)findViewById(R.id.map);
    lat=(EditText)findViewById(R.id.lat);
    lon=(EditText)findViewById(R.id.lon);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        String _lat=lat.getText().toString();
        String _lon=lon.getText().toString();
        Uri uri=Uri.parse("geo:"+_lat+","+_lon);

        startActivity(new Intent(Intent.ACTION_VIEW, uri));
      }
    });
  }
}
Put TableLayout into a LinearLayout

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Pyramid

OpenGL (402/474)
« Previous

Pyramid

Description

The following code shows how to create pyramid.

Example

Main Activity Java code

package com.java2s.myapplication3.app;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
//  ww w  . java2s. c  o  m
import javax.microedition.khronos.opengles.GL10;

import javax.microedition.khronos.egl.EGLConfig;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {

    private GLSurfaceView glView;
    private ColouredPyramid pyramid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        glView = new GLSurfaceView(this);
        glView.setRenderer(new MyOpenGLRenderer());
        setContentView(glView);
    }

    class MyOpenGLRenderer implements Renderer {
        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            gl.glViewport(0, 0, width, height);
            gl.glMatrixMode(GL10.GL_PROJECTION);
            gl.glLoadIdentity();
            GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f, 100.0f);
            gl.glMatrixMode(GL10.GL_MODELVIEW);
            gl.glLoadIdentity();
        }

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            pyramid = new ColouredPyramid();
        }
        @Override
        public void onDrawFrame(GL10 gl) {
            gl.glClearColor(0.0f, 0.0f, 0.0f, 1f);
            gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            gl.glLoadIdentity();
            gl.glTranslatef(0.0f, 0.0f, -10.0f);
            pyramid.draw(gl);
        }
    }
}

/**
 * @author tamas
 *
 */
class ColouredPyramid {

    private FloatBuffer vertexBuffer;
    private static final int VERTEX_SIZE = (3 + 4) * 4;
    private float vertices[] = {
            0.0f, 1.0f, 0.0f, 1, 0, 0, 1, // V1 - red
            -1.0f, 0.0f, 0.0f, 1, 0, 0, 1, // V2 - red
            0.0f, 0.0f, -1.0f, 1, 0, 0, 1, // V3 - red

            0.0f, 1.0f, 0.0f, 0, 1, 0, 1, // V1 - green
            0.0f, 0.0f, -1.0f, 0, 1, 0, 1, // V3 - green
            1.0f, 0.0f, 0.0f, 0, 1, 0, 1, // V4 - green

            0.0f, 1.0f, 0.0f, 0, 0, 1, 1, // V1 - blue
            1.0f, 0.0f, 0.0f, 0, 0, 1, 1, // V4 - blue
            -1.0f, 0.0f, 0.0f, 0, 0, 1, 1, // V2 - blue
    };

    private float rotation = 0.1f;

    public ColouredPyramid() {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(ColouredPyramid.VERTEX_SIZE * 3 * 4);
        byteBuffer.order(ByteOrder.nativeOrder());
        vertexBuffer = byteBuffer.asFloatBuffer();
        vertexBuffer.put(vertices);
        vertexBuffer.flip();
    }

    public void draw(GL10 gl) {
        rotation += 1.0f;
        gl.glRotatef(rotation, 1f, 1f, 1f);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

        vertexBuffer.position(0);
        gl.glVertexPointer(3, GL10.GL_FLOAT, ColouredPyramid.VERTEX_SIZE, vertexBuffer);
        vertexBuffer.position(3);
        gl.glColorPointer(4, GL10.GL_FLOAT, ColouredPyramid.VERTEX_SIZE, vertexBuffer);

        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3 * 3);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Qualifiers precedence order

Resources (20/474)
« Previous

Qualifiers precedence order

Description

Consider the directories as follows.

\res\layout\main_layout.xml
\res\layout-port\main_layout.xml
\res\layout-en\main_layout.xml

The layout file main_layout.xml is available in two additional variations: for the language or for the layout mode.

Even in portrait mode, Android picks the layout from the layout-en directory, because the language variation comes before the orientation variation.

Please note that string resources are based on individual IDs, whereas layout resources are file-based.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Query, delete, update, add Contacts

Contact (93/474)
« Previous

Query, delete, update, add Contacts

Description

The following code shows how to Query, delete, update, add Contacts.

Example

Manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest ...
        <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
        <uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
</manifest>

Main layout xml file

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="50dip"
        android:paddingTop="25dip"
        android:text="Click Buttons Below to Query, Add, Modify, Delete" />

    <Button
        android:id="@+id/queryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Click to Query Contacts" />

    <Button
        android:id="@+id/addContactButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Click to Add A Contact" />

    <Button
        android:id="@+id/modifyPhoneButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Click to Modify the Contact" />

    <Button
        android:id="@+id/deleteContactButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Click to Delete the Contact" />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.net.Uri;
import android.widget.Toast;
import android.database.Cursor;
import android.provider.Contacts.People;
import android.content.ContentValues;
/*from w  w  w  .  j  ava2s .  c  om*/
public class MainActivity extends Activity {
  public Uri addUri = null;
  public Uri changeUri = null;
    @Override  /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button queryButton = (Button)findViewById(R.id.queryButton);
        queryButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
               queryContactPhoneNumber();
            }
        });
        Button addButton = (Button)findViewById(R.id.addContactButton);
        addButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
               addContactPhoneNumber("Steve Wozniak", "415-555-7654");
            }
        });
        Button modButton = (Button)findViewById(R.id.modifyPhoneButton);
        modButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
               modifyPhoneNumber("916-555-1234");
            }
        });
        Button delButton = (Button)findViewById(R.id.deleteContactButton);
        delButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
               deleteContactPhoneNumber();
            }
        });
    }
  private void queryContactPhoneNumber() {
          String[] cols = new String[] {People.NAME, People.NUMBER};
          Uri myContacts = People.CONTENT_URI;
          Cursor mqCur = managedQuery(myContacts,cols,null,null,null);
          if (mqCur.moveToFirst()) {
                String myname = null;
                String mynumber = null;
                do {
                  myname = mqCur.getString(mqCur.getColumnIndex(People.NAME));
                  mynumber = mqCur.getString(mqCur.getColumnIndex(People.NUMBER));
                  Toast.makeText(this, myname + " " + mynumber, Toast.LENGTH_SHORT).show();
                } while (mqCur.moveToNext());
          }
  }
  private void addContactPhoneNumber(String newName, String newPhone) {
      ContentValues myContact = new ContentValues();
      myContact.put(People.NAME, newName);
      addUri = getContentResolver().insert(People.CONTENT_URI, myContact);
      Uri contentUri = Uri.withAppendedPath(addUri, People.Phones.CONTENT_DIRECTORY);
      myContact.clear();
      myContact.put(People.Phones.TYPE, People.TYPE_MOBILE);
      myContact.put(People.NUMBER, newPhone);
      changeUri = getContentResolver().insert(contentUri, myContact);
      Toast.makeText(this, "New Contact: " + newName + " " + newPhone, Toast.LENGTH_SHORT).show();
  }
  private void modifyPhoneNumber(String replacePhone) {
        if (changeUri == null) {
              Toast.makeText(this, "You need to create a new contact to update!", Toast.LENGTH_LONG).show();
        } else {
              ContentValues newPhoneNumber = new ContentValues();
              newPhoneNumber.put(People.Phones.TYPE, People.TYPE_MOBILE);
              newPhoneNumber.put(People.NUMBER, replacePhone);
              getContentResolver().update(changeUri, newPhoneNumber, null,null);
              Toast.makeText(this, "Updated phone number to: " + replacePhone, Toast.LENGTH_SHORT).show();
        }
      }
    private void deleteContactPhoneNumber() {
      if (changeUri == null) {
        Toast.makeText(this, "You need to create a new contact to delete!", Toast.LENGTH_LONG).show();

      } else {
        getContentResolver().delete(addUri, null, null);
        Toast.makeText(this, "Deleted contact at: " + addUri.toString(), Toast.LENGTH_SHORT).show();
        addUri = null;
        changeUri = null;
      }
    }
}
Query, delete, update, add Contacts

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Quoted strings

Resources (27/474)
« Previous

Quoted strings

Description

We can use Quoted strings in Android string resource file.

Example

The quoted strings need to be either escaped or placed in alternate quotes.

The following XML string resource file needs to be in the /res/values subdirectory.

<resources>
    <string name="simple_string">simple string</string>
    <string name="quoted_string">"quoted 'xyz' string"</string>
    <string name="double_quoted_string">\"double quotes\"</string>
</resources>

The following java code shows how to use the resource file above.

/*from w  w  w.  j  ava 2s .  c  o  m*/
String simpleString = activity.getString(R.string.simple_string);
textView.setText(simpleString);

String quotedString = activity.getString(R.string.quoted_string);
textView.setText(quotedString);

String doubleQuotedString = activity.getString(R.string.double_quoted_string);
textView.setText(doubleQuotedString);

Note

From the code above we can see that there are two ways to add quotations to a string.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - RadioGroup Checked Change Listener

RadioButton (413/474)
« Previous

RadioGroup Checked Change Listener

Description

The following code shows how to listen to selection changed event on a RadioGroup.

Example

Layout xml

//from  w  w w.jav  a 2  s  . c  o  m
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RadioButton
        android:id="@+id/anotherRadBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Outside" />

    <RadioGroup
        android:id="@+id/radGrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/chRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chicken" />

        <RadioButton
            android:id="@+id/fishRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fish" />

        <RadioButton
            android:id="@+id/stkRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Steak" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My Favorite" />

    </RadioGroup>
</LinearLayout>

Java code

package com.java2s.app;
/*from   ww w .j  a va  2  s  .  c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;

public class MainActivity extends Activity {

    protected static final String TAG = "RadioGroupActivity";

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

        RadioGroup radGrp = (RadioGroup) findViewById(R.id.radGrp);

        int checkedRadioButtonId = radGrp.getCheckedRadioButtonId();

        radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int id) {
                switch (id) {
                    case -1:
                        Log.v(TAG, "Choices cleared!");
                        break;
                    case R.id.chRBtn:
                        Log.v(TAG, "Chose Chicken");
                        break;
                    case R.id.fishRBtn:
                        Log.v(TAG, "Chose Fish");
                        break;
                    case R.id.stkRBtn:
                        Log.v(TAG, "Chose Steak");
                        break;
                    default:
                        Log.v(TAG, "Huh?");
                        break;
                }
            }
        });
    }

}
RadioGroup Checked Change Listener

We can get the currently checked RadioButton using getCheckedRadioButtonId(), which returns the resource ID of the checked item or -1 if nothing is checked.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - RadioGroup with More Than Just RadioButtons

RadioButton (408/474)
« Previous

RadioGroup with More Than Just RadioButtons

Description

You can have non-RadioButton controls inside a radio group.

Example

The following RadioGroup adds a TextView after the last radio button. Also note that the first radio button (anotherRadBtn) lies outside the radio group.

// www  . j a v  a 2  s . c  o m
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <RadioButton
        android:id="@+id/anotherRadBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Outside" />

    <RadioGroup
        android:id="@+id/radGrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/chRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chicken" />

        <RadioButton
            android:id="@+id/fishRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fish" />

        <RadioButton
            android:id="@+id/stkRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Steak" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My Favorite" />

    </RadioGroup>
</LinearLayout>
RadioGroup with More Than Just RadioButtons

Note

The radio group can only enforce single-selection on the radio buttons in its own container.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Raise alert or toast from Button click event

Dialog (279/474)
« Previous

Raise alert or toast from Button click event

Description

The following code shows how to Raise alert or toast from Button click event.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
  <Button
    android:id="@+id/alert"
    android:text="Raise an alert"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
  <Button
    android:id="@+id/toast"
    android:text="Make a toast"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

Java code

/***//from  w w  w.  java  2  s  .c  om
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
  Button alert;
  Button toast;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.main);

    alert=(Button)findViewById(R.id.alert);
    alert.setOnClickListener(this);
    toast=(Button)findViewById(R.id.toast);
    toast.setOnClickListener(this);
  }

  public void onClick(View view) {
    if (view==alert) {
      new AlertDialog.Builder(this)
        .setTitle("MessageDemo")
        .setMessage("eek!")
        .setNeutralButton("Close", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dlg, int sumthin) {
            // do nothing -- it will close on its own
          }
        })
        .show();
    }
    else {
      Toast
        .makeText(this, "<clink, clink>", Toast.LENGTH_SHORT)
        .show();
    }
  }
}
Raise alert or toast from Button click event

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - React to configuration changed event

Activity (69/474)
« Previous

React to configuration changed event

Description

The following code shows how to React to configuration changed event.

Example

Set the config change masks.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            android:configChanges="orientation|keyboardHidden|screenSize"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ToggleButton
    android:id="@+id/toggleButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Lock"
    android:textOn="LOCKED"
  />
</LinearLayout>

Main activity Java code

/*from w  w  w  . j a va 2 s  .co m*/
package com.java2s.myapplication3.app;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadView();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        saveState();
        loadView();
    }
    private void saveState() {
        //Implement any code to persist the UI state
    }
    private void loadView() {
        setContentView(R.layout.activity_main);
    }
}
React to configuration changed event

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - React to long-press listener

Event (300/474)
« Previous

React to long-press listener

Description

The following code shows how to React to long-press listener.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main layout xml

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

    <!-- Top Row of Draggable Items -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <ImageView
            android:id="@+id/image1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:id="@+id/image2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:id="@+id/image3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

    <!-- Bottom Row of Drop Targets -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >
        <com.examples.dragtouch.DropTargetView
            android:id="@+id/drag_target1"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#A00" />
        <com.examples.dragtouch.DropTargetView
            android:id="@+id/drag_target2"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#0A0" />
        <com.examples.dragtouch.DropTargetView
            android:id="@+id/drag_target3"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#00A" />
    </LinearLayout>

</RelativeLayout>

Main activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.DragShadowBuilder;
public class MainActivity extends Activity implements OnLongClickListener {
  /*from   ww w.j a va 2 s  .  c  o  m*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Attach long-press listener to each ImageView
        findViewById(R.id.image1).setOnLongClickListener(this);
        findViewById(R.id.image2).setOnLongClickListener(this);
        findViewById(R.id.image3).setOnLongClickListener(this);
    }

  @Override
  public boolean onLongClick(View v) {
    DragShadowBuilder shadowBuilder = new DragShadowBuilder(v);
//      DragShadowBuilder shadowBuilder = new DrawableDragShadowBuilder(v,
//              getResources().getDrawable(R.drawable.ic_launcher));
      v.startDrag(null, shadowBuilder, ((ImageView) v).getDrawable(), 0);
    return true;
  }

}

/*
 * Copyright (C) 2011 by Mark Doffman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE
 */

class DrawableDragShadowBuilder extends DragShadowBuilder {
    private Drawable mDrawable;

    public DrawableDragShadowBuilder(View view, Drawable drawable) {
        super(view);
        // Set the drawable and apply a green filter to it
        mDrawable = drawable;
        mDrawable.setColorFilter(new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY));
    }

    @Override
    public void onProvideShadowMetrics(Point shadowSize, Point touchPoint) {
        // Fill in the size
        shadowSize.x = mDrawable.getIntrinsicWidth();
        shadowSize.y = mDrawable.getIntrinsicHeight();
        // Fill in the location of the shadow relative to the touch.
        // Here we center the shadow under the finger.
        touchPoint.x = mDrawable.getIntrinsicWidth() / 2;
        touchPoint.y = mDrawable.getIntrinsicHeight() / 2;

        mDrawable.setBounds(new Rect(0, 0, shadowSize.x, shadowSize.y));
    }

    @Override
    public void onDrawShadow(Canvas canvas) {
        //Draw the shadow view onto the provided canvas
        mDrawable.draw(canvas);
    }
}

custom view java code

/*w w w. j  av  a 2  s .  c  o m*/

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.View.OnDragListener;
import android.widget.ImageView;

public class DropTargetView extends ImageView implements OnDragListener {

    private boolean mDropped;

    public DropTargetView(Context context) {
        super(context);
        init();
    }

    public DropTargetView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DropTargetView(Context context, AttributeSet attrs, int defaultStyle) {
        super(context, attrs, defaultStyle);
        init();
    }

    private void init() {
        //We must set a valid listener to receive DragEvents
        setOnDragListener(this);
    }

    @Override
    public boolean onDrag(android.view.View v, DragEvent event) {
        PropertyValuesHolder pvhX, pvhY;
        switch (event.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:
            //React to a new drag by shrinking the view
            pvhX = PropertyValuesHolder.ofFloat("scaleX", 0.5f);
            pvhY = PropertyValuesHolder.ofFloat("scaleY", 0.5f);
            ObjectAnimator.ofPropertyValuesHolder(this, pvhX, pvhY).start();
            //Clear the current drop image on a new event
            setImageDrawable(null);
            mDropped = false;
            break;
        case DragEvent.ACTION_DRAG_ENDED:
            // React to a drag ending by resetting the view size
            // if we weren't the drop target.
            if (!mDropped) {
                pvhX = PropertyValuesHolder.ofFloat("scaleX", 1f);
                pvhY = PropertyValuesHolder.ofFloat("scaleY", 1f);
                ObjectAnimator.ofPropertyValuesHolder(this, pvhX, pvhY).start();
                mDropped = false;
            }
            break;
        case DragEvent.ACTION_DRAG_ENTERED:
            //React to a drag entering this view by growing slightly
            pvhX = PropertyValuesHolder.ofFloat("scaleX", 0.75f);
            pvhY = PropertyValuesHolder.ofFloat("scaleY", 0.75f);
            ObjectAnimator.ofPropertyValuesHolder(this, pvhX, pvhY).start();
            break;
        case DragEvent.ACTION_DRAG_EXITED:
            //React to a drag leaving this view by returning to previous size
            pvhX = PropertyValuesHolder.ofFloat("scaleX", 0.5f);
            pvhY = PropertyValuesHolder.ofFloat("scaleY", 0.5f);
            ObjectAnimator.ofPropertyValuesHolder(this, pvhX, pvhY).start();
            break;
        case DragEvent.ACTION_DROP:
            // React to a drop event with a short animation keyframe animation
            // and setting this view's image to the drawable passed along with
            // the drag event

            // This animation shrinks the view briefly down to nothing
            // and then back.
            Keyframe frame0 = Keyframe.ofFloat(0f, 0.75f);
            Keyframe frame1 = Keyframe.ofFloat(0.5f, 0f);
            Keyframe frame2 = Keyframe.ofFloat(1f, 0.75f);
            pvhX = PropertyValuesHolder.ofKeyframe("scaleX", frame0, frame1,
                    frame2);
            pvhY = PropertyValuesHolder.ofKeyframe("scaleY", frame0, frame1,
                    frame2);
            ObjectAnimator.ofPropertyValuesHolder(this, pvhX, pvhY).start();
            //Set our image from the Object passed with the DragEvent
            setImageDrawable((Drawable) event.getLocalState());
            //We set the dropped flag to the ENDED animation will not also run
            mDropped = true;
            break;
        default:
            //Ignore events we aren't interested in
            return false;
        }
        //Declare interest in all events we have noted
        return true;
    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read and parse CSV file from asset folder

Resources (49/474)
« Previous

Read and parse CSV file from asset folder

Description

The following code shows how to Read and parse CSV file from asset folder.

Example

Register permission for WRITE_EXTERNAL_STORAGE

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <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="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Java code for main activity

package com.java2s.myapplication3.app;
/*from   w  w  w  .j  av  a 2 s .c om*/
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        setContentView(tv);

        try {
            AssetManager manager = getAssets();
            InputStream in = manager.open("data.csv");

            ArrayList<Person> cooked = parse(in);
            StringBuilder builder = new StringBuilder();
            for(Person piece : cooked) {
                builder.append(String.format("%s is %s years old, and likes the color %s",
                        piece.name, piece.age, piece.color));
                builder.append('\n');
            }
            tv.setText(builder.toString());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /* Simple CSV Parser */
    private static final int COL_NAME = 0;
    private static final int COL_AGE = 1;
    private static final int COL_COLOR = 2;

    private ArrayList<Person> parse(InputStream in) throws IOException {
        ArrayList<Person> results = new ArrayList<Person>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String nextLine = null;
        while ((nextLine = reader.readLine()) != null) {
            String[] tokens = nextLine.split(",");
            if (tokens.length != 3) {
                Log.w("CSVParser", "Skipping Bad CSV Row");
                continue;
            }
            //Add new parsed result
            Person current = new Person();
            current.name = tokens[COL_NAME];
            current.color = tokens[COL_COLOR];
            current.age = tokens[COL_AGE];

            results.add(current);
        }
        in.close();
        return results;
    }
}
class Person {
    public String name;
    public String age;
    public String color;

    public Person() { }
}

data.csv

Jack,Red,12
Jane,Black,13
Jode,Brown,14

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read Calendar information

Calendar (80/474)
« Previous

Read Calendar information

Description

The following code shows how to Read Calendar information.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Add two activity settings in manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.java2s.myapplication3.app.CalendarDetailActivity"
            ...
            ...
        </activity>

    </application>

</manifest>

Java code for CalendarListActivity.java

/*w w w .j a  va 2  s  .  c om*/
package com.java2s.myapplication3.app;

import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity implements
        LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {
    private static final int LOADER_LIST = 100;

    SimpleCursorAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLoaderManager().initLoader(LOADER_LIST, null, this);

        // Display all calendars in a ListView
        mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, null,
                new String[] {
                        CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                        CalendarContract.Calendars.ACCOUNT_NAME },
                new int[] {
                        android.R.id.text1, android.R.id.text2 }, 0);
        setListAdapter(mAdapter);
        // Listen for item selections
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        Cursor c = mAdapter.getCursor();
        if (c != null && c.moveToPosition(position)) {
            Intent intent = new Intent(this, CalendarDetailActivity.class);
            // Pass the _ID and TITLE of the selected calendar to the next
            // Activity
            intent.putExtra(Intent.EXTRA_UID, c.getInt(0));
            intent.putExtra(Intent.EXTRA_TITLE, c.getString(1));
            startActivity(intent);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // Return all calendars, ordered by name
        String[] projection = new String[] { CalendarContract.Calendars._ID,
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                CalendarContract.Calendars.ACCOUNT_NAME };

        return new CursorLoader(this, CalendarContract.Calendars.CONTENT_URI,
                projection, null, null,
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

Java code for Calendar detail

import java.text.SimpleDateFormat;
import java.util.Date;
//from   w w w  . j av  a2s.  co m
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;

public class CalendarDetailActivity extends ListActivity implements
        LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener,
        AdapterView.OnItemLongClickListener {
    private static final int LOADER_DETAIL = 101;

    SimpleCursorAdapter mAdapter;

    int mCalendarId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCalendarId = getIntent().getIntExtra(Intent.EXTRA_UID, -1);

        String title = getIntent().getStringExtra(Intent.EXTRA_TITLE);
        setTitle(title);

        getLoaderManager().initLoader(LOADER_DETAIL, null, this);

        // Display all events in a ListView
        mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, null,
                new String[] {
                        CalendarContract.Events.TITLE,
                        CalendarContract.Events.EVENT_LOCATION },
                new int[] {
                        android.R.id.text1, android.R.id.text2 }, 0);
        setListAdapter(mAdapter);
        // Listen for item selections
        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Add Event")
            .setIcon(android.R.drawable.ic_menu_add)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        showAddEventDialog();
        return true;
    }

    // Display a dialog to add a new event
    private void showAddEventDialog() {
        final EditText nameText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("New Event");
        builder.setView(nameText);
        builder.setNegativeButton("Cancel", null);
        builder.setPositiveButton("Add Event",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addEvent(nameText.getText().toString());
                    }
                });
        builder.show();
    }

    // Add an event to the calendar with the specified name
    // and the current time as the start date
    private void addEvent(String eventName) {
        long start = System.currentTimeMillis();
        // End 1 hour from now
        long end = start + (3600 * 1000);

        ContentValues cv = new ContentValues(5);
        cv.put(CalendarContract.Events.CALENDAR_ID, mCalendarId);
        cv.put(CalendarContract.Events.TITLE, eventName);
        cv.put(CalendarContract.Events.DESCRIPTION,
                "Event created by Android Recipes");
        cv.put(CalendarContract.Events.EVENT_TIMEZONE,
                Time.getCurrentTimezone());
        cv.put(CalendarContract.Events.DTSTART, start);
        cv.put(CalendarContract.Events.DTEND, end);

        getContentResolver().insert(CalendarContract.Events.CONTENT_URI, cv);
    }

    // Remove the selected event from the calendar
    private void deleteEvent(int eventId) {
        String selection = CalendarContract.Events._ID + " = ?";
        String[] selectionArgs = { String.valueOf(eventId) };
        getContentResolver().delete(CalendarContract.Events.CONTENT_URI,
                selection, selectionArgs);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        Cursor c = mAdapter.getCursor();
        if (c != null && c.moveToPosition(position)) {
            // Show a dialog with more detailed data about the event when
            // clicked
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            StringBuilder sb = new StringBuilder();

            sb.append("Location: "
                    + c.getString(
                            c.getColumnIndex(CalendarContract.Events.EVENT_LOCATION))
                    + "\n\n");
            int startDateIndex = c.getColumnIndex(CalendarContract.Events.DTSTART);
            Date startDate = c.isNull(startDateIndex) ? null
                    : new Date( Long.parseLong(c.getString(startDateIndex)) );
            if (startDate != null) {
                sb.append("Starts At: " + sdf.format(startDate) + "\n\n");
            }
            int endDateIndex = c.getColumnIndex(CalendarContract.Events.DTEND);
            Date endDate = c.isNull(endDateIndex) ? null
                    : new Date( Long.parseLong(c.getString(endDateIndex)) );
            if (endDate != null) {
                sb.append("Ends At: " + sdf.format(endDate) + "\n\n");
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(
                    c.getString(c.getColumnIndex(CalendarContract.Events.TITLE)) );
            builder.setMessage(sb.toString());
            builder.setPositiveButton("OK", null);
            builder.show();
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long id) {
        Cursor c = mAdapter.getCursor();
        if (c != null && c.moveToPosition(position)) {
            // Allow the user to delete the event on a long-press
            final int eventId = c.getInt(
                    c.getColumnIndex(CalendarContract.Events._ID));
            String eventName = c.getString(
                    c.getColumnIndex(CalendarContract.Events.TITLE));
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete Event");
            builder.setMessage(String.format(
                    "Are you sure you want to delete %s?",
                    TextUtils.isEmpty(eventName) ? "this event" : eventName));
            builder.setNegativeButton("Cancel", null);
            builder.setPositiveButton("Delete Event",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            deleteEvent(eventId);
                        }
                    });
            builder.show();
        }

        return true;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // Return all calendars, ordered by name
        String[] projection = new String[] { CalendarContract.Events._ID,
                CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART,
                CalendarContract.Events.DTEND,
                CalendarContract.Events.EVENT_LOCATION };
        String selection = CalendarContract.Events.CALENDAR_ID + " = ?";
        String[] selectionArgs = { String.valueOf(mCalendarId) };

        return new CursorLoader(this, CalendarContract.Events.CONTENT_URI,
                projection, selection, selectionArgs,
                CalendarContract.Events.DTSTART + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read contact

Contact (87/474)
« Previous

Read contact

Description

The following code shows how to Read contact and get contact information.

Example

manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.manning.androidhacks.hack045"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="preferExternal">

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

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

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

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<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/times_opened"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

</LinearLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning/*from   www .j a v  a 2 s .c om*/
 * See the file license.txt for copying permission.
 ******************************************************************************/
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.SharedPreferences;
import android.util.Log;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

  private static final String PREFS_NAME = "main_activity_prefs";
  private static final String TIMES_OPENED_KEY = "times_opened_key";
  private static final String TIMES_OPENED_FMT = "Times opened: %d";

  private TextView mTextView;
  private int mTimesOpened;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    mTextView = (TextView) findViewById(R.id.times_opened);
  }

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

    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
    mTimesOpened = prefs.getInt(TIMES_OPENED_KEY, 1);
    mTextView.setText(String.format(TIMES_OPENED_FMT, mTimesOpened));
  }

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

    Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
    editor.putInt(TIMES_OPENED_KEY, mTimesOpened + 1);
    SharedPreferencesCompat.apply(editor);
  }
}

/**
 * Reflection utils to call SharedPreferences$Editor.apply when possible,
 * falling back to commit when apply isn't available.
 */
class SharedPreferencesCompat {
  private static final String TAG = SharedPreferencesCompat.class
      .getCanonicalName();
  private static final Method sApplyMethod = findApplyMethod();

  private static Method findApplyMethod() {
    try {
      Class<?> cls = SharedPreferences.Editor.class;
      return cls.getMethod("apply");
    } catch (NoSuchMethodException unused) {
      // fall through
    }
    return null;
  }

  public static void apply(SharedPreferences.Editor editor) {
    if (sApplyMethod != null) {
      try {
        sApplyMethod.invoke(editor);
        Log.d(TAG, "Apply method was invoked!");
        return;
      } catch (InvocationTargetException unused) {
        // fall through
      } catch (IllegalAccessException unused) {
        // fall through
      }
    }
    editor.commit();
    Log.d(TAG, "Commit method was invoked!");
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read contact list

Contact (86/474)
« Previous

Read contact list

Description

The following code shows how to read contact list.

Example

manifest xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.contactlist"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ContactList"
                  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=".ContactDetails" android:label="@string/app_name"></activity>
    </application>
    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
</manifest>

layout xml file

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

  <TextView android:id="@+id/contact_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

  <TextView android:id="@+id/contact_phone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
// w  ww. j  av a 2  s  .com
public class ContactList extends ListActivity implements OnItemClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        String[] projection = new String[] { People._ID, People.NAME };
        Cursor cursor = managedQuery(People.CONTENT_URI, projection, null, null, People.NAME + " ASC");

        ListAdapter adapter = new SimpleCursorAdapter(
          this,
          android.R.layout.two_line_list_item,
          cursor,
          new String[] { People._ID, People.NAME },
          new int[] { android.R.id.text1, android.R.id.text2 }
        );
        setListAdapter(adapter);

        getListView().setOnItemClickListener(this);

    }

  public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

    Uri contactUri = ContentUris.withAppendedId(People.CONTENT_URI, id);
    Intent intent = new Intent(this, ContactDetails.class);
    intent.setData(contactUri);
    startActivity(intent);

  }

}

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.widget.TextView;
/*from   w w  w  . ja  v  a  2  s  . com*/
public class ContactDetails extends Activity {

  TextView nameField = null;
  TextView phoneField = null;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.details);

        nameField = (TextView) findViewById(R.id.contact_name);
        phoneField = (TextView) findViewById(R.id.contact_phone);

    }

  @Override
  protected void onStart() {

    super.onStart();

    Cursor cursor = managedQuery(getIntent().getData(), null, null, null, null);
    cursor.moveToFirst();

    nameField.setText(cursor.getString(cursor.getColumnIndex(People.NAME)));
    phoneField.setText(cursor.getString(cursor.getColumnIndex(People.NUMBER)));

  }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read Database backed content provider and fill ListView

Content Provider (107/474)
« Previous

Read Database backed content provider and fill ListView

Description

The following code shows how to Read Database backed content provider and fill ListView.

Example

Register provider in manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:name=".MyProvider"
        android:authorities="com.examples.sharedb.friendprovider">
    </provider>

    </application>

</manifest>

Layout xml file

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

Main activity Java file

package com.java2s.myapplication3.app;
//from w  w  w.  ja va  2  s. c o m
import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MainActivity extends Activity implements
        LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener {
    private static final int LOADER_LIST = 100;
    SimpleCursorAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // getSupportLoaderManager().initLoader(LOADER_LIST, null, this);

        mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null,
                new String[]{MyProvider.Columns.FIRST},
                new int[]{android.R.id.text1}, 0);

        ListView list = new ListView(this);
        list.setOnItemClickListener(this);
        list.setAdapter(mAdapter);

        setContentView(list);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        Cursor c = mAdapter.getCursor();
        c.moveToPosition(position);

        Uri uri = Uri.withAppendedPath(MyProvider.CONTENT_URI, c.getString(0));
        String[] projection = new String[]{MyProvider.Columns.FIRST,
                MyProvider.Columns.LAST,
                MyProvider.Columns.PHONE};
        //Get the full record
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        cursor.moveToFirst();

        String message = String.format("%s %s, %s", cursor.getString(0), cursor.getString(1), cursor.getString(2));
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        cursor.close();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] projection = new String[]{MyProvider.Columns._ID,
                MyProvider.Columns.FIRST};
        return new CursorLoader(this, MyProvider.CONTENT_URI,
                projection, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }
}

Content provider file

package com.java2s.myapplication3.app;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
//from w w  w  .  j  a  va 2s  . co m
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class MyProvider extends ContentProvider {

    public static final Uri CONTENT_URI = Uri.parse("content://com.examples.sharedb.friendprovider/friends");

    public static final class Columns {
        public static final String _ID = "_id";
        public static final String FIRST = "firstName";
        public static final String LAST = "lastName";
        public static final String PHONE = "phoneNumber";
    }

    /* Uri Matching */
    private static final int FRIEND = 1;
    private static final int FRIEND_ID = 2;

    private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        matcher.addURI(CONTENT_URI.getAuthority(), "friends", FRIEND);
        matcher.addURI(CONTENT_URI.getAuthority(), "friends/#", FRIEND_ID);
    }

    SQLiteDatabase db;

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int result = matcher.match(uri);
        switch(result) {
        case FRIEND:
            return db.delete(ShareDbHelper.TABLE_NAME, selection, selectionArgs);
        case FRIEND_ID:
            return db.delete(ShareDbHelper.TABLE_NAME, "_ID = ?", new String[]{uri.getLastPathSegment()});
        default:
            return 0;
        }
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long id = db.insert(ShareDbHelper.TABLE_NAME, null, values);
        if(id >= 0) {
            return Uri.withAppendedPath(uri, String.valueOf(id));
        } else {
            return null;
        }
    }

    @Override
    public boolean onCreate() {
        ShareDbHelper helper = new ShareDbHelper(getContext());
        db = helper.getWritableDatabase();
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        int result = matcher.match(uri);
        switch(result) {
        case FRIEND:
            return db.query(ShareDbHelper.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
        case FRIEND_ID:
            return db.query(ShareDbHelper.TABLE_NAME, projection, "_ID = ?", new String[]{uri.getLastPathSegment()}, null, null, sortOrder);
        default:
            return null;
        }
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int result = matcher.match(uri);
        switch(result) {
        case FRIEND:
            return db.update(ShareDbHelper.TABLE_NAME, values, selection, selectionArgs);
        case FRIEND_ID:
            return db.update(ShareDbHelper.TABLE_NAME, values, "_ID = ?", new String[]{uri.getLastPathSegment()});
        default:
            return 0;
        }
    }

}
class ShareDbHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "frienddb";
    private static final int DB_VERSION = 1;

    public static final String TABLE_NAME = "friends";
    public static final String COL_FIRST = "firstName";
    public static final String COL_LAST = "lastName";
    public static final String COL_PHONE = "phoneNumber";

    private static final String STRING_CREATE =
        "CREATE TABLE "+TABLE_NAME+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
        +COL_FIRST+" TEXT, "+COL_LAST+" TEXT, "+COL_PHONE+" TEXT);";

    public ShareDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(STRING_CREATE);

        ContentValues cv = new ContentValues(3);
        cv.put(COL_FIRST, "John");
        cv.put(COL_LAST, "Doe");
        cv.put(COL_PHONE, "8885551234");
        db.insert(TABLE_NAME, null, cv);
        cv = new ContentValues(3);
        cv.put(COL_FIRST, "Jane");
        cv.put(COL_LAST, "Doe");
        cv.put(COL_PHONE, "8885552345");
        db.insert(TABLE_NAME, null, cv);
        cv = new ContentValues(3);
        cv.put(COL_FIRST, "Jill");
        cv.put(COL_LAST, "Doe");
        cv.put(COL_PHONE, "8885553456");
        db.insert(TABLE_NAME, null, cv);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read metadata for a video

Video (452/474)
« Previous

Read metadata for a video

Description

The following code shows how to Read metadata for a video.

Example

Main layout xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:id="@+id/button_select"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pick Video"
        android:onClick="onSelectClick" />
    <TextView
        android:id="@+id/text_metadata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button_select"
        android:layout_margin="15dp" />
    <ImageView
        android:id="@+id/image_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp" />
</RelativeLayout>

Java code for main activity

package com.java2s.myapplication3.app;
//from   w w w.  jav a  2s  .c om
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
    private static final int PICK_VIDEO = 100;

    private ImageView mFrameView;
    private TextView mMetadataView;

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

        mFrameView = (ImageView) findViewById(R.id.image_frame);
        mMetadataView = (TextView) findViewById(R.id.text_metadata);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_VIDEO && resultCode == RESULT_OK && data != null) {
            Uri video = data.getData();
            MetadataTask task = new MetadataTask(this, mFrameView, mMetadataView);
            task.execute(video);
        }
    }

    public void onSelectClick(View v) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        startActivityForResult(intent, PICK_VIDEO);
    }

    public static class MetadataTask extends AsyncTask<Uri, Void, Bundle> {
        private Context mContext;
        private ImageView mFrame;
        private TextView mMetadata;
        private ProgressDialog mProgress;

        public MetadataTask(Context context, ImageView frame, TextView metadata) {
            mContext = context;
            mFrame = frame;
            mMetadata = metadata;
        }

        @Override
        protected void onPreExecute() {
            mProgress = ProgressDialog.show(mContext, "", "Analyzing Video File...", true);
        }

        @Override
        protected Bundle doInBackground(Uri... params) {
            Uri video = params[0];
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(mContext, video);

            Bitmap frame = retriever.getFrameAtTime();

            String date = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE);
            String duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);

            Bundle result = new Bundle();
            result.putParcelable("frame", frame);
            result.putString("date", date);
            result.putString("duration", duration);
            result.putString("width", width);
            result.putString("height", height);

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            if (mProgress != null) {
                mProgress.dismiss();
                mProgress = null;
            }

            Bitmap frame = result.getParcelable("frame");
            mFrame.setImageBitmap(frame);
            String metadata = String.format("Video Date: %s\nVideo Duration: %s\nVideo Size: %s x %s",
                    result.getString("date"),
                    result.getString("duration"),
                    result.getString("width"),
                    result.getString("height"));
            mMetadata.setText(metadata);
        }
    }

}
Read metadata for a video

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Read USB device information

Hardware (124/474)
« Previous

Read USB device information

Description

The following code shows how to Read USB device information.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".USBActivity"
            android:label="@string/title_activity_usb" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>

            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
        </activity>
    </application>

</manifest>

res\layout\main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button_connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connect"
        android:onClick="onConnectClick" />
    <TextView
        android:id="@+id/text_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

res\menu\main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_settings"
        android:title="@string/menu_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
</menu>

\res\xml\device_filter.xml

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

USBActivity.java

import java.util.HashMap;
/*from w  ww  .  j av  a 2s.co m*/
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    private static final String TAG = "UsbHost";

    TextView mDeviceText, mDisplayText;
    Button mConnectButton;

    UsbManager mUsbManager;
    UsbDevice mDevice;
    PendingIntent mPermissionIntent;

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

        mDeviceText = (TextView) findViewById(R.id.text_status);
        mDisplayText = (TextView) findViewById(R.id.text_data);
        mConnectButton = (Button) findViewById(R.id.button_connect);

        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, filter);
        //Check currently connected devices
        updateDeviceList();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mUsbReceiver);
    }

    public void onConnectClick(View v) {
        if (mDevice == null) {
            return;
        }
        mDisplayText.setText("---");

        //This will either prompt the user with a grant permission dialog,
        // or immediately fire the ACTION_USB_PERMISSION broadcast if the
        // user has already granted it to us.
        mUsbManager.requestPermission(mDevice, mPermissionIntent);
    }

    /*
     * Receiver to catch user permission responses, which are required in order to actuall
     * interact with a connected device.
     */
    private static final String ACTION_USB_PERMISSION = "com.android.recipes.USB_PERMISSION";
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                        && device != null) {
                        //Query the device's descriptor
                        getDeviceStatus(device);
                } else {
                    Log.d(TAG, "permission denied for device " + device);
                }
            }
        }
    };

    /*
     * Initiate a control transfer to request the first configuration
     * descriptor of the device.
     */
    //Type: Indicates whether this is a read or write
    // Matches USB_ENDPOINT_DIR_MASK for either IN or OUT
    private static final int REQUEST_TYPE = 0x80;
    //Request: GET_CONFIGURATION_DESCRIPTOR = 0x06
    private static final int REQUEST = 0x06;
    //Value: Descriptor Type (High) and Index (Low)
    // Configuration Descriptor = 0x2
    // Index = 0x0 (First configuration)
    private static final int REQ_VALUE = 0x200;
    private static final int REQ_INDEX = 0x00;
    private static final int LENGTH = 64;
    private void getDeviceStatus(UsbDevice device) {
        UsbDeviceConnection connection = mUsbManager.openDevice(device);
        //Create a sufficiently large buffer for incoming data
        byte[] buffer = new byte[LENGTH];
        connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX,
                buffer, LENGTH, 2000);
        //Parse received data into a description
        String description = parseConfigDescriptor(buffer);

        mDisplayText.setText(description);
        connection.close();
    }

    /*
     * Parse the USB configuration descriptor response per the
     * USB Specification.  Return a printable description of
     * the connected device.
     */
    private static final int DESC_SIZE_CONFIG = 9;
    private String parseConfigDescriptor(byte[] buffer) {
        StringBuilder sb = new StringBuilder();
        //Parse configuration descriptor header
        int totalLength = (buffer[3] &0xFF) << 8;
        totalLength += (buffer[2] & 0xFF);
        //Interface count
        int numInterfaces = (buffer[5] & 0xFF);
        //Configuration attributes
        int attributes = (buffer[7] & 0xFF);
        //Power is given in 2mA increments
        int maxPower = (buffer[8] & 0xFF) * 2;

        sb.append("Configuration Descriptor:\n");
        sb.append("Length: " + totalLength + " bytes\n");
        sb.append(numInterfaces + " Interfaces\n");
        sb.append(String.format("Attributes:%s%s%s\n",
                (attributes & 0x80) == 0x80 ? " BusPowered" : "",
                (attributes & 0x40) == 0x40 ? " SelfPowered" : "",
                (attributes & 0x20) == 0x20 ? " RemoteWakeup" : ""));
        sb.append("Max Power: " + maxPower + "mA\n");

        //The rest of the descriptor is interfaces and endpoints
        int index = DESC_SIZE_CONFIG;
        while (index < totalLength) {
            //Read length and type
            int len = (buffer[index] & 0xFF);
            int type = (buffer[index+1] & 0xFF);
            switch (type) {
            case 0x04: //Interface Descriptor
                int intfNumber = (buffer[index+2] & 0xFF);
                int numEndpoints = (buffer[index+4] & 0xFF);
                int intfClass = (buffer[index+5] & 0xFF);

                sb.append(String.format("- Interface %d, %s, %d Endpoints\n",
                        intfNumber, nameForClass(intfClass), numEndpoints));
                break;
            case 0x05: //Endpoint Descriptor
                int endpointAddr = ((buffer[index+2] & 0xFF));
                //Number is lower 4 bits
                int endpointNum = (endpointAddr & 0x0F);
                //Direction is high bit
                int direction = (endpointAddr & 0x80);

                int endpointAttrs = (buffer[index+3] & 0xFF);
                //Type is the lower two bits
                int endpointType = (endpointAttrs & 0x3);

                sb.append(String.format("-- Endpoint %d, %s %s\n",
                        endpointNum,
                        nameForEndpointType(endpointType),
                        nameForDirection(direction) ));
                break;
            }
            //Advance to next descriptor
            index += len;
        }

        return sb.toString();
    }

    private void updateDeviceList() {
        HashMap<String, UsbDevice> connectedDevices = mUsbManager
                .getDeviceList();
        if (connectedDevices.isEmpty()) {
            mDevice = null;
            mDeviceText.setText("No Devices Currently Connected");
            mConnectButton.setEnabled(false);
        } else {
            StringBuilder builder = new StringBuilder();
            for (UsbDevice device : connectedDevices.values()) {
                //Use the last device detected (if multiple) to open
                mDevice = device;
                builder.append(readDevice(device));
                builder.append("\n\n");
            }
            mDeviceText.setText(builder.toString());
            mConnectButton.setEnabled(true);
        }
    }

    /*
     * Enumerate the endpoints and interfaces on the connected device.
     * We do not need permission to do anything here, it is all "publicly available"
     * until we try to connect to an actual device.
     */
    private String readDevice(UsbDevice device) {
        StringBuilder sb = new StringBuilder();
        sb.append("Device Name: " + device.getDeviceName() + "\n");
        sb.append(String.format(
                "Device Class: %s -> Subclass: 0x%02x -> Protocol: 0x%02x\n",
                nameForClass(device.getDeviceClass()),
                device.getDeviceSubclass(), device.getDeviceProtocol()));

        for (int i = 0; i < device.getInterfaceCount(); i++) {
            UsbInterface intf = device.getInterface(i);
            sb.append(String
                    .format("+--Interface %d Class: %s -> Subclass: 0x%02x -> Protocol: 0x%02x\n",
                            intf.getId(),
                            nameForClass(intf.getInterfaceClass()),
                            intf.getInterfaceSubclass(),
                            intf.getInterfaceProtocol()));

            for (int j = 0; j < intf.getEndpointCount(); j++) {
                UsbEndpoint endpoint = intf.getEndpoint(j);
                sb.append(String.format("  +---Endpoint %d: %s %s\n",
                        endpoint.getEndpointNumber(),
                        nameForEndpointType(endpoint.getType()),
                        nameForDirection(endpoint.getDirection())));
            }
        }

        return sb.toString();
    }

    /* Helper Methods to Provide Readable Names for USB Constants */

    private String nameForClass(int classType) {
        switch (classType) {
        case UsbConstants.USB_CLASS_APP_SPEC:
            return String.format("Application Specific 0x%02x", classType);
        case UsbConstants.USB_CLASS_AUDIO:
            return "Audio";
        case UsbConstants.USB_CLASS_CDC_DATA:
            return "CDC Control";
        case UsbConstants.USB_CLASS_COMM:
            return "Communications";
        case UsbConstants.USB_CLASS_CONTENT_SEC:
            return "Content Security";
        case UsbConstants.USB_CLASS_CSCID:
            return "Content Smart Card";
        case UsbConstants.USB_CLASS_HID:
            return "Human Interface Device";
        case UsbConstants.USB_CLASS_HUB:
            return "Hub";
        case UsbConstants.USB_CLASS_MASS_STORAGE:
            return "Mass Storage";
        case UsbConstants.USB_CLASS_MISC:
            return "Wireless Miscellaneous";
        case UsbConstants.USB_CLASS_PER_INTERFACE:
            return "(Defined Per Interface)";
        case UsbConstants.USB_CLASS_PHYSICA:
            return "Physical";
        case UsbConstants.USB_CLASS_PRINTER:
            return "Printer";
        case UsbConstants.USB_CLASS_STILL_IMAGE:
            return "Still Image";
        case UsbConstants.USB_CLASS_VENDOR_SPEC:
            return String.format("Vendor Specific 0x%02x", classType);
        case UsbConstants.USB_CLASS_VIDEO:
            return "Video";
        case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
            return "Wireless Controller";
        default:
            return String.format("0x%02x", classType);
        }
    }

    private String nameForEndpointType(int type) {
        switch (type) {
        case UsbConstants.USB_ENDPOINT_XFER_BULK:
            return "Bulk";
        case UsbConstants.USB_ENDPOINT_XFER_CONTROL:
            return "Control";
        case UsbConstants.USB_ENDPOINT_XFER_INT:
            return "Interrupt";
        case UsbConstants.USB_ENDPOINT_XFER_ISOC:
            return "Isochronous";
        default:
            return "Unknown Type";
        }
    }

    private String nameForDirection(int direction) {
        switch (direction) {
        case UsbConstants.USB_DIR_IN:
            return "IN";
        case UsbConstants.USB_DIR_OUT:
            return "OUT";
        default:
            return "Unknown Direction";
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Receive Alarm Intent

Intent (147/474)
« Previous

Receive Alarm Intent

Description

The following code shows how to Receive Alarm Intent.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.alarms"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="3" />

    <application android:icon="@drawable/icon"
                 android:label="app_name">
        <activity android:name=".AlarmActivity"
                  android:label="Test">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".AlarmReceiver"></receiver>

    </application>
</manifest>

res\layout\main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/start"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Alarm"
  />
  <Button
    android:id="@+id/stop"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Cancel Alarm"
  />
</LinearLayout>

AlarmActivity.java

/*from   w w w . j a v  a2  s.co  m*/
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast;

public class AlarmActivity extends Activity implements View.OnClickListener {

    private PendingIntent mAlarmIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);

        Intent launchIntent = new Intent(this, AlarmReceiver.class);
        mAlarmIntent = PendingIntent.getBroadcast(this, 0, launchIntent, 0);
    }

    @Override
    public void onClick(View v) {
        AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        long interval = 5*1000; //5 seconds

        switch(v.getId()) {
        case R.id.start:
            Toast.makeText(this, "Scheduled", Toast.LENGTH_SHORT).show();
            manager.setRepeating(AlarmManager.ELAPSED_REALTIME,
                    SystemClock.elapsedRealtime()+interval,
                    interval,
                    mAlarmIntent);
            break;
        case R.id.stop:
            Toast.makeText(this, "Canceled", Toast.LENGTH_SHORT).show();
            manager.cancel(mAlarmIntent);
            break;
        default:
            break;
        }
    }

    private long nextStartTime() {
        long oneDay = 24*3600*1000; //24 hours
        Calendar startTime = Calendar.getInstance();
        startTime.set(Calendar.HOUR_OF_DAY, 9);
        startTime.set(Calendar.MINUTE, 0);
        startTime.set(Calendar.SECOND, 0);

        Calendar now = Calendar.getInstance();

        if(now.before(startTime)) {
            //It's not 9AM yet
            return startTime.getTimeInMillis();
        } else {
            //Return 9AM tomorrow
            startTime.add(Calendar.DATE, 1);
            return startTime.getTimeInMillis();
        }
    }
}

AlarmReceiver.java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/* w  ww .j ava 2s.  c om*/
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar now = Calendar.getInstance();
        DateFormat formatter = SimpleDateFormat.getTimeInstance();
        Toast.makeText(context, formatter.format(now.getTime()), Toast.LENGTH_SHORT).show();
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Receive SMS Messages

SMS (216/474)
« Previous

Receive SMS Messages

Description

You can receive incoming SMS messages by using a BroadcastReceiver object.

The following code shows how to Receive SMS Messages.

Example

Add the following statements in bold to the AndroidManifest.xml file:

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

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SMSActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".SMSReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

Java code

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
/*  w w  w  .j a  va  2 s.c o m*/
public class SMSReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent){
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "SMS from ";
        if (bundle != null){
          Object[] pdus = (Object[]) bundle.get("pdus");
          msgs = new SmsMessage[pdus.length];
          for (int i=0; i<msgs.length; i++){
              msgs[i] = SmsMessage.createFromPdu((byte [])pdus[i]);
              if (i==0) {
                  str += msgs[i].getOriginatingAddress();
                  str += ": ";
              }
              str += msgs[i].getMessageBody().toString();
          }
          Toast.makeText (context, str, Toast.LENGTH_SHORT).show();
          Log.d("SMSReceiver", str);
      }
  }
}

Note

Using the DDMS, send a message to the emulator. Your application should be able to receive the message and display it using the Toast class.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Record audio

Media (170/474)
« Previous

Record audio

Description

The following code shows how to Record audio.

Example

Register permission in manifest xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/startButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Recording"
  />
  <Button
    android:id="@+id/stopButton"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Recording"
    android:enabled="false"
  />
</LinearLayout>

Main activity Java code

package com.java2s.myapplication3.app;
//from  w w w . j  a v a2s  . com
import java.io.File;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    private MediaRecorder recorder;
    private Button start, stop;
    File path;

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

        start = (Button)findViewById(R.id.startButton);
        start.setOnClickListener(startListener);
        stop = (Button)findViewById(R.id.stopButton);
        stop.setOnClickListener(stopListener);

        recorder = new MediaRecorder();
        path = new File(Environment.getExternalStorageDirectory(),"myRecording.3gp");

        resetRecorder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        recorder.release();
    }

    private void resetRecorder() {
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        recorder.setOutputFile(path.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private View.OnClickListener startListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                recorder.start();

                start.setEnabled(false);
                stop.setEnabled(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private View.OnClickListener stopListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            recorder.stop();
            resetRecorder();

            start.setEnabled(true);
            stop.setEnabled(false);
        }
    };
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Redraw Canvas by calling invalidate method

Canvas (260/474)
« Previous

Redraw Canvas by calling invalidate method

Description

The following code shows how to Redraw Canvas by calling invalidate method.

Example

Main Activity Java code

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
/*from   w  ww  .j ava2s .co  m*/
import java.util.Random;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(new CanvasView(this));
   }

   class CanvasView extends View {
      Paint paint;
      Random random = new Random();

      public CanvasView(Context context) {
         super(context);
      }

      @Override
      protected void onDraw(Canvas canvas) {
         canvas.drawRGB(0, 0, 0);
         for (int i = 0; i < 10; i++) {
            paint = new Paint();
            paint.setARGB(random.nextInt(256), random.nextInt(256), random.nextInt(256), random.nextInt(256));
            canvas.drawLine(random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
                     random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), paint);
            canvas.drawCircle(random.nextInt(canvas.getWidth() - 30), random.nextInt(canvas.getHeight() - 30),
                     random.nextInt(30), paint);
            canvas.drawRect(random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()),
                     random.nextInt(canvas.getWidth()), random.nextInt(canvas.getHeight()), paint);
         }
         invalidate();
      }
   }
}
Redraw Canvas by calling invalidate method

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Reference color resource in TextView

TextView (423/474)
« Previous

Reference color resource in TextView

Description

The following code shows how to Reference color resource in TextView

Example

res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="background_color">#aa0000</color>
</resources>

Layout xml

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

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background_color"
    android:gravity="center"
    android:text="Hello World, MainActivity!" />
Reference color resource in TextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Request window feature

UI Basics (225/474)
« Previous

Request window feature

Description

The following code shows how to Request window feature.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Toggle Mode"
        android:onClick="onToggleClick" />
</RelativeLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
//from w w w . j  a v a 2  s .  c  o m
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_LEFT_ICON);
//        requestWindowFeature(Window.FEATURE_RIGHT_ICON);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        requestWindowFeature(Window.FEATURE_ACTION_BAR);

        setContentView(new TextView(this));

//        setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_launcher);
//        setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.ic_launcher);
        setProgress(7500);
        setProgressBarIndeterminateVisibility(true);
        setProgressBarVisibility(true);
    }
}
Request window feature

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - /res folder and subdirectories

Resources (14/474)
« Previous

/res folder and subdirectories

Description

Resource files are stored in various subdirectories based on their type under /res folder.

Folder

Here are some important subdirectories in the /res folder and the types of resources they host:

  • anim: Compiled animation files
  • drawable: Bitmaps
  • layout: UI and view definitions
  • values: Arrays, colors, dimensions, strings, and styles
  • xml: Compiled arbitrary XML files
  • raw: Noncompiled raw files

Note

The resource compiler in the Android Asset Packaging Tool (AAPT) compiles all the resources except the raw resources and places them into the final .apk file.
apk stands for Android package.

This .apk file, which contains the Android application's code and resources, correlates to Java's .jar file.

The .apk file is what gets installed onto the device.

Naming

XML resource parser allows resource names such as hello-string, but you will see a compile-time error in R.java. You can fix this by renaming your resource hello_string.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resize and Reposition

Activity (61/474)
« Previous

Resize and Reposition

Description

An easier way to customize the UI based on screen orientation is to create a separate res/layout folder containing the XML files for the UI of each orientation.

To support landscape mode, you can create a new folder in the res folder and name it as layout-land (representing landscape).

The main.xml file contained within the layout folder defines the UI for the activity in portrait mode, whereas the main.xml file in the layout-land folder defines the UI in landscape mode.

Example

The following code shows the content of main.xml under the layout folder:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   xmlns:android="http://schemas.android.com/apk/res/android">
   <Button
       android:id="@+id/button1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Top Left"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true" />
   <Button
       android:id="@+id/button2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Top Right"
       android:layout_alignParentTop="true"
       android:layout_alignParentRight="true" />
   <Button
       android:id="@+id/button3"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Bottom Left"
       android:layout_alignParentLeft="true"
       android:layout_alignParentBottom="true" />
   <Button
       android:id="@+id/button4"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Bottom Right"
       android:layout_alignParentRight="true"
       android:layout_alignParentBottom="true" />
   <Button
       android:id="@+id/button5"
       android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Middle"
          android:layout_centerVertical="true"
          android:layout_centerHorizontal="true" />
</RelativeLayout>

The following shows the content of main.xml under the layout-land folder:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Right"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true" />
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true" />
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Right"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />
    <Button
        android:id="@+id/button5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Middle"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <Button
        android:id="@+id/button6"
        android:layout_width="180px"
      android:layout_height="wrap_content"
      android:text="Top Middle"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true"
      android:layout_alignParentTop="true" />
  <Button
      android:id="@+id/button7"
      android:layout_width="180px"
      android:layout_height="wrap_content"
      android:text="Bottom Middle"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true"
      android:layout_alignParentBottom="true" />
</RelativeLayout>
Resize and Reposition

When the orientation of the device changes, Android automatically loads the appropriate XML file for your activity depending on the current screen orientation.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resolve Intent Filter Collision

Intent (129/474)
« Previous

Resolve Intent Filter Collision

Description

The <intent-filter> element defines how your activity can be invoked by another activity.

What happens if another activity in either the same or a separate application has the same filter name?

Example

For example, suppose your application has another activity named Activity3, with the following entry in the AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.app" >
/*from   ww  w .ja va2  s. c om*/
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.app.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:label="Second Activity"
            android:name=".SecondActivity" >
            <intent-filter >
                <action android:name="com.java2s.SecondActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
        android:label="Third Activity"
        android:name=".ThirdActivity" >
        <intent-filter >
            <action android:name="com.java2s.SecondActivity" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    </application>

</manifest>

If you call the startActivity() method with the following intent, then the Android OS will display a selection of activities:

startActivity(new Intent("com.java2s.SecondActivity"));

If you check the "Use by default for this action" item and then select an activity, then the next time the intent "com.java2s.SecondActivity" is called again, it will launch the previous activity that you have selected.

Clear

To clear this default,

  • go to the Settings application in Android
  • select Apps -> Manage applications,
  • select the application name.
  • When the details of the application are shown, scroll down to the bottom and click the Clear defaults button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resource configuration qualifiers

Resources (19/474)
« Previous

Resource configuration qualifiers

Description

Most of the available configuration qualifiers are listed as follows. New qualifiers may be added with newer APIs.

  • car, desk: Type of docking.
  • en-rUS: Language and region.
  • keysexposed, keyssoft, keyshidden: Kind of keyboard.
  • ldpi, mdpi, hdpi, xhdpi, nodpi, tvdpi: Screen density.
  • long, notlong: Screen type.
  • mccAAA: AAA is the mobile country code.
  • mncAAA: AAA is the carrier/network code.
  • navexposed, navhidden: Navigation keys hidden or exposed.
  • night, notnight: Night or day.
  • nokeys, qwerty, 12key: Number of keys.
  • nonav, dpad, trackball, wheel: Type of navigation device.
  • notouch, stylus, finger: Kind of screen.
  • port, land: Portrait or landscape.
  • small, normal, large, xlarge: Screen size.
  • sw<N>dp, w<N>dp, h<N>dp: Smallest width, available width, available height.
  • v3, v4, v7: API level.

Example

With qualifiers, you can have resource directories shown in the following code.

\res\layout-mcc312-mnc222-en-rUS
\res\layout-ldpi
\res\layout-hdpi
\res\layout-car

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resource Reference name and package

Resources (17/474)
« Previous

Resource Reference name and package

Description

The name part in the resource reference @[package:]type/name is the name given to the resource.

Example

For example, text1 in the following layout file, it also gets represented as an int constant in R.java.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
 <Button
    android:id="@+id/b1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
   />
</LinearLayout>

Note

If you don't specify any package in the syntax @[package:]type/name, the pair type/name is resolved based on local resources and the application's local R.java package.

If you specify android:type/name, the reference is resolved using the package android and specifically through the android.R.java file.

You can use any Java package name in place of the package placeholder to locate the correct R.java file to resolve the reference.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resource Reference Type

Resources (16/474)
« Previous

Resource Reference Type

Description

Regardless of the type of resource, all Android resources are identified by their IDs in Java source code.

The syntax for ID in the XML file is called resource-reference syntax.

Syntax

This resource reference has the following formal structure:

@[package:]type/name

The type corresponds to one of the resource-type namespaces available in R.java.

Map between R.java and resource type

The following R static fields

  • R.drawable
  • R.id
  • R.layout
  • R.string
  • R.attr
  • R.plural
  • R.array

are corresponding the following types in XML resource-reference syntax.

  • drawable
  • id
  • layout
  • string
  • attr
  • plurals
  • string-array

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resources and Configuration

Resources (18/474)
« Previous

Resources and Configuration

Description

Android resources generalize configuration idea to any configuration of the device. Language is one configuration choice.

Android allows you to pick different sets of layouts based on layout mode for the same resource ID.

Android does this by using different directories for each configuration.

Example

When using the smart phone we can use it vertically or horizontally. The vertical mode is called the portrait mode and the horizontal mode the landscape mode.

The following three main_layout.xml files are all for layout. Android will load the corresponding files.

\res\layout\main_layout.xml
\res\layout-port\main_layout.xml
\res\layout-land\main_layout.xml

Note

Even though there are three separate layout files here, they all generate only one layout ID in R.java.

This ID looks as follows:

R.layout.main_layout

When you retrieve the layout corresponding to this layout ID, you get the appropriate layout suitable for that device layout.

The directory extensions -port and -land are called configuration qualifiers.

These qualifiers are case insensitive and separated from the resource directory name with a hyphen (-).

Resources in these configuration qualifier directories are called alternate resources.

The resources in resource directories without the configuration qualifiers are called default resources.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Resources Directory Structure

Resources (15/474)
« Previous

Resources Directory Structure

Description

The following code offers a quick look at the overall resources directory structure.

/res/values/strings.xml
/res/values/colors.xml
/res/values/dimens.xml
/res/values/attrs.xml
/res/values/styles.xml
/res/drawable/*.png *.jpg *.gif *.9.png
/res/anim/*.xml
/res/layout/*.xml
/res/raw/*.*
/res/xml/*.xml
/assets/*.*/*.*

Note

Only the /assets directory can contain an arbitrary list of subdirectories. Every other directory can only have files at the level of that directory.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Return Results from an Intent

Intent (130/474)
« Previous

Return Results from an Intent

Description

The startActivity() method invokes another activity but does not return a result to the current activity.

To pass data back from an activity, you should instead use the startActivityForResult() method.

Example

Set up the manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.app" >
/*  w ww. j  a  v a 2 s  . c  om*/
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.app.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:label="Second Activity"
            android:name=".SecondActivity" >
            <intent-filter >
                <action android:name="com.java2s.SecondActivity" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Add the following statements in bold to SecondActivity.java

package com.java2s.app;
//w  w w . j av  a  2 s. com
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class SecondActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("Second");

        Toast.makeText(this, getIntent().getStringExtra("str1"), Toast.LENGTH_SHORT).show();

        Toast.makeText (this,Integer.toString(
                        getIntent().getIntExtra("age1", 0)),
                Toast.LENGTH_SHORT).show();

        Bundle bundle = getIntent().getExtras();

        Toast.makeText (this, bundle.getString("str2"),
                Toast.LENGTH_SHORT).show();

        Toast.makeText (this,Integer.toString(bundle.getInt("age2")),
                Toast.LENGTH_SHORT).show();
    }

    public void onClick(View view) {
        Intent i = new Intent();
        i.putExtra("age3", 45);

        i.setData(Uri.parse("Something passed back to main activity"));

        setResult(RESULT_OK, i);

        finish();
    }

}

Add the following statements to the MainActivity.java file

package com.java2s.app;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
//from   www. ja  va 2 s.  c  om
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("Open");
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent("com.java2s.SecondActivity");
                i.putExtra("str1", "This is a string");
                i.putExtra("age1", 25);

                Bundle extras = new Bundle();
                extras.putString("str2", "This is another string");
                extras.putInt("age2", 35);

                i.putExtras(extras);

                startActivityForResult(i, 1);

            }
        });

        setContentView(parentContainer);
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Toast.makeText (this, Integer.toString(
                            data.getIntExtra("age3", 0)),
                    Toast.LENGTH_SHORT).show();
            Toast.makeText (this, data.getData().toString(),
                    Toast.LENGTH_SHORT).show();
        }
    }

}
Return Results from an Intent

Note

To call an activity and wait for a result to be returned from it, you need to use the startActivityForResult() method, like this:

startActivityForResult(new Intent("com.java2s.SecondActivity"),request_Code);

If the request code is set to -1, then calling it using the startActivityForResult() method is equivalent to calling it using the startActivity() method. No result will be returned.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save And Load User Preferences

Preference (191/474)
« Previous

Save And Load User Preferences

Description

Android provides the SharedPreferences object to help you save simple application data.

Using the SharedPreferences object, you save the data you want through the use of name/value pairs.

In the following code, you learn how to use the SharedPreferences object to store application data.

Example

Create a file at res/xml/myapppreferences.xml and populate the myapppreferences.xml file as follows:

         <?xml version="1.0" encoding="utf-8"?>
         <PreferenceScreen
             xmlns:android="http://schemas.android.com/apk/res/android">
             <PreferenceCategory android:title="Category 1">
                 <CheckBoxPreference
                     android:title="Checkbox"
                     android:defaultValue="false"
                     android:summary="True or False"
                     android:key="checkboxPref" />
                 </PreferenceCategory>
             <PreferenceCategory android:title="Category 2">
                 <EditTextPreference
                     android:summary="Enter a string"
                     android:defaultValue="[Enter a string here]"
                     android:title="Edit Text"
                     android:key="editTextPref" />
                 <RingtonePreference
                     android:summary="Select a ringtone"
                     android:title="Ringtones"
                     android:key="ringtonePref" />
                 <PreferenceScreen
                     android:title="Second Preference Screen"
                  android:summary= "Click here to go to the second Preference Screen"
                  android:key="secondPrefScreenPref" >
                  <EditTextPreference
                      android:summary="Enter a string"
                      android:title="Edit Text (second Screen)"
                      android:key="secondEditTextPref" />
              </PreferenceScreen>
          </PreferenceCategory>
      </PreferenceScreen>

Java code

import android.os.Bundle;
import android.preference.PreferenceActivity;
//from w  ww . j  ava  2 s  .c  o m
public class AppPreferenceActivity extends PreferenceActivity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         //load the preferences from an XML file
         addPreferencesFromResource(R.xml.myapppreferences);
     }
}

Note

Once you have modified the value of at least one of the preferences, a file is created in the /data/data/com.java2s.your activity name/shared_prefs folder of the Android emulator.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save data on pause and read back on resume for Activity

Activity (57/474)
« Previous

Save data on pause and read back on resume for Activity

Description

The following code shows how to Save data on pause and read back on resume for Activity.

Example

Layout 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">
  <Button android:id="@+id/close"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Close" />
  <EditText
    android:id="@+id/editor"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:singleLine="false"
    />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
//from   w  w w  . ja v  a  2s  .co  m
public class MainActivity extends Activity {
  private final static String NOTES="notes.txt";
  private EditText editor;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    editor=(EditText)findViewById(R.id.editor);

    Button btn=(Button)findViewById(R.id.close);

    btn.setOnClickListener(new Button.OnClickListener() {
      public void onClick(View v) {
        finish();
      }
    });
  }

  public void onResume() {
    super.onResume();

    try {
      InputStream in=openFileInput(NOTES);

      if (in!=null) {
        InputStreamReader tmp=new InputStreamReader(in);
        BufferedReader reader=new BufferedReader(tmp);
        String str;
        StringBuffer buf=new StringBuffer();

        while ((str = reader.readLine()) != null) {
          buf.append(str+"\n");
        }

        in.close();
        editor.setText(buf.toString());
      }
    }
    catch (java.io.FileNotFoundException e) {
      // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
      Toast
        .makeText(this, "Exception: "+t.toString(), 2000)
        .show();
    }
  }

  public void onPause() {
    super.onPause();

    try {
      OutputStreamWriter out=
          new OutputStreamWriter(openFileOutput(NOTES, 0));

      out.write(editor.getText().toString());
      out.close();
    }
    catch (Throwable t) {
      Toast
        .makeText(this, "Exception: "+t.toString(), 2000)
        .show();
    }
  }
}/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Save data on pause and read back on resume for Activity

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save Media content

Media (171/474)
« Previous

Save Media content

Description

The following code shows how to Save Media content.

Example

Register Media content

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.mediastore"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4"
        android:targetSdkVersion="19" />

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

</manifest>

Main layout xml file

<?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" >
    <Button
        android:id="@+id/imageButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Images" />
    <Button
        android:id="@+id/videoButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Video" />
    <Button
        android:id="@+id/textButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Text Document" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/*from  ww  w  .j  a  v a 2  s  .c om*/
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class MainActivity extends Activity implements View.OnClickListener {

    private static final int REQUEST_CAPTURE = 100;
    private static final int REQUEST_DOCUMENT = 101;

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

        Button images = (Button) findViewById(R.id.imageButton);
        images.setOnClickListener(this);
        Button videos = (Button) findViewById(R.id.videoButton);
        videos.setOnClickListener(this);
        Button text = (Button) findViewById(R.id.textButton);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            text.setOnClickListener(this);
        } else {
            text.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CAPTURE && resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "All Done!", Toast.LENGTH_SHORT).show();
        }
        if (requestCode == REQUEST_DOCUMENT && resultCode == Activity.RESULT_OK) {
            Uri document = data.getData();
            writeDocument(document);
        }
    }

    private void writeDocument(Uri document) {
        try {
            ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(document, "w");
            FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
            StringBuilder sb = new StringBuilder();
            sb.append("Last Written at: ");
            sb.append(DateFormat.getLongDateFormat(this).format(new Date()));

            out.write(sb.toString().getBytes());
            out.flush();
            out.close();
            pfd.close();
        } catch (Exception e) {
            Log.w("Android", e);
        }
    }

    @Override
    public void onClick(View v) {
        ContentValues values;
        Intent intent;
        Uri storeLocation;
        final long nowMillis = System.currentTimeMillis();

        switch(v.getId()) {
        case R.id.imageButton:
            values = new ContentValues(5);
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, nowMillis);
            values.put(MediaStore.Images.ImageColumns.DATE_ADDED, nowMillis / 1000);
            values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, nowMillis / 1000);
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, "Test Image Sample");
            values.put(MediaStore.Images.ImageColumns.TITLE, "Test Image Sample");

            storeLocation = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, storeLocation);
            startActivityForResult(intent, REQUEST_CAPTURE);
            return;
        case R.id.videoButton:
            values = new ContentValues(7);
            values.put(MediaStore.Video.VideoColumns.DATE_TAKEN, nowMillis);
            values.put(MediaStore.Video.VideoColumns.DATE_ADDED, nowMillis / 1000);
            values.put(MediaStore.Video.VideoColumns.DATE_MODIFIED, nowMillis / 1000);
            values.put(MediaStore.Video.VideoColumns.DISPLAY_NAME, "Test Video Sample");
            values.put(MediaStore.Video.VideoColumns.TITLE, "Test Video Sample");
            values.put(MediaStore.Video.VideoColumns.ARTIST, "Yours Truly");
            values.put(MediaStore.Video.VideoColumns.DESCRIPTION, "Sample Video Clip");

            storeLocation = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
            intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, storeLocation);
            startActivityForResult(intent, REQUEST_CAPTURE);
            return;
        case R.id.textButton:
            intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);

            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TITLE, "Test");
            startActivityForResult(intent, REQUEST_DOCUMENT);
        default:
            return;
        }
    }
}
Save Media content

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save State during orientation change

Activity (65/474)
« Previous

Save State during orientation change

Description

The following code shows how to Save State during orientation change.

Example

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

res/layout-land/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

Java code

//  w w w .j ava2s . c  om
/* Copyright (c) 2008-2009 -- CommonsWare, LLC

   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.
*/

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class MainActivity extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;

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

    Button btn=(Button)findViewById(R.id.pick);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                    Uri.parse("content://contacts/people"));

        startActivityForResult(i, PICK_REQUEST);
      }
    });

    viewButton=(Button)findViewById(R.id.view);

    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });

    restoreMe(savedInstanceState);

    viewButton.setEnabled(contact!=null);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (contact!=null) {
      outState.putString("contact", contact.toString());
    }
  }

  private void restoreMe(Bundle state) {
    contact=null;

    if (state!=null) {
      String contactUri=state.getString("contact");

      if (contactUri!=null) {
        contact=Uri.parse(contactUri);
      }
    }
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save State Information during Changes in Configuration

Activity (58/474)
« Previous

Save State Information during Changes in Configuration

Description

When an activity is killed, it will fire one or both of the following two methods:

  • onPause() is always fired whenever an activity is killed or pushed into the background.
  • onSaveInstanceState() is also fired whenever an activity is about to be killed or put into the background. onSaveInstanceState() method is not fired when an activity is being unloaded from the stack, because there is no need to restore its state later.

To preserve the state of an activity, you could always implement the onPause() method.

To preserve the state of an activity so that it can be restored later when the activity is recreated, a much simpler way is to implement the onSaveInstanceState() method, as it provides a Bundle object as an argument so that you can use it to save your activity's state.

Example

The following code shows that you can save the string ID into the Bundle object during the onSaveInstanceState() method:

@Override//ww w .ja  v  a2 s .c  o  m
public void onSaveInstanceState(Bundle outState) {
    //save whatever you need to persist
    outState.putString("ID", "1234567890");
    super.onSaveInstanceState(outState);
}

When an activity is recreated, the onCreate() method is first called, followed by the onRestoreInstanceState() method.

@ Override// w  w w  . ja v a  2s  . c o m
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    //retrieve the information persisted earlier
    String ID = savedInstanceState.getString("ID");
}

Bundle object only support basic data types.

Example 2

onRetainNonConfigurationInstance() method is fired when an activity is about to be destroyed due to a configuration change.

You can save your current data by returning it in this method, like this:

@Override//from www  .  j  av  a2s.co m
public Object onRetainNonConfigurationInstance() {
    //save whatever you want here; it takes in an Object type
    return ("Some text to preserve");
}

This method returns an Object type, which allows you to return nearly any data type.

To extract the saved data, you can extract it in the onCreate() method, using the getLastNonConfigurationInstance() method:

@Override/* ww w.j  a  va2s.c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.d("StateInfo", "onCreate");
    String str = (String) getLastNonConfigurationInstance();
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save to External Storage (SD Card)

Resources (47/474)
« Previous

Save to External Storage (SD Card)

Description

The following code shows how to Save to External Storage (SD Card).

Example

Main layout file

<?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:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Please enter some text" />

 <EditText
     android:id="@+id/txtText1"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

 <Button
     android:id="@+id/btnSave"
     android:text="Save"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:onClick="onClickSave" />

 <Button
     android:id="@+id/btnLoad"
     android:text="Load"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:onClick="onClickLoad" />

</LinearLayout>

MainActivity.java file

package com.java2s.myapplication3.app;
//from  www  .  ja  v  a2  s.c  o m
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText textBox;
    static final int READ_BLOCK_SIZE = 100;

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

        textBox = (EditText) findViewById(R.id.txtText1);
    }

    public void onClickSave(View view) {
        String str = textBox.getText().toString();
        try
        {
            FileOutputStream fOut =
                    openFileOutput("textfile.txt",
                            MODE_WORLD_READABLE);
            OutputStreamWriter osw = new
                    OutputStreamWriter(fOut);
            osw.write(str);
            osw.flush();
            osw.close();
            Toast.makeText (getBaseContext(),
                    "File saved successfully!",
                    Toast.LENGTH_SHORT).show();
            textBox.setText("");
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
    }
    public void onClickLoad(View view) {
        try{
            FileInputStream fIn =
                    openFileInput("textfile.txt");
            InputStreamReader isr = new
                    InputStreamReader(fIn);

            char [] inputBuffer = new char [READ_BLOCK_SIZE];
            String s = "";

            int charRead;
            while ((charRead = isr.read(inputBuffer))>0)
            {
                String readString =
                        String.copyValueOf(inputBuffer, 0,
                                charRead);
                s += readString;

                inputBuffer = new char [READ_BLOCK_SIZE];
            }
            textBox.setText(s);
            Toast.makeText (getBaseContext(),
                    "File loaded successfully!",
                    Toast.LENGTH_SHORT).show();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Save to Internal Storage

Resources (46/474)
« Previous

Save to Internal Storage

Description

The following code shows how to save files to Internal Storage.

Example

Main layout file

<?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:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Please enter some text" />

 <EditText
     android:id="@+id/txtText1"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

 <Button
     android:id="@+id/btnSave"
     android:text="Save"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:onClick="onClickSave" />

 <Button
     android:id="@+id/btnLoad"
     android:text="Load"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:onClick="onClickLoad" />

</LinearLayout>

MainActivity.java file

package com.java2s.myapplication3.app;
/*from  w  ww. ja  v a2 s  . c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class MainActivity extends Activity {
    EditText textBox;
    static final int READ_BLOCK_SIZE = 100;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textBox = (EditText) findViewById(R.id.txtText1);
    }

    public void onClickSave(View view) {
        String str = textBox.getText().toString();
        try {
            //SD Card Storage
            File sdCard = Environment.getExternalStorageDirectory();
            File directory = new File(sdCard.getAbsolutePath() +
                    "/MyFiles");
            directory.mkdirs();
            File file = new File(directory, "textfile.txt");
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter osw = new
                    OutputStreamWriter(fOut);
            osw.write(str);
            osw.flush();
            osw.close();

            Toast.makeText(getBaseContext(),
                    "File saved successfully!",
                    Toast.LENGTH_SHORT).show();
            textBox.setText("");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

Note

The preceding code uses the getExternalStorageDirectory() method to return the full path to the external storage.

Typically, it should return the "/sdcard" path for a real device, and "/mnt/ sdcard" for an Android emulator.

You should never try to hardcode the path to the SD card, as manufacturers may choose to assign a different path name to the SD card.

Note 2

In order to write to the external storage, you need to add the WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml file:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".FilesActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - screen densities

Layout (338/474)
« Previous

screen densities

Description

Android defines and recognizes four screen densities:

  • Low density (ldpi) - 120 dpi
  • Medium density (mdpi) - 160 dpi
  • High density (hdpi) - 240 dpi
  • Extra High density (xhdpi) - 320 dpi

Example

The screen of the Nexus S has a 4-inch screen diagonally, with a screen width of 2.04 inches.

Its resolution is 480 (width) 800 (height) pixels. With 480 pixels spread across a width of 2.04 inches, the result is a pixel density of about 235 dots per inch (dpi).

The Nexus S is regarded as a hdpi device, as its pixel density is closest to 240 dpi.

Note

Using the dp unit ensures that your views are always displayed in the right proportion regardless of the screen density.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - ScrollView

View (459/474)
« Previous

ScrollView

Description

A ScrollView is a special type of FrameLayout which support scrolling through a list of views that occupy more space than the physical display.

The ScrollView can contain only one child view or ViewGroup, which normally is a LinearLayout.

Do not use a ListView together with the ScrollView.

Example

The following main.xml content shows a ScrollView containing a LinearLayout, which in turn contains some Button and EditText views:

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <Button
            android:id="@+id/button1"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="Button 1" />
          <Button
              android:id="@+id/button2"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="Button 2" />
          <Button
              android:id="@+id/button3"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="Button 3" />
          <EditText
              android:id="@+id/txt"
              android:layout_width="fill_parent"
              android:layout_height="600dp" />
          <Button
              android:id="@+id/button4"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="Button 4" />
          <Button
              android:id="@+id/button5"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="Button 5" />
      </LinearLayout>
</ScrollView>

Note

Because the EditText automatically gets the focus, it fills up the entire activity.

To prevent it from getting the focus, add the following two attributes to the <LinearLayout> element:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true" >

You will now be able to view the buttons and scroll through the list of views.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Select a RadioButton

RadioButton (414/474)
« Previous

Select a RadioButton

Description

The radio buttons within the radio group are, by default, unchecked. You can set one to checked in the XML definition.

To set one of the radio buttons to the checked state programmatically, you can obtain a reference to the radio button and call setChecked():

RadioButton steakBtn = (RadioButton)this.findViewById(R.id.stkRBtn); steakBtn.setChecked(true);

You can also use the toggle() method to toggle the state of the radio button.

XML Example

Select a RadioButton in XML.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//from   w w  w  .j ava 2 s . c  om
    <RadioGroup
        android:id="@+id/rBtnGrp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/chRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Chicken" />

        <RadioButton
            android:id="@+id/fishRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Fish" />

        <RadioButton
            android:id="@+id/stkRBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Steak" />

    </RadioGroup>

</LinearLayout>

Java Example

Select a RadioButton in Java code.

package com.java2s.app;
/*w  w w  .java2s. com*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RadioButton steakBtn = (RadioButton) this.findViewById(R.id.stkRBtn);
        steakBtn.setChecked(true);
    }

}
Select a RadioButton

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Select multiple items in the ListView

ListView (377/474)
« Previous

Select multiple items in the ListView

Description

You can allow multiple items in the ListView to be selected.

Example

/*  www. j  a v a2  s .c o m*/
package com.java2s.myapplication3.app;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity  {
    String[] presidents = {
            "XML",
            "HTML",
            "CSS",
            "Java",
            "Javascript"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListView lstView = getListView();
        //lstView.setChoiceMode(ListView.CHOICE_MODE_NONE);
        //lstView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, presidents));
    }

    public void onListItemClick(
            ListView parent, View v, int position, long id)
    {
        Toast.makeText (this,
                "You have selected " + presidents [position],
                Toast.LENGTH_SHORT).show();
    }

}
Select multiple items in the ListView

Note

To programmatically get a reference to the ListView object, you use the getListView() method, which fetches the ListActivity's list view.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Send E-Mail

Intent (140/474)
« Previous

Send E-Mail

Description

You can also send e-mail messages programmatically from within your Android application.

The following code shows how to Send E-Mail.

Example

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

<Button
    android:id="@+id/btnSendEmail"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Email"
    android:onClick="onClick" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*w ww.ja  v a2  s .co m*/
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View v) {
        String[] to = {"XML@example.com",
                       "HTML@example.com"};
        String[] cc = {"CSS@example.com"};
        sendEmail(to, cc, "Hello", "Hello my friends!");
    }

    private void sendEmail(String[] emailAddresses, String[] carbonCopies,
                           String subject, String message)
    {
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        String[] to = emailAddresses;
        String[] cc = carbonCopies;
        emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
        emailIntent.putExtra(Intent.EXTRA_CC, cc);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        emailIntent.putExtra(Intent.EXTRA_TEXT, message);
        emailIntent.setType("message/rfc822");
        startActivity(Intent.createChooser(emailIntent, "Email"));
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Send out email

Intent (141/474)
« Previous

Send out email

Description

The following code shows how to send out email.

Example

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:onClick="sendFeedback"
        android:text="Send Feedback" />

</RelativeLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning/*from  w ww  .  ja v a  2  s.  c  o m*/
 * See the file license.txt for copying permission.
 ******************************************************************************/

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.content.Context;
import android.content.Intent;

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

public class MainActivity extends Activity {

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

  public void sendFeedback(View v) {
    LaunchEmailUtil.launchEmailToIntent(this);
  }
}

class EnvironmentInfoUtil {

  public static String getApplicationInfo(Context context) {
    return String.format("%s\n%s\n%s\n%s\n%s\n%s\n",
        getCountry(context), getBrandInfo(), getModelInfo(),
        getDeviceInfo(), getVersionInfo(context), getLocale(context));
  }

  public static String getCountry(Context context) {
    TelephonyManager mTelephonyMgr = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
    return String.format("Country: %s",
        mTelephonyMgr.getNetworkCountryIso());
  }

  public static String getModelInfo() {
    return String.format("Model: %s", Build.MODEL);
  }

  public static String getBrandInfo() {
    return String.format("Brand: %s", Build.BRAND);
  }

  public static String getDeviceInfo() {
    return String.format("Device: %s", Build.DEVICE);
  }

  public static String getLocale(Context context) {
    return String.format("Locale: %s", context.getResources()
        .getConfiguration().locale.getDisplayName());
  }

  public static String getVersionInfo(Context context) {
    String version = null;

    try {
      PackageInfo info = context.getPackageManager().getPackageInfo(
          context.getPackageName(), 0);
      version = info.versionName + " (release " + info.versionCode
          + ")";
    } catch (NameNotFoundException e) {
      version = "not_found";
    }

    return String.format("Version: %s", version);
  }
}
class LaunchEmailUtil {

  public static void launchEmailToIntent(Context context) {
    Intent msg = new Intent(Intent.ACTION_SEND);

    StringBuilder body = new StringBuilder("\n\n----------\n");
    body.append(EnvironmentInfoUtil.getApplicationInfo(context));

    msg.putExtra(Intent.EXTRA_EMAIL,"feed@back.com".split(", "));
    msg.putExtra(Intent.EXTRA_SUBJECT,"feedback_subject");
    msg.putExtra(Intent.EXTRA_TEXT, body.toString());

    msg.setType("message/rfc822");
    context.startActivity(Intent.createChooser(msg,"send email"));
  }
}
Send out email

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Send SMS Messages Programmatically

SMS (213/474)
« Previous

Send SMS Messages Programmatically

Description

The following code shows how to Send SMS Messages Programmatically.

Example

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

<Button
    android:id="@+id/btnSendSMS"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send SMS"
    android:onClick="onClick" />

</LinearLayout>

Java code

//from   w w  w .  ja v  a 2  s. c o m
package com.java2s.myapplication3.app;

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

import android.telephony.SmsManager;
import android.view.View;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View v) {
        sendSMS("5556", "Hello my friends!");
    }

    //sends an SMS message to another device
    private void sendSMS(String phoneNumber, String message)
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }
}

In the AndroidManifest.xml file, add the following statements:

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

    <uses-sdk android:minSdkVersion="14" />
 <uses-permission android:name="android.permission.SEND_SMS"/>

 <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
     <activity
         android:label="@string/app_name"
         android:name=".SMSActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
 </application>

</manifest>

How to run

On the first Android emulator (5554), click the Send SMS button to send an SMS message to the second emulator (5556).

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Send SMS Messages Using Intent

SMS (214/474)
« Previous

Send SMS Messages Using Intent

Description

To invoke the built-in Messaging application and let it do all the work of sending the message. you can use an Intent object together with the MIME type "vnd.android-dir/mms-sms".

The following code shows how to Send SMS Messages Using Intent.

Example

Intent i = new Intent(android.content.Intent.ACTION_VIEW);
i.putExtra("address", "5556; 5558; 5560");
//  www .  j  a  v  a  2  s .c o m
i.putExtra("sms_body", "Hello my friends!");
i.setType("vnd.android-dir/mms-sms");
startActivity(i);

Note

You can send your SMS to multiple recipients by simply separating each phone number with a semi-colon in the putExtra() method.

The numbers will be separated using commas in the Messaging application.

If using this method to invoke the Messaging application, there is no need to declare SEND_SMS permission in AndroidManifest.xml.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set activity to no title bar and full screen

Activity (71/474)
« Previous

Set activity to no title bar and full screen

Description

We can Set activity to no title bar and full screen in manifest xml file.

Example

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

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

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Set activity to no title bar and full screen

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set hint text for EditText

EditText (294/474)
« Previous

Set hint text for EditText

Description

You can specify hint text for EditText. This text will be displayed slightly faded and disappears as soon as the user starts to type text.

The purpose of the hint is to let the user know what is expected in this field, without the user having to select and erase default text.

In XML, this attribute is

android:hint="your hint text here"

or

android:hint="@string/your_hint_name"

where your_hint_name is a resource name of a string to be found in /res/values/strings.xml.

In code, you would call the setHint() method with either a CharSequence or a resource ID.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
/* w w  w. j  a  va2s  .c om*/
    <EditText
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="your hint text here" />

</LinearLayout>

Java code

package com.java2s.app;
/*from www . j  a  v a2 s  . c  om*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}
Set hint text for EditText

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set ImageView adjustViewBounds to true

ImageView (327/474)
« Previous

Set ImageView adjustViewBounds to true

Description

The following code shows how to Set ImageView adjustViewBounds to true.

Example

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/icon"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:adjustViewBounds="true"
    android:src="@drawable/myImageFileName"
    />//w  w  w .  j av  a2s  .com

Java code.

import android.app.Activity;
import android.os.Bundle;
/*from   w w w. j  a v  a2  s.c o  m*/
public class ImageViewDemo extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
      super.onCreate(icicle);
      setContentView(R.layout.main);
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set input method option with imeOptions

EditText (297/474)
« Previous

Set input method option with imeOptions

Description

The following code shows how to Set input method option with imeOptions.

Example

Main layout activity_main.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
  <EditText
    android:id="@+id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:imeOptions="actionSearch"
  />
  <EditText
    android:id="@+id/text2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:imeOptions="actionGo"
  />
</LinearLayout>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w ww  .j a va 2 s.c o  m*/
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Set input method option with imeOptions

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set layout weight, gravity and background

Layout (342/474)
« Previous

Set layout weight, gravity and background

Description

The following code shows how to Set layout weight, gravity and background.

Example

<?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:background="#ffEEee"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="1" >

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="Click Me" />

</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
// www  .j av  a2  s.co m
public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }
}
Set layout weight, gravity and background

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set one view to the right of another view

Layout (363/474)
« Previous

Set one view to the right of another view

Description

The following code shows how to Set one view to the right of another view.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/text_view_1"
        android:layout_width="150px"
        android:layout_height="100px"
        android:background="@android:color/darker_gray"
        />
    <TextView android:id="@+id/one"
        android:layout_width="150px"
        android:layout_height="100px"
        android:layout_toRightOf="@id/text_view_1"
        android:layout_centerVertical="true"
        android:background="@android:color/white"
        />
</RelativeLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
// ww w . ja  va  2 s .  c  om
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set system UI to full screen

UI Basics (227/474)
« Previous

Set system UI to full screen

Description

The following code shows how to Set system UI to full screen.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Toggle Mode"
        android:onClick="onToggleClick" />
</RelativeLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
//from  w  ww.j  av  a2 s .co  m
public class MainActivity extends Activity {

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

    }

    public void onToggleClick(View v) {
        v.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }
}
Set system UI to full screen

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set system UI to low profile

UI Basics (228/474)
« Previous

Set system UI to low profile

Description

The following code shows how to Set system UI to low profile.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Toggle Mode"
        android:onClick="onToggleClick" />
</RelativeLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
/*w  w w. j av a2s .c  om*/
public class MainActivity extends Activity {

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

    public void onToggleClick(View v) {
        int currentVis = v.getSystemUiVisibility();
        int newVis;
        if ((currentVis & View.SYSTEM_UI_FLAG_LOW_PROFILE) == View.SYSTEM_UI_FLAG_LOW_PROFILE) {
            newVis = View.SYSTEM_UI_FLAG_VISIBLE;
        } else {
            newVis = View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        v.setSystemUiVisibility(newVis);
    }
}
Set system UI to low profile

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set System UI Visibility

UI Basics (226/474)
« Previous

Set System UI Visibility

Description

The following code shows how to Set System UI Visibility.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Toggle Mode"
        android:onClick="onToggleClick" />
</RelativeLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
//www.  ja  v  a  2s  .c o  m
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onToggleClick(View v) {
        v.setSystemUiVisibility(
                /* This flag tells Android not to shift
                 * our layout when resizing the window to
                 * hide/show the system elements
                 */
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                /* This flag hides the system status bar.
                 */
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                /* This flag hides the on-screen controls
                 */
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                /* This flag tells the controls to stay hidden until
                 * the user brings them back explicitly with a gesture,
                 * and hide them again after a period.
                 */
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}
Set System UI Visibility

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set target SDK version

Hello Android (6/474)
« Previous

Set target SDK version

Description

We can set target SDK version in manifest xml file.

Example

<manifest ...

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note

The code above sets the target SDK version by using the <uses-sdk> tag as follows.

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set text for TextView in XML

TextView (424/474)
« Previous

Set text for TextView in XML

Description

The following example shows how to Set text for TextView in XML.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >// ww  w . j a  v a 2  s  . c o m
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Example from java2s.com"
        />
</LinearLayout>

Java code

package com.java2s.app;
//  www.  j av a 2 s  .  com
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Set text for TextView in XML

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set text to EditText

EditText (287/474)
« Previous

Set text to EditText

Description

The following code shows how to Set text to EditText.

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//from  w w w. jav  a  2s  . c  om
    <EditText xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/field"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:singleLine="false"
        />

</LinearLayout>

Java code.

package com.java2s.app;
//from  ww w . j a  va2  s.  co  m
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_main);
        EditText fld=(EditText)findViewById(R.id.field);
        fld.setText("java2s.com");
    }
}
Set text to EditText

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set the minSdkVersion

Hello Android (7/474)
« Previous

Set the minSdkVersion

Description

In the manifest file we can Set the minSdkVersion.

Example

<?xml version="1.0" encoding="utf-8"?>
<manifest ...
    android:versionCode="1"
    android:versionName="1.0" >

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

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

</manifest>

Note

The code above sets the minSdkVersion by using the <uses-sdk> tag as follows:

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

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set Threshold for AutoCompleteTextView

TextView (435/474)
« Previous

Set Threshold for AutoCompleteTextView

Description

Threshold defines the number of characters that the user must type before completion suggestions are displayed in a drop down menu.

Example

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Name of President" />

<AutoCompleteTextView android:id="@+id/txtCountries"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*from   w  w w  .ja va 2s  .  c  o  m*/
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity {
    String[] presidents = {
            "Dwight D. Eisenhower",
            "John F. Kennedy",
            "Lyndon B. Johnson",
            "Richard Nixon",
            "Gerald Ford",
            "Jimmy Carter",
            "Ronald Reagan",
            "George H. W. Bush",
            "Bill Clinton",
            "George W. Bush",
            "Barack Obama"
    };

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

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, presidents);

        AutoCompleteTextView textView = (AutoCompleteTextView)
                findViewById(R.id.txtCountries);

        textView.setThreshold(3);
        textView.setAdapter(adapter);
    }
}
Set Threshold for AutoCompleteTextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set TimePicker to 24 Hour View

Clock Date Picker (272/474)
« Previous

Set TimePicker to 24 Hour View

Description

The following code shows how to Set TimePicker to 24 Hour View.

Example

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

<TimePicker android:id="@+id/timePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

   <Button android:id="@+id/btnSet"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="I am all set!"
       android:onClick="onClick" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*from  w w w.  ja v  a2 s  .c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
    TimePicker timePicker;

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

        timePicker = (TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
    }

    public void onClick(View view) {
        Toast.makeText (getBaseContext(),
                "Time selected:" +
                        timePicker.getCurrentHour() +
                        ":" + timePicker.getCurrentMinute(),
                Toast.LENGTH_SHORT).show();
    }

}
Set TimePicker to 24 Hour View

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set ttf font for TextView

TextView (431/474)
« Previous

Set ttf font for TextView

Description

The following code shows how to Set ttf font for TextView.

Example

<?xml version="1.0" encoding="utf-8"?>
<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:stretchColumns="1">
  <TableRow>
    <TextView
      android:text="sans:"
      android:layout_marginRight="4px"
      android:textSize="20sp"
    />
    <TextView
      android:id="@+id/sans"
      android:text="Hello, world!"
      android:typeface="sans"
      android:textSize="20sp"
    />
  </TableRow>
  <TableRow>
    <TextView
      android:text="serif:"
      android:layout_marginRight="4px"
      android:textSize="20sp"
    />
    <TextView
      android:id="@+id/serif"
      android:text="Hello, world!"
      android:typeface="serif"
      android:textSize="20sp"
    />
  </TableRow>
  <TableRow>
    <TextView
      android:text="monospace:"
      android:layout_marginRight="4px"
      android:textSize="20sp"
    />
    <TextView
      android:id="@+id/monospace"
      android:text="Hello, world!"
      android:typeface="monospace"
      android:textSize="20sp"
    />
  </TableRow>
  <TableRow>
    <TextView
      android:text="Custom:"
      android:layout_marginRight="4px"
      android:textSize="20sp"
    />
    <TextView
      android:id="@+id/custom"
      android:text="Hello, world!"
      android:textSize="20sp"
    />
  </TableRow>
</TableLayout>

Java code

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
/* w ww.  j  a  v  a 2s  . c  o  m*/
public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    TextView tv=(TextView)findViewById(R.id.custom);
    Typeface face=Typeface.createFromAsset(getAssets(),"fonts/yourfont file.ttf");

    tv.setTypeface(face);
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set up click handler in XML for CheckBox

CheckBox (266/474)
« Previous

Set up click handler in XML for CheckBox

Description

We can use xml attribute to specify click event handler for a CheckBox.

The following code shows the XML for a Button where you specify an attribute for the handler, plus the Java code that is the click handler.

<CheckBox   ...
          android:onClick="myClickHandler"
          ...  />

Java code to handle the click event.

public void myClickHandler(View target) {
    switch(target.getId()) {
       case R.id.button1:
       ...

The handler method will be called with target set to the View object representing the button that was clicked.

The switch statement in the click handler method uses the resource IDs of the buttons to select the logic to run.

In this way you won't have to explicitly create each Button object in your code, and you can reuse the same method across multiple buttons.

Example

<?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" >
/*from w  w w . j  av a  2s.  c o m*/
    <CheckBox android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myClickHandler"
        />
</LinearLayout>

Java code

package com.java2s.app;
/*from www. j a v a2  s  .c om*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

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

    }
    public void myClickHandler(View view) {
        if(view.getId() == R.id.imageButton2) {
            Log.v("CheckBoxActivity", "The steak checkbox is now ");
        }
    }
}
Set up click handler in XML for CheckBox

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Set up GLSurfaceView for OpenGL

OpenGL (401/474)
« Previous

Set up GLSurfaceView for OpenGL

Description

The following code shows how to Set up GLSurfaceView.

Example

Main Activity Java code

package com.java2s.myapplication4.app;
//  w  w  w  . ja v a2 s  .  c  o m
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {

    private GLSurfaceView glView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        glView = new GLSurfaceView(this);
        glView.setRenderer(new MyOpenGLRenderer());
        setContentView(glView);
    }

    class MyOpenGLRenderer implements Renderer {

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            Log.d("MyOpenGLRenderer", "Surface changed. Width=" + width + " Height=" + height);
        }

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            Log.d("MyOpenGLRenderer", "Surface created");
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            gl.glClearColor(0.0f, 0.5f, 0.0f, 1f);
            gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        }
    }
}
Set up GLSurfaceView for OpenGL

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Setup view for orientation change

Activity (66/474)
« Previous

Setup view for orientation change

Description

The following code show how to Setup view for orientation change.

Example

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

res/layout-land/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

Java code

/* Copyright (c) 2008-2009 -- CommonsWare, LLC
//from  ww w  . ja  v a  2s  .c  om
   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.
*/

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class MainActivity extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setupViews();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }

  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    setupViews();
  }

  private void setupViews() {
    setContentView(R.layout.main);

    Button btn=(Button)findViewById(R.id.pick);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                    Uri.parse("content://contacts/people"));

        startActivityForResult(i, PICK_REQUEST);
      }
    });

    viewButton=(Button)findViewById(R.id.view);

    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });

    viewButton.setEnabled(contact!=null);
  }
}
Setup view for orientation change

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Show Toast in four different corners

Toast (448/474)
« Previous

Show Toast in four different corners

Description

The following code shows how to Show Toast in four different corners.

Example

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

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:onClick="upperLeft"
        android:text="show toast" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:onClick="upperRight"
        android:text="show toast" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:onClick="bottomLeft"
        android:text="show toast" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:onClick="bottomRight"
        android:text="show toast" />

</RelativeLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;
/*from   w  w w .j a v a2s.  com*/
public class MainActivity extends Activity {

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

  public void upperLeft(View v) {
    Toast toast = Toast.makeText(this, "Upper Left!",
        Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
    toast.show();
  }

  public void upperRight(View v) {
    Toast toast = Toast.makeText(this, "Upper Right!",
        Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
    toast.show();
  }

  public void bottomLeft(View v) {
    Toast toast = Toast.makeText(this, "Bottom Left!",
        Toast.LENGTH_SHORT);

    toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, 0, 0);
    toast.show();
  }

  public void bottomRight(View v) {
    Toast toast = Toast.makeText(this, "Bottom Right!",
        Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
    toast.show();
  }
}
Show Toast in four different corners

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Show your home location on Map

Map (387/474)
« Previous

Show your home location on Map

Description

The following example shows how to Show your home location on Map.

Example

//from www .  jav a2s  .c om
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Please enter your home address."
        />
    <EditText
        android:id="@+id/address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:autoText="true"
        />
    <Button
        android:id="@+id/launchmap"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Map"
        />
</LinearLayout>

Java code

package com.java2s.app;
//from ww w.j a  va 2s.c  o m
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final AlertDialog.Builder adb = new AlertDialog.Builder(this);

        final EditText addressfield = (EditText) findViewById(R.id.address);

        final Button button = (Button) findViewById(R.id.launchmap);
        button.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View v) {
                try {
                    // Perform action on click
                    String address = addressfield.getText().toString();
                    address = address.replace(' ', '+');
                    Intent geoIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + address));
                    startActivity(geoIntent);
                } catch (Exception e) {
                    AlertDialog ad = adb.create();
                    ad.setMessage("Failed to Launch");
                    ad.show();
                }
            }
        });
    }
}
Show your home location on Map

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - SMS reciver

SMS (217/474)
« Previous

SMS reciver

Description

The following code shows how to create a SMS reciver.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication4.app">

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.java2s.myapplication4.app.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>
        <receiver
            android:name="com.java2s.myapplication4.app.SmsReceiver"
            android:exported="true">
            <intent-filter android:priority="5">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Main layout xml file

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

\res\menu\main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>

Main Activity Java code

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
// w ww . jav a  2s  . c  o m
public class MainActivity extends Activity {
    private static final String SHORTCODE = "55443";
    private static final String ACTION_SENT =
            "com.java2s.myapplication4.app.SENT";
    private static final String ACTION_DELIVERED =
            "com.java2s.myapplication4.app.DELIVERED";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Button sendButton = new Button(this);
        sendButton.setText("Hail the Mothership");
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendSMS("Beam us up!");
            }
        });

        setContentView(sendButton);
    }

    private void sendSMS(String message) {
        PendingIntent sIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_SENT), 0);
        PendingIntent dIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_DELIVERED), 0);
        registerReceiver(sent, new IntentFilter(ACTION_SENT));
        registerReceiver(delivered,new IntentFilter(ACTION_DELIVERED));
        SmsManager manager = SmsManager.getDefault();
        manager.sendTextMessage(SHORTCODE, null, message,sIntent, dIntent);
    }
    private BroadcastReceiver sent = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
            case SmsManager.RESULT_ERROR_NO_SERVICE:
            case SmsManager.RESULT_ERROR_NULL_PDU:
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                break;
            }

            unregisterReceiver(this);
        }
    };

    private BroadcastReceiver delivered = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                break;
            case Activity.RESULT_CANCELED:
                break;
            }

            unregisterReceiver(this);
        }
    };
}

SmsReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
/*www.ja  v a 2  s. c o m*/
public class SmsReceiver extends BroadcastReceiver {
    private static final String SHORTCODE = "55443";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();

        Object[] messages = (Object[])bundle.get("pdus");
        SmsMessage[] sms = new SmsMessage[messages.length];
        for(int n=0; n < messages.length; n++) {
            sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
        }
        for(SmsMessage msg : sms) {
            if(TextUtils.equals(msg.getOriginatingAddress(), SHORTCODE)) {
                abortBroadcast();
                Toast.makeText(context,
                        "Received message from the mothership: "
                        + msg.getMessageBody(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Sorting

Content Provider (106/474)
« Previous

Sorting

Description

The last parameter of the managedQuery() method and constructor for the CursorLoader class enables you to specify a SQL ORDER BY clause to sort the result of the query.

Example

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

<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:stackFromBottom="false"
    android:transcriptMode="normal" />

<TextView
    android:id="@+id/contactName"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/contactID"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*ww  w. j a  va 2 s.com*/
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

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

        Uri allContacts = Uri.parse("content://contacts/people");

        Cursor c;
        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            c = managedQuery(allContacts, null,
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                    new String[]{"%Lee"},
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC");
        } else {
            //Honeycomb and later
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    null,
                    ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?",
                    new String[]{"%Lee"},
                    ContactsContract.Contacts.DISPLAY_NAME + " ASC");
            c = cursorLoader.loadInBackground();
        }

        String[] columns = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID};

        int[] views = new int[]{R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter;

        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views);
        } else {
            //Honeycomb and later
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        }

        this.setListAdapter(adapter);
    }
}

Add the following statements to the AndroidManifest.xml file:

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

     <uses-sdk android:minSdkVersion="14" />
     <uses-permission android:name="android.permission.READ_CONTACTS"/>

     <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name" >
       <activity
           android:label="@string/app_name"
           android:name=".ProviderActivity" >
           <intent-filter >
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Speech recognize

Media (172/474)
« Previous

Speech recognize

Description

The following code shows how to do Speech recognize.

Example

package com.java2s.myapplication3.app;
//from   w  w w . ja  v  a 2s .com
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity {

    private static final int REQUEST_RECOGNIZE = 100;

    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        setContentView(tv);

        Intent intent = new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                "Tell Me Your Name");
        try {
            startActivityForResult(intent, REQUEST_RECOGNIZE);
        } catch (ActivityNotFoundException e) {
            showDownloadDialog();
        }
    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                this);
        builder.setTitle("Not Available");
        builder.setMessage("No recognition application installed."
                + "  Would you like to download one?");
        builder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                        marketIntent.setData(Uri.parse("market://details?id=com.google.android.voicesearch"));
                    }
                }
        );
        builder.setNegativeButton("No", null);
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode,
                                    int resultCode, Intent data) {
        if (requestCode == REQUEST_RECOGNIZE && resultCode == Activity.RESULT_OK) {
            ArrayList<String> matches = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            StringBuilder sb = new StringBuilder();
            for (String piece : matches) {
                sb.append(piece);
                sb.append('\n');
            }
            tv.setText(sb.toString());
        } else {
            Toast.makeText(this, "Operation Canceled",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Start activity vs start activity for result

Activity (76/474)
« Previous

Start activity vs start activity for result

Description

The following code shows the difference between Start activity and start activity for result.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

Java code

//ww w .  j a  v a  2 s.  c  o  m
/* Copyright (c) 2008-2009 -- CommonsWare, LLC

   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.
*/

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class MainActivity extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Button btn=(Button)findViewById(R.id.pick);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                    Uri.parse("content://contacts/people"));

        startActivityForResult(i, PICK_REQUEST);
      }
    });

    viewButton=(Button)findViewById(R.id.view);

    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });

    viewButton.setEnabled(contact!=null);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Start Intent for web search

Intent (142/474)
« Previous

Start Intent for web search

Description

The following code shows how to Start Intent for web search.

Example

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
//from  ww w.  ja va 2s .com
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout parentContainer = new LinearLayout(this);

        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("OK");
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                intent.setData(Uri.parse("http://www.google.com"));
                startActivity(intent);
            }
        });

        setContentView(parentContainer);

    }
}
Start Intent for web search

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Stop the AsyncTask

Thread (443/474)
« Previous

Stop the AsyncTask

Description

The following code shows how to Stop the AsyncTask.

Example

Main layout xml file

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="hello" />

<Button
    android:id="@+id/btnStartCounter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    android:onClick="startCounter" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication4.app;
/* ww w.j  a v  a 2 s. c  o  m*/
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    static TextView txtView1;

    DoCountingTask task;

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

        txtView1 = (TextView) findViewById(R.id.textView1);
    }

    public void startCounter(View view) {
        task = (DoCountingTask) new DoCountingTask().execute();
    }

    public void stopCounter(View view) {
        task.cancel(true);
    }

    private class DoCountingTask extends AsyncTask<Void, Integer, Void> {
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < 1000; i++) {
                publishProgress(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.d ("Threading", e.getLocalizedMessage());
                }
                if (isCancelled()) break;
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            txtView1.setText(progress[0].toString());
            Log.d ("Threading", "updating...");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopCounter(txtView1);
    }

}

The preceding code will update the UI safely from another thread.

Note

To stop the AsyncTask subclass, you need to get an instance of it first and call its cancel() method.

Within the task, you call the isCancelled() method to check whether the task should be terminated.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - String Arrays

Resources (29/474)
« Previous

String Arrays

Description

You can specify an array of strings as a resource in any file under the /res/values subdirectory.

Example

You can use an XML node called string-array. This node is a child node of resources.

The following code shows an example of an array in a resource file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
      <string name="hello">hello</string>
      <string name="app_name">hello appname</string>
      <string-array name="test_array">
                 <item>one</item>
                 <item>two</item>
                 <item>three</item>
      </string-array>
</resources>

Once you have this string-array resource definition, you can retrieve this array in the Java code as follows.

// w w  w  . j  a v a 2 s  .  com
//Get access to Resources object from an Activity
Resources res = your_Activity.getResources();
String strings[] = res.getStringArray(R.array.test_array);

//Print strings
for (String s: strings)
{
    Log.d("example", s);
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - String Resources

Resources (22/474)
« Previous

String Resources

Description

Android allows you to define strings in one or more XML resource files.

These XML files reside in the /res/values subdirectory.

You can name the XML files the way you like, although you commonly see the file name as strings.xml.

Example

The following code shows an example of a string-resource file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="hello">hello</string>
   <string name="app_name">hello appname</string>
</resources>

Note

When this file is created or updated, the Eclipse ADT plug-in automatically creates or updates a Java class in your application's root package called R.java with unique IDs for the two string resources specified.

Regardless of the number of resource files, there is only one R.java file.

The generated IDs in R.java point to ints rather than strings.

Most methods that take strings also take these resource identifiers as inputs. Android resolves those ints to strings where necessary.

Android takes any number of arbitrary files as long as the structure of the XML file looks like the xml above and the files reside in the /res/values subdirectory.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - TableLayout with two TableRow

Layout (353/474)
« Previous

TableLayout with two TableRow

Description

The following code shows how to create a TableLayout with two table rows.

Example

Layout xml

/*w w  w  .java  2s . c  o  m*/
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:stretchColumns="1">
  <TableRow>
    <TextView
        android:text="URL:" />
    <EditText android:id="@+id/entry"
      android:layout_span="3"/>
  </TableRow>
  <View
    android:layout_height="2px"
    android:background="#0000FF" />
  <TableRow>
    <Button android:id="@+id/cancel"
      android:layout_column="2"
      android:text="Cancel" />
    <Button android:id="@+id/ok"
      android:text="OK" />
  </TableRow>
</TableLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
//from ww w  .  j av a  2 s  .  com
public class TableLayoutDemo extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
  }
}
TableLayout with two TableRow

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Take a picture

Intent (143/474)
« Previous

Take a picture

Description

The following code shows how to Take a picture.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
  android:id="@+id/main_text_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click the button below to take a picture"
  android:textSize="30dip"
    />
<Button
  android:id="@+id/camera_button"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Take a picture"
  android:textSize="30dip"/>
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
//from  www.jav a  2  s .c  o m
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.provider.MediaStore;

import android.view.View.OnClickListener;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;

/*

Written by Martin Dinstuhl
mdinstuhl@gmail.com

I put this together in order to help other Android developers
who might be having the same problem I've
had for the past few days.  Please let me know if you have any questions.

*/

public class MainActivity extends Activity
{

  final int PICTURE_ACTIVITY = 1;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    final Button cameraButton = (Button)findViewById(R.id.camera_button);
    cameraButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v){
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, PICTURE_ACTIVITY);
      }
    });
    }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    AlertDialog msgDialog;
    if (resultCode == RESULT_CANCELED) { // The user didn't like the photo.  ;_;
        msgDialog = createAlertDialog("Q_Q", "", "OK!  I'LL TRY AGAIN!");
    } else {
      msgDialog = createAlertDialog("ZOMG!", "CRAP!", "I KNOW RITE??!?");
    }
    msgDialog.show();
  }

  private AlertDialog createAlertDialog(String title, String msg, String buttonText){
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    AlertDialog msgDialog = dialogBuilder.create();
    msgDialog.setTitle(title);
    msgDialog.setMessage(msg);
    msgDialog.setButton(buttonText, new DialogInterface.OnClickListener(){
      @Override
      public void onClick(DialogInterface dialog, int idx){
        return; // Nothing to see here...
      }
    });

    return msgDialog;
  }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Take a picture and preview

Camera (82/474)
« Previous

Take a picture and preview

Description

The following code shows how to Take a picture and preview.

Example

Register permission for camera.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <SurfaceView
    android:id="@+id/preview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
  <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="100dip"
    android:layout_alignParentBottom="true"
    android:gravity="center_vertical"
    android:background="#A000">
    <Button
      android:layout_width="100dip"
      android:layout_height="wrap_content"
      android:text="Cancel"
      android:onClick="onCancelClick"
    />
    <Button
      android:layout_width="100dip"
      android:layout_height="wrap_content"
      android:layout_alignParentRight="true"
      android:text="Snap Photo"
      android:onClick="onSnapClick"
    />
  </RelativeLayout>
</RelativeLayout>

Main activity Java code

package com.java2s.myapplication3.app;
//from  w w  w .  java2  s . com
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity implements SurfaceHolder.Callback, Camera.ShutterCallback, Camera.PictureCallback {

    Camera mCamera;
    SurfaceView mPreview;

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

        mPreview = (SurfaceView)findViewById(R.id.preview);
        mPreview.getHolder().addCallback(this);
        mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mCamera = Camera.open();
    }

    @Override
    public void onPause() {
        super.onPause();
        mCamera.stopPreview();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCamera.release();
        Log.d("CAMERA","Destroy");
    }

    public void onCancelClick(View v) {
        finish();
    }

    public void onSnapClick(View v) {
        mCamera.takePicture(this, null, null, this);
    }
    @Override
    public void onShutter() {
        Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        try {
            FileOutputStream out = openFileOutput("picture.jpg", Activity.MODE_PRIVATE);
            out.write(data);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Must restart preview
        camera.startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Camera.Parameters params = mCamera.getParameters();
        List<Camera.Size> sizes = params.getSupportedPreviewSizes();
        Camera.Size selected = sizes.get(0);
        params.setPreviewSize(selected.width,selected.height);
        mCamera.setParameters(params);

        mCamera.setDisplayOrientation(90);
        mCamera.startPreview();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera.setPreviewDisplay(mPreview.getHolder());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i("PREVIEW","surfaceDestroyed");
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Talk to a Socket Server

Network (185/474)
« Previous

Talk to a Socket Server

Description

The following code shows how to Talk to a Socket Server.

Example

Add the following line to the AndroidManifest.xml file:

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

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

    <application
        ...
    </application>

</manifest>

Main layout xml file

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

<EditText
    android:id="@+id/txtMessage"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Message"
    android:onClick="onClickSend"/>

<TextView
    android:id="@+id/txtMessagesReceived"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:scrollbars = "vertical" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication4.app;
/*  ww w  . ja va2 s .  com*/
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.util.Log;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    InetAddress serverAddress;
    Socket socket;

    static TextView txtMessagesReceived;
    EditText txtMessage;

    CommsThread commsThread;

    static Handler UIupdater = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int numOfBytesReceived = msg.arg1;
            byte [] buffer = (byte []) msg.obj;

            String strReceived = new String(buffer);

            strReceived = strReceived.substring(
                    0, numOfBytesReceived);

            txtMessagesReceived.setText(
                    txtMessagesReceived.getText().toString() +
                            strReceived);
        }
    };

    private class CreateCommThreadTask extends AsyncTask
            <Void, Integer, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                serverAddress =
                        InetAddress.getByName("192.168.1.101");
                socket = new Socket(serverAddress, 500);
                commsThread = new CommsThread(socket);
                commsThread.start();
                sendToServer("hi");
            } catch (UnknownHostException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }

    private class WriteToServerTask extends AsyncTask
            <byte [], Void, Void> {
        protected Void doInBackground(byte []...data) {
            commsThread.write(data[0]);
            return null;
        }
    }

    private class CloseSocketTask extends AsyncTask
            <Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                socket.close();
            } catch (IOException e) {
                Log.d("Sockets", e.getLocalizedMessage());
            }
            return null;
        }
    }

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

        txtMessage = (EditText) findViewById(R.id.txtMessage);
        txtMessagesReceived = (TextView)
                findViewById(R.id.txtMessagesReceived);
    }

    public void onClickSend(View view) {
        sendToServer(txtMessage.getText().toString());
    }

    private void sendToServer(String message) {
        byte [] theByteArray =
                message.getBytes();
        new WriteToServerTask().execute(theByteArray);
    }

    @Override
    public void onResume() {
        super.onResume();
        new CreateCommThreadTask().execute();
    }

    @Override
    public void onPause() {
        super.onPause();
        new CloseSocketTask().execute();
    }
}
class CommsThread extends Thread {
    private final Socket socket;
    private final InputStream inputStream;
    private final OutputStream outputStream;

    public CommsThread(Socket sock) {
        socket = sock;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.d("SocketChat", e.getLocalizedMessage());
        }
        inputStream = tmpIn;
        outputStream = tmpOut;
    }

    public void run() {
        byte [] buffer = new byte [1024];

        int bytes;

        while (true) {
            try {
                bytes = inputStream.read(buffer);

                MainActivity.UIupdater.obtainMessage(
                        0,bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(byte [] bytes) {
        try {
            outputStream.write(bytes);
        } catch (IOException e) { }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) { }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - TextView add links

TextView (425/474)
« Previous

TextView add links

Description

You can invoke the static addLinks() method of the Linkify class to find and add links to the content of any TextView or any Spannable on demand.

Linkify.addLinks(tv, Linkify.ALL);

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//w w  w.  j  a v a 2 s .  c o m
    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="abc@yourserver.com"
        android:autoLink="email" />

</LinearLayout>

Java code

package com.java2s.app;
//from   ww w  .java 2 s.  co m
import android.app.Activity;
import android.os.Bundle;
import android.text.util.Linkify;
import android.widget.TextView;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView nameValue = (TextView)findViewById(R.id.myText);
        Linkify.addLinks(nameValue, Linkify.ALL);
    }

}
TextView add links

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Track user gesture velocity

Gesture (317/474)
« Previous

Track user gesture velocity

Description

The following code shows how to Track user gesture velocity.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

/*from  w  w w.  j a v a2  s. c  o  m*/

package com.java2s.myapplication3.app;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.FrameLayout;
import android.widget.Scroller;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PanScrollView scrollView = new PanScrollView(this);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        for(int i=0; i < 5; i++) {
            ImageView iv = new ImageButton(this);
            iv.setImageResource(R.drawable.ic_launcher);
            layout.addView(iv, new LinearLayout.LayoutParams(1000, 500));
        }

        scrollView.addView(layout);
        setContentView(scrollView);
    }
}

class PanScrollView extends FrameLayout {

    // Fling components
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;

    /* Positions of the last motion event */
    private float mLastTouchX, mLastTouchY;
    /* Drag threshold */
    private int mTouchSlop;
    /* Fling Velocity */
    private int mMaximumVelocity, mMinimumVelocity;
    /* Drag Lock */
    private boolean mDragging = false;

    public PanScrollView(Context context) {
        super(context);
        init(context);
    }

    public PanScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PanScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mScroller = new Scroller(context);
        mVelocityTracker = VelocityTracker.obtain();
        // Get system constants for touch thresholds
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mMaximumVelocity = ViewConfiguration.get(context)
                .getScaledMaximumFlingVelocity();
        mMinimumVelocity = ViewConfiguration.get(context)
                .getScaledMinimumFlingVelocity();
    }

    /*
     * Override the measureChild... implementations to guarantee that the child
     * view gets measured to be as large as it wants to be. The default
     * implementation will force some children to be only as large as this view.
     */
    @Override
    protected void measureChild(View child, int parentWidthMeasureSpec,
                                int parentHeightMeasureSpec) {
        int childWidthMeasureSpec;
        int childHeightMeasureSpec;

        childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    @Override
    protected void measureChildWithMargins(View child,
                                           int parentWidthMeasureSpec, int widthUsed,
                                           int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child
                .getLayoutParams();

        final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            // This is called at drawing time by ViewGroup. We use
            // this method to keep the fling animation going through
            // to completion.
            int oldX = getScrollX();
            int oldY = getScrollY();
            int x = mScroller.getCurrX();
            int y = mScroller.getCurrY();

            if (getChildCount() > 0) {
                View child = getChildAt(0);
                x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(),
                        child.getWidth());
                y = clamp(y,
                        getHeight() - getPaddingBottom() - getPaddingTop(),
                        child.getHeight());
                if (x != oldX || y != oldY) {
                    scrollTo(x, y);
                }
            }

            // Keep on drawing until the animation has finished.
            postInvalidate();
        }
    }

    // Override scrollTo to do bounds checks on any scrolling request
    @Override
    public void scrollTo(int x, int y) {
        // we rely on the fact the View.scrollBy calls scrollTo.
        if (getChildCount() > 0) {
            View child = getChildAt(0);
            x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(),
                    child.getWidth());
            y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(),
                    child.getHeight());
            if (x != getScrollX() || y != getScrollY()) {
                super.scrollTo(x, y);
            }
        }
    }

    /*
     * Monitor touch events passed down to the children and intercept as soon as
     * it is determined we are dragging. This allows child views to still
     * receive touch events if they are interactive (i.e. Buttons)
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // Stop any flinging in progress
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                // Reset the velocity tracker
                mVelocityTracker.clear();
                mVelocityTracker.addMovement(event);
                // Save the initial touch point
                mLastTouchX = event.getX();
                mLastTouchY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                final float y = event.getY();
                final int yDiff = (int) Math.abs(y - mLastTouchY);
                final int xDiff = (int) Math.abs(x - mLastTouchX);
                // Verify that either difference is enough to be a drag
                if (yDiff > mTouchSlop || xDiff > mTouchSlop) {
                    mDragging = true;
                    mVelocityTracker.addMovement(event);
                    // Start capturing events ourselves
                    return true;
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mDragging = false;
                mVelocityTracker.clear();
                break;
        }

        return super.onInterceptTouchEvent(event);
    }

    /*
     * Feed all touch events we receive to the detector for processing.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mVelocityTracker.addMovement(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // We've already stored the initial point,
                // but if we got here a child view didn't capture
                // the event, so we need to.
                return true;
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                final float y = event.getY();
                float deltaY = mLastTouchY - y;
                float deltaX = mLastTouchX - x;
                // Check for slop on direct events
                if (!mDragging
                        && (Math.abs(deltaY) > mTouchSlop || Math.abs(deltaX) > mTouchSlop)) {
                    mDragging = true;
                }
                if (mDragging) {
                    // Scroll the view
                    scrollBy((int) deltaX, (int) deltaY);
                    // Update the last touch event
                    mLastTouchX = x;
                    mLastTouchY = y;
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                mDragging = false;
                // Stop any flinging in progress
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                break;
            case MotionEvent.ACTION_UP:
                mDragging = false;
                // Compute the current velocity and start a fling if it is above
                // the minimum threshold.
                mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                int velocityX = (int) mVelocityTracker.getXVelocity();
                int velocityY = (int) mVelocityTracker.getYVelocity();
                if (Math.abs(velocityX) > mMinimumVelocity
                        || Math.abs(velocityY) > mMinimumVelocity) {
                    fling(-velocityX, -velocityY);
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    /*
     * Utility method to initialize the Scroller and start redrawing
     */
    public void fling(int velocityX, int velocityY) {
        if (getChildCount() > 0) {
            int height = getHeight() - getPaddingBottom() - getPaddingTop();
            int width = getWidth() - getPaddingLeft() - getPaddingRight();
            int bottom = getChildAt(0).getHeight();
            int right = getChildAt(0).getWidth();

            mScroller.fling(getScrollX(), getScrollY(), velocityX, velocityY,
                    0, Math.max(0, right - width), 0,
                    Math.max(0, bottom - height));

            invalidate();
        }
    }

    /*
     * Utility method to assist in doing bounds checking
     */
    private int clamp(int n, int my, int child) {
        if (my >= child || n < 0) {
            /*
             * my >= child is this case: |--------------- me ---------------|
             * |------ child ------| or |--------------- me ---------------|
             * |------ child ------| or |--------------- me ---------------|
             * |------ child ------|
             *
             * n < 0 is this case: |------ me ------| |-------- child --------|
             * |-- mScrollX --|
             */
            return 0;
        }
        if ((my + n) > child) {
            /*
             * this case: |------ me ------| |------ child ------| |-- mScrollX
             * --|
             */
            return child - my;
        }
        return n;
    }
}
Track user gesture velocity

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Turn Activity to Dialog

Activity (77/474)
« Previous

Turn Activity to Dialog

Description

By default, an activity occupies the entire screen.

You can apply a dialog theme to an activity so that it is displayed as a floating dialog.

Example

To apply a dialog theme to an activity, simply modify the <Activity> element in the AndroidManifest.xml file by adding the android:theme attribute:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.app" >

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Turn Activity to Dialog

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Turn off soft input panel

Hello Android (8/474)
« Previous

Turn off soft input panel

Description

Get EditText to automatically have the focus, but you do not want the soft input panel (keyboard) to appear automatically which happens on a real device.

Example

To prevent the keyboard from appearing, add the following attribute to the <activity> element in the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateHidden"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note

The code above turns off the soft input panel by using the attribute in <activity> tag as follows.

        <activity
             ...
            android:windowSoftInputMode="stateHidden"
        >

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


UI Development in Android

Description

At the heart of the common controls in Android are two classes:

  • android.view.View
  • android.view.ViewGroup

The View class represents a general-purpose View object. The common controls in Android ultimately extend the View class.

ViewGroup is a view and it contains other views. ViewGroup is the base class for a list of layout classes.

Layout

Android uses the concept of layouts to manage how controls are laid out within a container view.

You can choose from several approaches to build UIs in Android.

  • You can construct UIs entirely in code.
  • You can also define UIs in XML.
  • You can even combine the two-define the UI in XML and then refer to it, and modify it, in code.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Units Of Measurement

Layout (336/474)
« Previous

Units Of Measurement

Description

When specifying the size of an element on an Android UI, you should know the following units of measurement:

dp

dp is Density-independent pixel.
1 dp is equivalent to one pixel on a 160 dpi screen.
This is the recommended unit of measurement when specifying the dimension of views. The 160 dpi screen is the baseline density assumed by Android. You can specify either "dp" or "dip" when referring to a density-independent pixel.

sp

sp is Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes.

pt

pt - Point.
A point is defined to be 1/72 of an inch, based on the physical screen size.

px

px - Pixel.
Corresponds to actual pixels on the screen. Using this unit is not recommended, as your UI may not render correctly on devices with a different screen resolution.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Update Button text when clicking

Button (245/474)
« Previous

Update Button text when clicking

Description

The following code shows how to update Button text when clicking.

Example

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;

public class MainActivity extends Activity implements View.OnClickListener {
  Button btn;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    btn = new Button(this);
    btn.setOnClickListener(this);
    updateTime();
    setContentView(btn);
  }

  public void onClick(View view) {
    updateTime();
  }

  private void updateTime() {
    btn.setText(new Date().toString());
  }
}
Update Button text when clicking

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Update Preferences

Preference (196/474)
« Previous

Update Preferences

Description

The following code shows how to Update Preferences.

Example

Register permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="com.java2s.myapplication3.app.READ_PREFERENCES" />
    <uses-permission android:name="com.java2s.myapplication3.app.WRITE_PREFERENCES" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:id="@+id/button_settings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Settings"
        android:onClick="onSettingsClick" />
    <CheckBox
        android:id="@+id/checkbox_enable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button_settings"
        android:text="Set Enable Setting"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">
        <TextView
            android:id="@+id/value_enabled"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/value_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/value_selection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>

Java code

package com.java2s.myapplication3.app;
// w ww  . j  a v  a2 s .c  o  m
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnCheckedChangeListener {

    public static final String SETTINGS_ACTION = "com.java2s.sharepreferences.ACTION_SETTINGS";
    public static final Uri SETTINGS_CONTENT_URI =
            Uri.parse("content://com.java2s.sharepreferences.settingsprovider/settings");
    public static class SettingsColumns {
        public static final String _ID = Settings.NameValueTable._ID;
        public static final String NAME = Settings.NameValueTable.NAME;
        public static final String VALUE = Settings.NameValueTable.VALUE;
    }

    TextView mEnabled, mName, mSelection;
    CheckBox mToggle;

    private ContentObserver mObserver = new ContentObserver(new Handler()) {
        public void onChange(boolean selfChange) {
            updatePreferences();
        }
    };

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

        mEnabled = (TextView) findViewById(R.id.value_enabled);
        mName = (TextView) findViewById(R.id.value_name);
        mSelection = (TextView) findViewById(R.id.value_selection);
        mToggle = (CheckBox) findViewById(R.id.checkbox_enable);
        mToggle.setOnCheckedChangeListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updatePreferences();
        getContentResolver().registerContentObserver(SETTINGS_CONTENT_URI, false, mObserver);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        ContentValues cv = new ContentValues(2);
        cv.put(SettingsColumns.NAME, "preferenceEnabled");
        cv.put(SettingsColumns.VALUE, isChecked);
        getContentResolver().update(SETTINGS_CONTENT_URI, cv, null, null);
    }

    public void onSettingsClick(View v) {
        try {
            Intent intent = new Intent(SETTINGS_ACTION);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this,
                    "You do not have the Settings App installed.",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void updatePreferences() {
        Cursor c = getContentResolver().query(SETTINGS_CONTENT_URI,
                new String[] {SettingsColumns.NAME, SettingsColumns.VALUE},
                null, null, null);
        if (c == null) {
            return;
        }

        while (c.moveToNext()) {
            String key = c.getString(0);
            if ("preferenceEnabled".equals(key)) {
                mEnabled.setText( String.format("Enabled Setting = %s", c.getString(1)) );
                mToggle.setChecked( Boolean.parseBoolean(c.getString(1)) );
            } else if ("preferenceName".equals(key)) {
                mName.setText( String.format("User Name Setting = %s", c.getString(1)) );
            } else if ("preferenceSelection".equals(key)) {
                mSelection.setText( String.format("Selection Setting = %s", c.getString(1)) );
            }
        }

        c.close();
    }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Update TextView with a Thread

TextView (439/474)
« Previous

Update TextView with a Thread

Description

The following code shows how to Update TextView with a Thread.

Example

\res\layout\main.xml

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

MainActivity.java

//from   w w  w.  j ava 2s  .c  o  m
package com.java2s.myapplication3.app;

import java.util.Calendar;

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

public class MainActivity extends Activity {

    TextView mClock;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mClock = new TextView(this);
        setContentView(mClock);
    }

    private Handler mHandler = new Handler();
    private Runnable timerTask = new Runnable() {
        @Override
        public void run() {
            Calendar now = Calendar.getInstance();
            mClock.setText(String.format("%02d:%02d:%02d",
                    now.get(Calendar.HOUR),
                    now.get(Calendar.MINUTE),
                    now.get(Calendar.SECOND)) );
            mHandler.postDelayed(timerTask,1000);
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        mHandler.post(timerTask);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(timerTask);
    }
}
Update TextView with a Thread

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Update the UI from a separate thread with AsyncTask

Thread (444/474)
« Previous

Update the UI from a separate thread with AsyncTask

Description

The following code shows how to Update the UI from a separate thread with AsyncTask.

Example

Main layout xml file

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<Button
    android:id="@+id/btnStartCounter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    android:onClick="startCounter" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
//from  w  ww .ja v  a  2  s  . co  m

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView txtView1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(android.R.layout.main);

        txtView1 = (TextView) findViewById(android.R.id.textView1);
    }

    private class DoCountingTask extends AsyncTask<Void, Integer, Void> {
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < 1000; i++) {
                publishProgress(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.d("Threading", e.getLocalizedMessage());
                }
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            txtView1.setText(progress[0].toString());
            Log.d("Threading", "updating...");
        }
    }

    public void startCounter(View view) {
        new DoCountingTask().execute();
    }

}

}

The preceding code will update the UI safely from another thread.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Upgrade the Database

Database (111/474)
« Previous

Upgrade the Database

Description

To upgrade the database, change the DATABASE_VERSION constant to a value higher than the previous one. For example, if its previous value was 1, change it to 2:

Example

package com.java2s.myapplication3.app;
//from w  ww.j  a v a2s  .co  m
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
    static final String KEY_ROWID = "_id";
    static final String KEY_NAME = "name";
    static final String KEY_EMAIL = "email";
    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "MyDB";
    static final String DATABASE_TABLE = "contacts";
    static final int DATABASE_VERSION = 1;

    static final String DATABASE_CREATE =
            "create table contacts (_id integer primary key autoincrement, "
                    + "name text not null, email text not null);";

    final Context context;

    DatabaseHelper DBHelper;
    SQLiteDatabase db;

    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }
    //opens the database
    public DBAdapter open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //closes the database
    public void close()
    {
        DBHelper.close();
    }

    //insert a contact into the database
    public long insertContact(String name, String email)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_EMAIL, email);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //deletes a particular contact
    public boolean deleteContact(long rowId)
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    //retrieves all the contacts
    public Cursor getAllContacts()
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_EMAIL}, null, null, null, null, null);
    }

    //retrieves a particular contact
    public Cursor getContact(long rowId) throws SQLException
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                                KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //updates a contact
    public boolean updateContact(long rowId, String name, String email)
    {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_EMAIL, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use a DialogFragment

Fragment (312/474)
« Previous

Use a DialogFragment

Description

A dialog fragment floats on top of an activity and is displayed modally.

To create a dialog fragment, you need to extend the DialogFragment base class.

Example

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/*from  w  w w . ja v  a  2 s  .c o  m*/
public class Fragment1 extends DialogFragment {

    static Fragment1 newInstance(String title) {
        Fragment1 fragment = new Fragment1();
        Bundle args = new Bundle();
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
          String title = getArguments().getString("title");
          return new AlertDialog.Builder(getActivity())
          .setIcon(R.drawable.ic_launcher)
          .setTitle(title)
          .setPositiveButton("OK",
                  new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                      int whichButton) {
                  ((DialogFragmentExampleActivity)
                          getActivity()).doPositiveClick();
              }
          })
          .setNegativeButton("Cancel",
                  new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                      int whichButton) {
                  ((DialogFragmentExampleActivity)
                          getActivity()).doNegativeClick();
              }
          }).create();
    }

}

Populate the MainActivity.java file as shown here:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
/*w w w. java 2s  .  c om*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment1 dialogFragment = Fragment1.newInstance (
                "Are you sure you want to do this?");
        dialogFragment.show(getFragmentManager(), "dialog");
    }

    public void doPositiveClick() {
        //---perform steps when user clicks on OK---
        Log.d("DialogFragmentExample", "User clicks on OK");
    }

    public void doNegativeClick() {
        //---perform steps when user clicks on Cancel---
        Log.d("DialogFragmentExample", "User clicks on Cancel");
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use a ListFragment

Fragment (311/474)
« Previous

Use a ListFragment

Description

The following code shows how to Use a ListFragment. A list fragment is a fragment that contains a ListView.

Example

Main layout file

<?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="horizontal" >

 <fragment
    android:name="com.java2s.ListFragmentExample.Fragment1"
    android:id="@+id/fragment1"
    android:layout_weight="0.5"
    android:layout_width="0dp"
    android:layout_height="200dp" />

 <fragment
    android:name="com.java2s.ListFragmentExample.Fragment1"
    android:id="@+id/fragment2"
    android:layout_weight="0.5"
    android:layout_width="0dp"
    android:layout_height="300dp" />

</LinearLayout>

Populate the fragment1.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   <ListView
       android:id="@id/android:list"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_weight="1"
       android:drawSelectorOnTop="false"/>
</LinearLayout>

Java code for Fragment1.java

import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/*w  w w  . jav  a  2  s  .c o  m*/
public class Fragment1 extends ListFragment {
    String[] myValue = {"XML","HTML","CSS","Javascript"};

    @Override
    public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, myValue));
    }

    public void onListItemClick(ListView parent, View v,
    int position, long id)
    {
        Toast.makeText (getActivity(),
            "You have selected " + myValue [position],
            Toast.LENGTH_SHORT).show();
    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Action Bar

Action Bar (233/474)
« Previous

Use Action Bar

Description

Action Bar is located at the top of the device's screen, it displays the application icon together with the activity title.

To turn off the action bar in manifest xml file.

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
          <activity
              android:label="@string/app_name"
              android:name=".MyActionBarActivity"
              android:theme="@android:style/Theme.Holo.NoActionBar" >
              <intent-filter >
                  <action android:name="android.intent.action.MAIN" />
                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

</manifest>

To hide the action bar in code

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
/*from w  w  w .j  av  a  2  s  .  c  o m*/
public class MyActionBarActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ActionBar actionBar = getActionBar();
        actionBar.hide();
        //actionBar.show(); //show it again
    }
}

If you use the android:theme attribute to turn off the Action Bar, calling the getActionBar() method returns a null during runtime.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use AlertDialog.Builder to build an AlertDialog

Dialog (284/474)
« Previous

Use AlertDialog.Builder to build an AlertDialog

Description

The following code shows how to Use AlertDialog.Builder to build an AlertDialog.

Example

package com.java2s.myapplication3.app;
//from   w w w  . j a  v  a2  s .  c om
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity
        implements DialogInterface.OnClickListener, View.OnClickListener {

    private static final String[] ZONES =
            {"Pacific Time", "Mountain Time", "Central Time", "Eastern Time", "Atlantic Time"};

    Button mButton;
    AlertDialog mActions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Activity");
        mButton = new Button(this);
        mButton.setText("Click for Time Zones");
        mButton.setOnClickListener(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select Time Zone");
        builder.setItems(ZONES, this);
        builder.setNegativeButton("Cancel", null);
        mActions = builder.create();
        setContentView(mButton);
    }
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String selected = ZONES[which];
        mButton.setText(selected);
    }
   @Override
    public void onClick(View v) {
        mActions.show();
    }
}
Use AlertDialog.Builder to build an AlertDialog

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use AlertDialog to display text from EditText

Dialog (280/474)
« Previous

Use AlertDialog to display text from EditText

Description

The following code shows how to use AlertDialog to display text from EditText.

Example

/*from   www.j  a  v a 2s . com*/

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/script"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/eval"
        android:test="OK"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</LinearLayout>

Java code

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
//w  w  w.  j a v  a  2s . co  m
public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    Button btn=(Button)findViewById(R.id.eval);
    final EditText script=(EditText)findViewById(R.id.script);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        String src=script.getText().toString();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Exception!")
             .setMessage(e.toString())
            .setPositiveButton("OK", null)
            .show();
      }
    });
  }
}
Use AlertDialog to display text from EditText

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use any XML Resource Files

Resources (38/474)
« Previous

Use any XML Resource Files

Description

In Android we can use arbitrary XML files as resources.

You can access the xml file from its generated resource IDs, by which you can localize these resource XML files.
Therefore you can compile and store these XML files on the device efficiently.

XML files need to be stored under the /res/xml subdirectory.

Example

The following code shows an example XML file called /res/xml/test.xml.

<root>
   <sub>
      Hello World from an xml sub element
   </sub>
</root>

The AAPT compiles this XML file before placing it in the application package.

The following code shows how to use XmlPullParser to parse these files.

Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.test);
//from ww  w  .j  a va 2 s  . c o m
private String getEventsFromAnXMLFile(Activity activity) throws XmlPullParserException, IOException
{
   StringBuffer sb = new StringBuffer();
   Resources res = activity.getResources();
   XmlResourceParser xpp = res.getXml(R.xml.test);

   xpp.next();
   int eventType = xpp.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT)
    {
        if(eventType == XmlPullParser.START_DOCUMENT)
        {
           System.out.println("Start document");
        }
        else if(eventType == XmlPullParser.START_TAG)
        {
           System.out.println("Start tag "+xpp.getName());
        }
        else if(eventType == XmlPullParser.END_TAG)
        {
           System.out.println("End tag "+xpp.getName());
        }
        else if(eventType == XmlPullParser.TEXT)
        {
           System.out.println("Text "+xpp.getText());
        }
        eventType = xpp.next();
    }
    return sb.toString();
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ArrayAdapter to fill data to AutoCompleteTextView

TextView (436/474)
« Previous

Use ArrayAdapter to fill data to AutoCompleteTextView

Description

The following code show how to use ArrayAdapter to fill data to AutoCompleteTextView.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <AutoCompleteTextView android:id="@+id/edit"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:completionThreshold="3"/>
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
// w  ww . jav  a  2 s.  co  m
public class MainActivity extends Activity
  implements TextWatcher {
  TextView selection;
  AutoCompleteTextView edit;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);
    edit=(AutoCompleteTextView)findViewById(R.id.edit);
    edit.addTextChangedListener(this);

    edit.setAdapter(new ArrayAdapter<String>(this,
                          android.R.layout.simple_dropdown_item_1line,
                          items));
  }

  public void onTextChanged(CharSequence s, int start, int before,
                              int count) {
    selection.setText(edit.getText());
  }

  public void beforeTextChanged(CharSequence s, int start,int count, int after) {

  }

  public void afterTextChanged(Editable s) {

  }
}
Use ArrayAdapter to fill data to AutoCompleteTextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Assets

Resources (43/474)
« Previous

Use Assets

Description

Android offers one more directory for you to store resource files: /assets.

/assets is at the same level as /res.

The files in /assets do not generate IDs in R.java. You must specify the file path to read them.

The file path is a relative path starting at /assets.

Example

You use the AssetManager class to access these files.

String getStringFromAssetFile(Activity activity)
{//from  w w  w. j a va 2  s  .co  m
   AssetManager am = activity.getAssets();
   InputStream is = am.open("test.txt");
   String s = convertStreamToString(is);
   is.close();
   return s;
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use AutoCompleteTextView

TextView (437/474)
« Previous

Use AutoCompleteTextView

Description

The AutoCompleteTextView control is a TextView with auto-complete functionality. As you types in the TextView, the control can display suggestions for selection.

Example

The following code shows how to use the AutoCompleteTextView control with XML and with the corresponding code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
// w  w  w. j  a v a  2 s  . c  om
    <AutoCompleteTextView
        android:id="@+id/myID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

The Java code.

    // ww  w . ja va  2 s.c  o m
package com.java2s.app;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

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

        AutoCompleteTextView actv = (AutoCompleteTextView) this.findViewById(R.id.myID);

        ArrayAdapter<String> aa = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
                new String[]{"XML", "CSS", "HTML", "Java",
                        "SQL", "Code"}
        );

        actv.setAdapter(aa);
    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use background thread to do image processing

Thread (446/474)
« Previous

Use background thread to do image processing

Description

The following code shows how to Use background thread to do image processing.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main layout xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Scale Icon"
        android:onClick="onScaleClick" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Crop Icon"
        android:onClick="onCropClick" />

    <ImageView
        android:id="@+id/image_result"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="center" />
</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
//from  w  w  w  .jav  a2 s.c om
public class WorkerActivity extends Activity implements Handler.Callback {

    private ImageProcessor mWorker;
    private Handler mResponseHandler;

    private ImageView mResultView;

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

        mResultView = (ImageView) findViewById(R.id.image_result);
        mResponseHandler = new Handler(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWorker = new ImageProcessor(this, mResponseHandler);
        mWorker.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWorker.setCallback(null);
        mWorker.quit();
        mWorker = null;
    }
    @Override
    public boolean handleMessage(Message msg) {
        Bitmap result = (Bitmap) msg.obj;
        mResultView.setImageBitmap(result);
        return true;
    }

    public void onScaleClick(View v) {
        for(int i=1; i < 10; i++) {
            mWorker.scaleIcon(i);
        }
    }

    public void onCropClick(View v) {
        for(int i=1; i < 10; i++) {
            mWorker.cropIcon(i);
        }
    }
}
class ImageProcessor extends HandlerThread implements Handler.Callback {
    public static final int MSG_SCALE = 100;
    public static final int MSG_CROP = 101;

    private Context mContext;
    private Handler mReceiver, mCallback;

    public ImageProcessor(Context context) {
        this(context, null);
    }

    public ImageProcessor(Context context, Handler callback) {
        super("AndroidRecipesWorker");
        mCallback = callback;
        mContext = context;
    }

    @Override
    protected void onLooperPrepared() {
        mReceiver = new Handler(getLooper(), this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        Bitmap source, result;
        int scale = msg.arg1;
        switch (msg.what) {
        case MSG_SCALE:
            source = BitmapFactory.decodeResource(mContext.getResources(),
                    R.drawable.ic_launcher);
            result = Bitmap.createScaledBitmap(source,
                    source.getWidth() * scale, source.getHeight() * scale, true);
            break;
        case MSG_CROP:
            source = BitmapFactory.decodeResource(mContext.getResources(),
                    R.drawable.ic_launcher);
            int newWidth = source.getWidth() / scale;
            result = Bitmap.createBitmap(source,
                    (source.getWidth() - newWidth) / 2, 0,
                    newWidth, source.getHeight());
            break;
        default:
            throw new IllegalArgumentException("Unknown Worker Request");
        }
        if (mCallback != null) {
            mCallback.sendMessage(Message.obtain(null, 0, result));
        }
        return true;
    }
    public void setCallback(Handler callback) {
        mCallback = callback;
    }
    public void scaleIcon(int scale) {
        Message msg = Message.obtain(null, MSG_SCALE, scale, 0, null);
        mReceiver.sendMessage(msg);
    }

    //Crop the icon in the center and scale the result to the specified value
    public void cropIcon(int scale) {
        Message msg = Message.obtain(null, MSG_CROP, scale, 0, null);
        mReceiver.sendMessage(msg);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use code to change the gravity layout for RadioGroup

RadioButton (410/474)
« Previous

Use code to change the gravity layout for RadioGroup

Description

The following code shows how to use code to change the gravity layout for RadioGroup.

Example

Layout xml

<LinearLayout/*from ww  w  .  ja  v  a2 s.  c o  m*/
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <RadioGroup android:id="@+id/orientation"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5px">
        <RadioButton
            android:id="@+id/horizontal"
            android:text="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <RadioButton
            android:id="@+id/vertical"
            android:text="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </RadioGroup>
    <RadioGroup android:id="@+id/gravity"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5px">
        <RadioButton
            android:id="@+id/left"
            android:text="left"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <RadioButton
            android:id="@+id/center"
            android:text="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <RadioButton
            android:id="@+id/right"
            android:text="right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </RadioGroup>
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.text.TextWatcher;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.EditText;
//from   w w  w.j a v  a2s .c o m
public class MainActivity extends Activity
  implements RadioGroup.OnCheckedChangeListener {
  RadioGroup orientation;
  RadioGroup gravity;

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

    orientation=(RadioGroup)findViewById(R.id.orientation);
    orientation.setOnCheckedChangeListener(this);
    gravity=(RadioGroup)findViewById(R.id.gravity);
    gravity.setOnCheckedChangeListener(this);
  }

  public void onCheckedChanged(RadioGroup group, int checkedId) {
    if (group==orientation) {
      if (checkedId==R.id.horizontal) {
        orientation.setOrientation(LinearLayout.HORIZONTAL);
      }
      else {
        orientation.setOrientation(LinearLayout.VERTICAL);
      }
    }
    else if (group==gravity) {
      if (checkedId==R.id.left) {
        gravity.setGravity(Gravity.LEFT);
      }
      else if (checkedId==R.id.center) {
        gravity.setGravity(Gravity.CENTER_HORIZONTAL);
      }
      else if (checkedId==R.id.right) {
        gravity.setGravity(Gravity.RIGHT);
      }
    }
  }
}
Use code to change the gravity layout for RadioGroup

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use code to control vertical or horizontal layout for RadioGroup

RadioButton (411/474)
« Previous

Use code to control vertical or horizontal layout for RadioGroup

Description

The following code shows how to use code to control vertical or horizontal layout for RadioGroup.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout// www.  j  ava 2s.  co  m
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <RadioGroup android:id="@+id/orientation"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5px">
        <RadioButton
            android:id="@+id/horizontal"
            android:text="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <RadioButton
            android:id="@+id/vertical"
            android:text="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RadioGroup>
    <RadioGroup android:id="@+id/gravity"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5px">
        <RadioButton
            android:id="@+id/left"
            android:text="left"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <RadioButton
            android:id="@+id/center"
            android:text="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <RadioButton
            android:id="@+id/right"
            android:text="right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RadioGroup>
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.text.TextWatcher;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.EditText;
/*www .jav a  2 s .  c om*/
public class MainActivity extends Activity
  implements RadioGroup.OnCheckedChangeListener {
  RadioGroup orientation;
  RadioGroup gravity;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    orientation=(RadioGroup)findViewById(R.id.orientation);
    orientation.setOnCheckedChangeListener(this);
    gravity=(RadioGroup)findViewById(R.id.gravity);
    gravity.setOnCheckedChangeListener(this);
  }

  public void onCheckedChanged(RadioGroup group, int checkedId) {
    if (group==orientation) {
      if (checkedId==R.id.horizontal) {
        orientation.setOrientation(LinearLayout.HORIZONTAL);
      }
      else {
        orientation.setOrientation(LinearLayout.VERTICAL);
      }
    }
    else if (group==gravity) {
      if (checkedId==R.id.left) {
        gravity.setGravity(Gravity.LEFT);
      }
      else if (checkedId==R.id.center) {
        gravity.setGravity(Gravity.CENTER_HORIZONTAL);
      }
      else if (checkedId==R.id.right) {
        gravity.setGravity(Gravity.RIGHT);
      }
    }
  }
}
Use code to control vertical or horizontal layout for RadioGroup

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use color resource in a view definition

Resources (32/474)
« Previous

Use color resource in a view definition

Description

As string resource, we can reference color resource in layout.

Example

The following code shows how you can use a color resource in a view definition.

<resources>
    <color name="red">#f00</color>
    <color name="blue">#0000ff</color>
    <color name="green">#f0f0</color>
    <color name="main_back_ground_color">#ffffff00</color>
</resources>

The following code shows how to use defined color in layout resource.

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textColor="@color/red"
          android:text="Sample Text to Show Red Color"/>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Contact Content Provider

Contact (89/474)
« Previous

Use Contact Content Provider

Description

The following code shows how to Use Contact Content Provider.

Example

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

<ListView
    android:id="@+id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:stackFromBottom="false"
    android:transcriptMode="normal" />

<TextView
    android:id="@+id/contactName"
    android:textStyle="bold"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/contactID"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

Java code

package com.java2s.myapplication3.app;
/*w  w w  .j av a2 s .c  o m*/
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

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

        Uri allContacts = Uri.parse("content://contacts/people");

        Cursor c;
        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            c = managedQuery(allContacts, null, null, null, null);
        } else {
            //Honeycomb and later
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    null,
                    null,
                    null,
                    null);
            c = cursorLoader.loadInBackground();
        }

        String[] columns = new String[]{
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID};

        int[] views = new int[]{R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter;

        if (android.os.Build.VERSION.SDK_INT < 11) {
            //before Honeycomb
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views);
        } else {
            //Honeycomb and later
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_main, c, columns, views,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        }

        this.setListAdapter(adapter);
    }
}

Add the following statements to the AndroidManifest.xml file:

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

     <uses-sdk android:minSdkVersion="14" />
     <uses-permission android:name="android.permission.READ_CONTACTS"/>

     <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name" >
       <activity
           android:label="@string/app_name"
           android:name=".ProviderActivity" >
           <intent-filter >
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Context menu to control ListView

ListView (383/474)
« Previous

Use Context menu to control ListView

Description

The following code shows how to Use Context menu to control ListView.

Example

Menu main.xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/menu_delete"
    android:icon="@android:drawable/ic_menu_delete"
    android:title="Delete Item"
  />
  <item
    android:id="@+id/menu_edit"
    android:icon="@android:drawable/ic_menu_edit"
    android:title="Edit Item"
  />
</menu>

Activity Java code

package com.java2s.myapplication3.app;
/*from  w w  w . j a va2s .  c  o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private static final String[] ITEMS =
            {"CSS", "HTML", "Javascript", "SQL", "Java", "Android"};

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListView list = new ListView(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, ITEMS);
        list.setAdapter(adapter);
        registerForContextMenu(list);

        setContentView(list);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.main, menu);
        menu.setHeaderTitle("Choose an Option");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int listPosition = info.position;
        switch(item.getItemId()) {
            case R.id.menu_delete:
                //Perform delete actions
                break;
            case R.id.menu_edit:
                //Perform edit actions
                break;
            default:
                return super.onContextItemSelected(item);
        }
        return true;
    }

}
Use Context menu to control ListView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use custom model in ArrayAdapter

Model (397/474)
« Previous

Use custom model in ArrayAdapter

Description

The following code shows how to use custom model in ArrayAdapter.

Example

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2012 Manning
  See the file license.txt for copying permission.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/image"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/text1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/text2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>

Java code

/*******************************************************************************
 * Copyright (c) 2012 Manning/*from  w  w w.j  av a  2 s. c  o  m*/
 * See the file license.txt for copying permission.
 ******************************************************************************/
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.os.Bundle;

public class MainActivity extends ListActivity {

  private static final int MODEL_COUNT = 30;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new ModelAdapter(this, 0, buildModels()));
  }

  private List<Model> buildModels() {
    final ArrayList<Model> ret = new ArrayList<Model>(MODEL_COUNT);
    for (int i = 0; i < MODEL_COUNT; i++) {
      final Model model = new Model();
      model.setImage(R.drawable.icon);
      model.setText1("Name " + i);
      model.setText2("Description " + i);
      ret.add(model);
    }
    return ret;
  }
}
class Model {

  private String mText1;
  private String mText2;
  private int mImageResId;

  public String getText1() {
    return mText1;
  }

  public void setText1(String text1) {
    mText1 = text1;
  }

  public String getText2() {
    return mText2;
  }

  public void setText2(String text2) {
    mText2 = text2;
  }

  public int getImage() {
    return mImageResId;
  }

  public void setImage(int imageResId) {
    mImageResId = imageResId;
  }
}

class ModelAdapter extends ArrayAdapter<Model> {

  private LayoutInflater mInflater;

  public ModelAdapter(Context context, int textViewResourceId,
      List<Model> objects) {
    super(context, textViewResourceId, objects);
    mInflater = LayoutInflater.from(context);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;

    if (convertView == null) {
      convertView = mInflater.inflate(R.layout.row_layout, parent,
          false);

      viewHolder = new ViewHolder();
      viewHolder.imageView = (ImageView) convertView
          .findViewById(R.id.image);
      viewHolder.text1 = (TextView) convertView
          .findViewById(R.id.text1);
      viewHolder.text2 = (TextView) convertView
          .findViewById(R.id.text2);

      convertView.setTag(viewHolder);

    } else {
      viewHolder = (ViewHolder) convertView.getTag();
    }

    Model model = getItem(position);
    viewHolder.imageView.setImageResource(model.getImage());
    viewHolder.text1.setText(model.getText1());
    viewHolder.text2.setText(model.getText2());

    return convertView;
  }

  private static class ViewHolder {
    public ImageView imageView;
    public TextView text1;
    public TextView text2;
  }
}

res/layout/row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@+id/numbers_row_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"/>

    <Button android:id="@+id/numbers_row_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remove"/>

</LinearLayout>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use DatePickerDialog

Clock Date Picker (273/474)
« Previous

Use DatePickerDialog

Description

The following code shows how to Use DatePickerDialog.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView android:id="@+id/dateAndTime"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <Button android:id="@+id/dateBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Set the Date"
    />
  <Button android:id="@+id/timeBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Set the Time"
    />
</LinearLayout>

Java code

/***/*from  w  w w  . j a v  a2s.c o  m*/
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.java2s.myapplication3.app;

import android.app.Activity;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Calendar;

public class MainActivity extends Activity {
    DateFormat fmtDateAndTime=DateFormat.getDateTimeInstance();
    TextView dateAndTimeLabel;
    Calendar dateAndTime=Calendar.getInstance();
    DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            dateAndTime.set(Calendar.YEAR, year);
            dateAndTime.set(Calendar.MONTH, monthOfYear);
            dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }
    };
    TimePickerDialog.OnTimeSetListener t=new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay,
                              int minute) {
            dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            dateAndTime.set(Calendar.MINUTE, minute);
            updateLabel();
        }
    };

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

        Button btn=(Button)findViewById(R.id.dateBtn);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new DatePickerDialog(MainActivity.this,
                        d,
                        dateAndTime.get(Calendar.YEAR),
                        dateAndTime.get(Calendar.MONTH),
                        dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        btn=(Button)findViewById(R.id.timeBtn);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new TimePickerDialog(MainActivity.this,
                        t,
                        dateAndTime.get(Calendar.HOUR_OF_DAY),
                        dateAndTime.get(Calendar.MINUTE),
                        true).show();
            }
        });

        dateAndTimeLabel=(TextView)findViewById(R.id.dateAndTime);

        updateLabel();
    }

    private void updateLabel() {
        dateAndTimeLabel.setText(fmtDateAndTime.format(dateAndTime.getTime()));
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use DownloadManager to download

Network (180/474)
« Previous

Use DownloadManager to download

Description

The following code shows how to Use DownloadManager to download.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.downloader"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DownloadActivity"
                  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>
    <uses-sdk android:minSdkVersion="9" />

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

Main layout xml file

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

Main Activity Java code

// w  w w.j  av a  2 s  . c om
package com.java2s.myapplication4.app;

import java.io.FileInputStream;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private static final String DL_ID = "downloadId";
    private SharedPreferences prefs;
    private DownloadManager dm;
    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageView = new ImageView(this);
        setContentView(imageView);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!prefs.contains(DL_ID)) {
            Uri resource = Uri.parse("http://www.java2s.com");
            DownloadManager.Request request = new DownloadManager.Request(resource);
            request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
            request.setAllowedOverRoaming(false);
            request.setTitle("Download Sample");
            long id = dm.enqueue(request);
            prefs.edit().putLong(DL_ID, id).commit();
        } else {
            queryDownloadStatus();
        }
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

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

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            queryDownloadStatus();
        }
    };

    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(prefs.getLong(DL_ID, 0));
        Cursor c = dm.query(query);
        if(c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch(status) {
                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    try {
                        ParcelFileDescriptor file = dm.openDownloadedFile(prefs.getLong(DL_ID, 0));
                        FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(file);
                        imageView.setImageBitmap(BitmapFactory.decodeStream(fis));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case DownloadManager.STATUS_FAILED:
                    dm.remove(prefs.getLong(DL_ID, 0));
                    prefs.edit().clear().commit();
                    break;
            }
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ExpandableListView

ListView (384/474)
« Previous

Use ExpandableListView

Description

The following code shows how to Use ExpandableListView.

Example

Main layout xml file

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

Main Activity Java code

import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
//from  w ww.j  av  a2  s  .c o  m
import android.app.Activity;
import android.os.Bundle;
import android.widget.ExpandableListView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExpandableListView list = new ExpandableListView(this);
        list.setGroupIndicator(null);
        list.setChildIndicator(null);
        String[] titles = {"Fruits","Vegetables","Meats"};
        String[] fruits = {"Apples","Oranges"};
        String[] veggies = {"Carrots","Peas","Broccoli"};
        String[] meats = {"Pork","Chicken"};
        String[][] contents = {fruits,veggies,meats};
        SimplerExpandableListAdapter adapter = new SimplerExpandableListAdapter(this,
            titles, contents);

        list.setAdapter(adapter);
        setContentView(list);

    }
}

class SimplerExpandableListAdapter extends BaseExpandableListAdapter {
  private Context mContext;
  private String[][] mContents;
  private String[] mTitles;

  public SimplerExpandableListAdapter(Context context, String[] titles, String[][] contents) {
    super();
    //Check arguments
    if(titles.length != contents.length) {
      throw new IllegalArgumentException("Titles and Contents must be the same size.");
    }

    mContext = context;
    mContents = contents;
    mTitles = titles;
  }

  //Return a child item
  @Override
  public String getChild(int groupPosition, int childPosition) {
    return mContents[groupPosition][childPosition];
  }

  //Return a item's id
  @Override
  public long getChildId(int groupPosition, int childPosition) {
    return 0;
  }

  //Return view for each item row
  @Override
  public View getChildView(int groupPosition, int childPosition,
      boolean isLastChild, View convertView, ViewGroup parent) {
    TextView row = (TextView)convertView;
    if(row == null) {
      row = new TextView(mContext);
    }
    row.setText(mContents[groupPosition][childPosition]);
    return row;
  }

  //Return number of items in each section
  @Override
  public int getChildrenCount(int groupPosition) {
    return mContents[groupPosition].length;
  }

  //Return sections
  @Override
  public String[] getGroup(int groupPosition) {
    return mContents[groupPosition];
  }

  //Return the number of sections
  @Override
  public int getGroupCount() {
    return mContents.length;
  }

  //Return a section's id
  @Override
  public long getGroupId(int groupPosition) {
    return 0;
  }

  //Return a view for each section header
  @Override
  public View getGroupView(int groupPosition, boolean isExpanded,
      View convertView, ViewGroup parent) {
    TextView row = (TextView)convertView;
    if(row == null) {
      row = new TextView(mContext);
    }
    row.setTypeface(Typeface.DEFAULT_BOLD);
    row.setText(mTitles[groupPosition]);
    return row;
  }

  @Override
  public boolean hasStableIds() {
    return false;
  }

  @Override
  public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
  }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use format string in TextView

TextView (426/474)
« Previous

Use format string in TextView

Description

The following code shows how to Use format string in TextView.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <ImageButton android:id="@+id/format"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@drawable/icon"
      />
    <EditText android:id="@+id/name"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      />
  </LinearLayout>
  <TextView android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Java code

/***/*from  www.  j  a  v a  2  s  .co  m*/
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
  EditText name;
  TextView result;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    name=(EditText)findViewById(R.id.name);
    result=(TextView)findViewById(R.id.result);

    ImageButton btn=(ImageButton)findViewById(R.id.format);

    btn.setOnClickListener(new Button.OnClickListener() {
      public void onClick(View v) {
        applyFormat();
      }
    });
  }

  private void applyFormat() {
    String format="My name is &lt;b&gt;%1$s&lt;/b&gt;";
    String simpleResult=String.format(format,TextUtils.htmlEncode(name.getText().toString()));
    result.setText(Html.fromHtml(simpleResult));
  }
}
Use format string in TextView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use FragmentManager

Fragment (314/474)
« Previous

Use FragmentManager

Description

The following code shows how to Use FragmentManager.

Example

Layout xml file

<?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">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Go Home"
        android:onClick="onHomeClick" />
    <FrameLayout
        android:id="@+id/container_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Main activity Java code

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/*from  ww  w .  j ava2 s.  com*/
public class MyActivity extends FragmentActivity {

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

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container_fragment, MyFragment.newInstance("First Fragment"));
        ft.commit();

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container_fragment, MyFragment.newInstance("Second Fragment"));
        ft.addToBackStack("second");
        ft.commit();

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container_fragment, MyFragment.newInstance("Third Fragment"));
        ft.addToBackStack("second");
        ft.commit();

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container_fragment, MyFragment.newInstance("Fourth Fragment"));
        ft.addToBackStack("fourth");
        ft.commit();
    }

    public void onHomeClick(View v) {
        getSupportFragmentManager().popBackStack("second", FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public static class MyFragment extends Fragment {
        private CharSequence mTitle;

        public static MyFragment newInstance(String title) {
            MyFragment fragment = new MyFragment();
            fragment.setTitle(title);

            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            TextView text = new TextView(getActivity());
            text.setText(mTitle);
            text.setBackgroundColor(Color.WHITE);

            return text;
        }

        public void setTitle(CharSequence title) {
            mTitle = title;
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use FrameLayout inside TabHost

Layout (355/474)
« Previous

Use FrameLayout inside TabHost

Description

The following xml code puts FrameLayout inside TabHost.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TabHost android:id="@+id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabWidget android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    />
    <FrameLayout android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:paddingTop="62px">
      <AnalogClock android:id="@+id/tab1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
      />
      <Button android:id="@+id/tab2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="A semi-random button"
      />
    </FrameLayout>
  </TabHost>
</LinearLayout>

Java code

/***//from  w  w  w.  ja v  a2 s. c  o  m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

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

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    TabHost tabs=(TabHost)findViewById(R.id.tabhost);

    tabs.setup();

    TabHost.TabSpec spec=tabs.newTabSpec("tag1");

    spec.setContent(R.id.tab1);
    spec.setIndicator("Clock");
    tabs.addTab(spec);

    spec=tabs.newTabSpec("tag2");
    spec.setContent(R.id.tab2);
    spec.setIndicator("Button");
    tabs.addTab(spec);

    tabs.setCurrentTab(0);
  }
}
Use FrameLayout inside TabHost

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use GridView to display array data

GridView (322/474)
« Previous

Use GridView to display array data

Description

The following code shows how to Use GridView to display array data.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <GridView
    android:id="@+id/grid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:verticalSpacing="35px"
    android:horizontalSpacing="5px"
    android:numColumns="auto_fit"
    android:columnWidth="100px"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />
</LinearLayout>

Java code

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
//  www .  j a  v  a  2s .  c o m
public class MainActivity extends Activity
  implements AdapterView.OnItemSelectedListener {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);

    GridView g=(GridView) findViewById(R.id.grid);
    g.setAdapter(new FunnyLookingAdapter(this,
                        android.R.layout.simple_list_item_1,
                        items));
    g.setOnItemSelectedListener(this);
  }

  public void onItemSelected(AdapterView<?> parent, View v,
                              int position, long id) {
    selection.setText(items[position]);
  }

  public void onNothingSelected(AdapterView<?> parent) {
    selection.setText("");
  }

  private class FunnyLookingAdapter extends ArrayAdapter {
    Context ctxt;

    FunnyLookingAdapter(Context ctxt, int resource,
                        String[] items) {
      super(ctxt, resource, items);

      this.ctxt=ctxt;
    }

    public View getView(int position, View convertView,
                          ViewGroup parent) {
      TextView label=(TextView)convertView;

      if (convertView==null) {
        convertView=new TextView(ctxt);
        label=(TextView)convertView;
      }

      label.setText(items[position]);

      return(convertView);
    }
  }
}

/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/
Use GridView to display array data

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Handler class to Update UI from another thread

Thread (445/474)
« Previous

Use Handler class to Update UI from another thread

Description

A Handler enables you to send and process messages, similar to using the post() method of a View.

The following code shows how to Use Handler class to Update UI from another thread.

Example

Main layout xml file

<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

<Button
    android:id="@+id/btnStartCounter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    android:onClick="startCounter" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*ww  w.  j  a  va  2 s  . c  om*/

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    static TextView txtView1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtView1 = (TextView) findViewById(R.id.textView1);
    }

    static Handler UIupdater = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            byte [] buffer = (byte []) msg.obj;
            String strReceived = new String(buffer);
            txtView1.setText(strReceived);
        }
    };

    public void startCounter(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0; i<=1000; i++) {
                    MainActivity.UIupdater.obtainMessage(
                            0,  String.valueOf(i).getBytes() ).sendToTarget();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Log.d ("Threading", e.getLocalizedMessage());
                    }
                }
            }
        }).start();
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Handler to send message to ProgressBar and update progress

ProgressBar (405/474)
« Previous

Use Handler to send message to ProgressBar and update progress

Description

The following code shows how to use Handler to send message to ProgressBar and update progress.

Example

Layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <ProgressBar android:id="@+id/progress"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
/*  w ww .j  ava  2s.  co m*/
public class MainActivity extends Activity {
  ProgressBar bar;
  Handler handler=new Handler() {
    @Override
    public void handleMessage(Message msg) {
      bar.incrementProgressBy(5);
    }
  };
  boolean isRunning=false;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    bar=(ProgressBar)findViewById(R.id.progress);
  }

  public void onStart() {
    super.onStart();
    bar.setProgress(0);

    Thread background=new Thread(new Runnable() {
      public void run() {
        try {
          for (int i=0;i<20 && isRunning;i++) {
            Thread.sleep(1000);
            handler.sendMessage(handler.obtainMessage());
          }
        }
        catch (Throwable t) {
          // just end the background thread
        }
      }
    });

    isRunning=true;
    background.start();
  }

  public void onStop() {
    super.onStop();
    isRunning=false;
  }
}
Use Handler to send message to ProgressBar and update progress

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ImageButton

Button (248/474)
« Previous

Use ImageButton

Description

Android provides an image button via android.widget.ImageButton.

Using an image button is similar to using the basic button.

//  w  w w  .  j a v a2  s  .  c o  m
<ImageButton android:id="@+id/imageButton2"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:onClick="myClickHandler"
             android:src="@drawable/icon"  />

Java code to set image to an ImageButton.

ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setImageResource(R.drawable.icon);

The image file for the button must exist under /res/drawable.

Example

<?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" >
/*from   ww w.  ja  v  a 2  s  . c o m*/
    <ImageButton android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myClickHandler"
        android:src="@drawable/ic_launcher"  />
</LinearLayout>

Java code

package com.java2s.app;
// w  ww.  j a  va2  s  .c om
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent Categories

Intent (131/474)
« Previous

Use Intent Categories

Description

You can group your activities into categories by using the <category> element in the intent filter.

Example

AndroidManifest.xml file:

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

              <uses-sdk android:minSdkVersion="14" />
              <uses-permission android:name="android.permission.CALL_PHONE"/>
              <uses-permission android:name="android.permission.INTERNET"/>
              <application
                  android:icon="@drawable/ic_launcher"
                  android:label="@string/app_name" >
                  <activity
                      android:label="@string/app_name"
                      android:name=".IntentsActivity" >
                      <intent-filter >
                          <action android:name="android.intent.action.MAIN" />
                          <category android:name="android.intent.category.LAUNCHER" />
                      </intent-filter>
                  </activity>

                  <activity android:name=".MyBrowserActivity"
                            android:label="@string/app_name">
                      <intent-filter>
                          <action android:name="android.intent.action.VIEW" />
                          <action android:name="com.java2s.MyBrowser" />
                          <category android:name="android.intent.category.DEFAULT" />
                          <category android:name="com.java2s.Apps" />
                          <data android:scheme="http" />
                      </intent-filter>
                  </activity>

              </application>

          </manifest>

The following code will directly invoke the MyBrowerActivity activity:

Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse ("http://www.java2s.com"));
i.addCategory("com.java2s.Apps");
startActivity(Intent.createChooser(i, "Open URL using..."));

If you omit the addCategory() statement, the preceding code will still invoke the MyBrowerActivity activity because it will still match the default category android.intent.category.DEFAULT.

For the following code it does not match the category defined in the intent filter, therefore no activity will be launched:

Note

The following code references category com.java2s.OtherApps and it does not match any category in the intent filter, so a run-time exception will be raised if you don't use the createChoose() method of the Intent class.

Intent i = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse ("http://www.java2s.com"));
//i.addCategory("com.java2s.Apps");
//this category does not match any in the intent-filter
i.addCategory("com.java2s.OtherApps");
startActivity(Intent.createChooser(i, "Open URL using..."));

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent Filters

Intent (132/474)
« Previous

Use Intent Filters

Description

The following code shows how to Use Intent Filters.

Example

Set up manifest file

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

          <uses-sdk android:minSdkVersion="14" />
          <uses-permission android:name="android.permission.CALL_PHONE"/>
          <uses-permission android:name="android.permission.INTERNET"/>
          <application
              android:icon="@drawable/ic_launcher"
              android:label="@string/app_name" >
              <activity
                  android:label="@string/app_name"
                  android:name=".IntentsActivity" >
                  <intent-filter >
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
              <activity android:name=".MyBrowserActivity"
                        android:label="@string/app_name">
                  <intent-filter>
                      <action android:name="android.intent.action.VIEW" />
                      <action android:name="com.java2s.MyBrowser" />
                      <category android:name="android.intent.category.DEFAULT" />
                      <data android:scheme="http" />
                  </intent-filter>
              </activity>

          </application>

      </manifest>

Add the following statements to the MainActivity.java file:

//www  . j  a v a2s  .c o  m
package com.java2s.myapplication3.app;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
    int request_Code = 1;

    public void onClickLaunchMyBrowser(View view) {
        Intent i = new Intent("com.java2s.MyBrowser");
        i.setData(Uri.parse ("http://www.java2s.com"));
        startActivity(i);
    }

}

Add the following statements to the activity_main.xml file:

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

Add the following statements to the MyBrowserActivity.java file:

      import android.app.Activity;
      import android.net.Uri;
      import android.os.Bundle;
      import android.webkit.WebView;
      import android.webkit.WebViewClient;
/*from ww  w . ja va2  s  .  c  o m*/
      public class MyBrowserActivity extends Activity {
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.browser);

              Uri url = getIntent().getData();
              WebView webView = (WebView) findViewById(R.id.WebView01);
              webView.setWebViewClient(new Callback());
              webView.loadUrl(url.toString());
             }

             private class Callback extends WebViewClient {
                 @Override
                 public boolean shouldOverrideUrlLoading
                 (WebView view, String url) {
                     return(false);
                 }
             }
         }

Note

In the AndroidManifest.xml file you have the following definition.

...
                 <activity android:name=".MyBrowserActivity"
                           android:label="@string/app_name">
                     <intent-filter>
                         <action android:name="android.intent.action.VIEW" />
                         <action android:name="com.java2s.MyBrowser" />
                         <category android:name="android.intent.category.DEFAULT" />
                         <data android:scheme="http" />
                     </intent-filter>
                 </activity>
...

In the <intent-filter> element, you declared it to have two actions, one category, and one data.

This means that all other activities can invoke this activity using either the "android.intent.action.VIEW" or the "com.java2s.MyBrowser" action.

Activities need to have the "android.intent.category.DEFAULT" category in order to call the startActivity() or startActivityForResult() methods.

The <data> element specifies the type of data expected by the activity. The code above expects the data to start with the "http://" prefix.

Note 2

The preceding intent filter could also be rewritten as follows:

                 <activity android:name=".MyBrowserActivity"
                           android:label="@string/app_name">
                     <intent-filter>
                         <action android:name="android.intent.action.VIEW" />
                         <category android:name="android.intent.category.DEFAULT" />
                         <data android:scheme="http" />
                     </intent-filter>
                     <intent-filter>
                         <action android:name="com.java2s.MyBrowser" />
                         <category android:name="android.intent.category.DEFAULT" />
                       <data android:scheme="http" />
                   </intent-filter>
               </activity>

The intent filter in this way is much more readable, and it logically groups the action, category, and data within an intent filter.

Note 3

Suppose we create an Intent as follows:

Intent i = new Intent(android.content.Intent.ACTION_VIEW,
                      Uri.parse ("http://www.java2s.com"));

Android will display a selection.

You can choose between using the Browser application or the Intents application that you are currently building.

When multiple activities match your Intent object, the dialog titled "Complete action using" appears.

You can customize this by using the createChooser() method from the Intent class, like this:

Intent i = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse ("http://www.amazon.com"));
startActivity(Intent.createChooser(i, "Open URL using..."));

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent Share a message with friends

Intent (148/474)
« Previous

Use Intent Share a message with friends

Description

The following code shows how to Use Intent Share a message with friends.

Example

Main layout xml file

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

Main Activity Java code

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
/*from w w  w  .  j  a v  a 2  s.c  o m*/
public class MainActivity extends Activity {

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

        shareContent("Check this out!");
    }

    private void shareContent(String update) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, update);
        startActivity(Intent.createChooser(intent, "Share..."));
    }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to do Speech Recognize

Intent (150/474)
« Previous

Use Intent to do Speech Recognize

Description

The following code shows how to Use Intent to do Speech Recognize.

Example

Register permission for RECORD_AUDIO.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main activity Java code

package com.java2s.myapplication3.app;
//from  w ww . j a  v a 2  s.  c o m
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int REQUEST_RECOGNIZE = 100;

    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv = new TextView(this);
        setContentView(tv);

        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Tell Me Your Name");
        try {
            startActivityForResult(intent, REQUEST_RECOGNIZE);
        } catch (ActivityNotFoundException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Not Available");
            builder.setMessage("There is currently no recognition software installed.  Would you like to download one?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Download, for example, Google Voice Search
                    Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                    marketIntent.setData(Uri.parse("market://details?id=com.google.android.voicesearch"));
                }
            });
            builder.setNegativeButton("No", null);
            builder.create().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_RECOGNIZE && resultCode == Activity.RESULT_OK) {
            ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            StringBuilder sb = new StringBuilder();
            for(String piece : matches) {
                sb.append(piece);
                sb.append('\n');
            }
            tv.setText(sb.toString());
        } else {
            Toast.makeText(this, "Operation Canceled", Toast.LENGTH_SHORT).show();
        }
    }
}
Use Intent to do Speech Recognize

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to get content and pick video

Intent (151/474)
« Previous

Use Intent to get content and pick video

Description

The following code shows how to Use Intent to get content and pick video.

Example

Main layout xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Button
        android:id="@+id/button_select"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pick Video"
        android:onClick="onSelectClick" />
    <TextView
        android:id="@+id/text_metadata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button_select"
        android:layout_margin="15dp" />
    <ImageView
        android:id="@+id/image_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp" />
</RelativeLayout>

Java code for main activity

package com.java2s.myapplication3.app;
/* w  ww.j a v  a 2  s.  c  o m*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
    private static final int PICK_VIDEO = 100;

    private ImageView mFrameView;
    private TextView mMetadataView;

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

        mFrameView = (ImageView) findViewById(R.id.image_frame);
        mMetadataView = (TextView) findViewById(R.id.text_metadata);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_VIDEO && resultCode == RESULT_OK && data != null) {
            Uri video = data.getData();
            MetadataTask task = new MetadataTask(this, mFrameView, mMetadataView);
            task.execute(video);
        }
    }

    public void onSelectClick(View v) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        startActivityForResult(intent, PICK_VIDEO);
    }

    public static class MetadataTask extends AsyncTask<Uri, Void, Bundle> {
        private Context mContext;
        private ImageView mFrame;
        private TextView mMetadata;
        private ProgressDialog mProgress;

        public MetadataTask(Context context, ImageView frame, TextView metadata) {
            mContext = context;
            mFrame = frame;
            mMetadata = metadata;
        }

        @Override
        protected void onPreExecute() {
            mProgress = ProgressDialog.show(mContext, "", "Analyzing Video File...", true);
        }

        @Override
        protected Bundle doInBackground(Uri... params) {
            Uri video = params[0];
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(mContext, video);

            Bitmap frame = retriever.getFrameAtTime();

            String date = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE);
            String duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);

            Bundle result = new Bundle();
            result.putParcelable("frame", frame);
            result.putString("date", date);
            result.putString("duration", duration);
            result.putString("width", width);
            result.putString("height", height);

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            if (mProgress != null) {
                mProgress.dismiss();
                mProgress = null;
            }

            Bitmap frame = result.getParcelable("frame");
            mFrame.setImageBitmap(frame);
            String metadata = String.format("Video Date: %s\nVideo Duration: %s\nVideo Size: %s x %s",
                    result.getString("date"),
                    result.getString("duration"),
                    result.getString("width"),
                    result.getString("height"));
            mMetadata.setText(metadata);
        }
    }

}
Use Intent to get content and pick video

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to Get Media content

Intent (149/474)
« Previous

Use Intent to Get Media content

Description

The following code shows how to Use Intent to Get Media content.

Example

Register permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.mediastore"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4"
        android:targetSdkVersion="19" />

    <!-- Necessary for constructing a MediaStore Uri on external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

Main layout xml file

<?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" >
    <Button
        android:id="@+id/imageButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Images" />
    <Button
        android:id="@+id/videoButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Video" />
    <Button
        android:id="@+id/audioButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Audio" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/*ww  w.j a  va2 s. com*/
public class MainActivity extends Activity implements View.OnClickListener {

    private static final int REQUEST_AUDIO = 1;
    private static final int REQUEST_VIDEO = 2;
    private static final int REQUEST_IMAGE = 3;

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

        Button images = (Button)findViewById(R.id.imageButton);
        images.setOnClickListener(this);
        Button videos = (Button)findViewById(R.id.videoButton);
        videos.setOnClickListener(this);
        Button audio = (Button)findViewById(R.id.audioButton);
        audio.setOnClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == Activity.RESULT_OK) {
            //Uri to user selection returned in the Intent
            Uri selectedContent = data.getData();

            if(requestCode == REQUEST_IMAGE) {
                //Pass an InputStream to BitmapFactory
            }
            if(requestCode == REQUEST_VIDEO) {
                //Pass the Uri or a FileDescriptor to MediaPlayer
            }
            if(requestCode == REQUEST_AUDIO) {
                //Pass the Uri or a FileDescriptor to MediaPlayer
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        //Only return files to which we can open a stream
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        //Set correct MIME type and launch
        switch(v.getId()) {
        case R.id.imageButton:
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_IMAGE);
            return;
        case R.id.videoButton:
            intent.setType("video/*");
            startActivityForResult(intent, REQUEST_VIDEO);
            return;
        case R.id.audioButton:
            intent.setType("audio/*");
            startActivityForResult(intent, REQUEST_AUDIO);
            return;
        default:
            return;
        }
    }
}
Use Intent to Get Media content

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to launch another activity to play m4v file

Intent (152/474)
« Previous

Use Intent to launch another activity to play m4v file

Description

The following code shows how to Use Intent to launch another activity to play m4v file.

Example

Manifext xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.matchmaker"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="3" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".RootActivity"
                  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=".PlayerActivity">
            <intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <data android:mimeType="video/h264" />
            </intent-filter>
            <intent-filter>
              <action android:name="com.examples.myplayer.PLAY" />
              <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Main layout xml file

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

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
//ww w. ja  v a  2s  . c om
public class MainActivity extends Activity implements View.OnClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = new Button(this);
        button.setOnClickListener(this);
        setContentView(button);
    }

    @Override
    public void onClick(View v) {
//        Intent intent = new Intent();
//        intent.setAction(PlayerActivity.ACTION_PLAY);
//        startActivity(intent);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file:///android_asset/movie.m4v"), "video/h264");
        startActivity(Intent.createChooser(intent, "Play Video"));
    }
}

Second activity Java code

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
/*from ww  w. ja  v  a  2 s  .  c  om*/
public class PlayerActivity extends Activity {

    public static final String ACTION_PLAY = "com.examples.myplayer.PLAY";

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

        Intent incoming = getIntent();

        Uri videoUri = incoming.getData();

        String title;
        if(incoming.hasExtra(Intent.EXTRA_TITLE)) {
            title = incoming.getStringExtra(Intent.EXTRA_TITLE);
        } else {
            title = "";
        }

        Log.i("PLAYER", "Begin playing the video and displaying the title");
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to pick contact People

Intent (153/474)
« Previous

Use Intent to pick contact People

Description

The following code shows how to Use Intent to pick contact People.

Example

Main Activity Java code

package com.java2s.myapplication4.app;
//from w w  w  . jav a2s .co m
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Contacts;
import android.view.Menu;

public class MainActivity extends Activity {

    private Intent contactIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        contactIntent = new Intent();
        contactIntent.setAction(Intent.ACTION_PICK);
        contactIntent.setData(Contacts.People.CONTENT_URI);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Contacts").setIntent(contactIntent);
        return true;
    }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to send email with attachment

Intent (156/474)
« Previous

Use Intent to send email with attachment

Description

The following code shows how to Use Intent to send email with attachment.

Example

Main Activity Java code

// w w  w  .  j  ava 2 s. co  m
import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.view.Menu;

public class MainActivity extends Activity {

    private Intent mailIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mailIntent = new Intent();
        mailIntent.setAction(Intent.ACTION_SEND);
        mailIntent.setType("message/rfc822");
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"recipient@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_CC, new String[] {"carbon@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_BCC, new String[] {"blind@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
        mailIntent.putExtra(Intent.EXTRA_TEXT, "Body Text");
        mailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileOne.txt")));
        /*Block for sending multiple attachments
        mailIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        mailIntent.setType("message/rfc822");
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"recipient@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_CC, new String[] {"carbon@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_BCC, new String[] {"blind@gmail.com"});
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
        mailIntent.putExtra(Intent.EXTRA_TEXT, "Body Text");
        ArrayList<Uri> files = new ArrayList<Uri>();
        files.add(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileOne.txt")));
        files.add(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"fileTwo.txt")));
        //...
        mailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
        */

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Mail").setIntent(Intent.createChooser(mailIntent, "Mail Client"));
        return true;
    }

}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to send SMS message

Intent (155/474)
« Previous

Use Intent to send SMS message

Description

The following code shows how to Use Intent to send SMS message.

Example

Main Activity Java code

import java.io.File;
import java.util.ArrayList;
/*from   ww w  .  j  a va  2  s . c o  m*/
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Contacts;
import android.view.Menu;

public class MainActivity extends Activity {

    private Intent smsIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        smsIntent = new Intent();
        smsIntent.setAction(Intent.ACTION_VIEW);
        smsIntent.setType("vnd.android-dir/mms-sms");
        smsIntent.putExtra("address", "8885551234");
        smsIntent.putExtra("sms_body", "SMS Body");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("SMS").setIntent(smsIntent);
        return true;
    }

}
Use Intent to send SMS message

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to start your service

Intent (154/474)
« Previous

Use Intent to start your service

Description

The following code shows how to Use Intent to start your service.

Example

Populate the MyService.java file with the following code:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
//ww  w  .ja  v  a  2  s.  c  om
public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        Toast.makeText (this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText (this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService">
         <intent-filter>
            <action android:name="com.java2s.MyService" />
         </intent-filter>
     </service>
 </application>

</manifest>

Main layout xml file

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

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/*from  ww  w  . j  a v a 2  s  .  co m*/
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
        //startService(new Intent(getBaseContext(), MyService.class));
        //OR
        startService(new Intent("com.java2s.MyService"));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}

Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Intent to view PDF file

Intent (157/474)
« Previous

Use Intent to view PDF file

Description

The following code shows how to Use Intent to view PDF file.

Example

Main layout xml file

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

Main Activity Java code

package com.java2s.myapplication4.app;
/*from w  w  w . j  a  va2  s .  co  m*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import java.io.File;

public class MainActivity extends Activity {

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

        //Create a Uri for files on external storage
        File externalFile = new
                File(Environment.getExternalStorageDirectory(), "yourPDF.pdf");
        Uri external = Uri.fromFile(externalFile);
        viewPdf(external);

    }

    private void viewPdf(Uri file) {
        Intent intent;
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(file, "application/pdf");
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("No Application Found");
            builder.setMessage("We could not find an application on your device to view PDFs.  Would you like to download one from Android Market?");
            builder.setPositiveButton("Yes, Please",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                            marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader"));
                            startActivity(marketIntent);
                        }
                    });
            builder.setNegativeButton("No, Thanks", null);
            builder.create().show();
        }
    }
}
Use Intent to view PDF file

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use LayoutTransition

Layout (364/474)
« Previous

Use LayoutTransition

Description

The following code shows how to Use LayoutTransition.

Example

Main layout xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="19dp"
        android:onClick="onClick"
        android:text="Button" />

</LinearLayout>

Menu main.xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_settings"
        android:title="menu_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
</menu>

Main Activity Java code

import android.animation.LayoutTransition;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/*w  w w .ja  v a  2s .c o m*/
public class MainActivity extends Activity {

  private ViewGroup viewGroup;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LayoutTransition l = new LayoutTransition();
    l.enableTransitionType(LayoutTransition.CHANGING);
    viewGroup = (ViewGroup) findViewById(R.id.container);
    viewGroup.setLayoutTransition(l);

  }

  public void onClick(View view) {
    viewGroup.addView(new Button(this));
  }

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

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use LinearLayout to layout common controls

Layout (346/474)
« Previous

Use LinearLayout to layout common controls

Description

The following code shows how to Use LinearLayout to layout common controls.

  • Button - Represents a push-button widget
  • ImageButton - Button view displays an image
  • EditText - Subclass TextView view to support editing its text content
  • CheckBox - Button that has two states: checked or unchecked
  • RadioGroup and RadioButton - The RadioButton has two states: checked or unchecked. A RadioGroup is used to group together one or more RadioButton views, allowing only one RadioButton to be checked within the RadioGroup.
  • ToggleButton - Displays checked/unchecked states using a light indicator

Example

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<Button android:id="@+id/btnSave"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="save" />

<Button android:id="@+id/btnOpen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Open" />

<ImageButton android:id="@+id/btnImg1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher" />

<EditText android:id="@+id/txtName"
    android:layout_width="fill_parent"
       android:layout_height="wrap_content" />

   <CheckBox android:id="@+id/chkAutosave"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="Autosave" />

   <CheckBox android:id="@+id/star"
       style="?android:attr/starStyle"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />

   <RadioGroup android:id="@+id/rdbGp1"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical" >

       <RadioButton android:id="@+id/rdb1"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="Option 1" />

       <RadioButton android:id="@+id/rdb2"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="Option 2" />

   </RadioGroup>

   <ToggleButton android:id="@+id/toggle1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />

</LinearLayout>

Java code

// ww w . j  av a  2s  . com
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnOpen = (Button) findViewById(R.id.btnOpen);
        btnOpen.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                DisplayToast("You have clicked the Open button");
            }
        });

        Button btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v) {
                DisplayToast("You have clicked the Save button");
            }
        });

        CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave);
        checkBox.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v) {
              if (((CheckBox)v).isChecked())
                  DisplayToast("CheckBox is checked");
              else
                  DisplayToast("CheckBox is unchecked");
          }
      });

      RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
      radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
      {
          public void onCheckedChanged(RadioGroup group, int checkedId) {
              RadioButton rb1 = (RadioButton) findViewById(R.id.rdb1);
              if (rb1.isChecked()) {
                  DisplayToast("Option 1 checked!");
              } else {
                  DisplayToast("Option 2 checked!");
              }
          }
      });

      ToggleButton toggleButton =
              (ToggleButton) findViewById(R.id.toggle1);
      toggleButton.setOnClickListener(new View.OnClickListener()
      {
          public void onClick(View v) {
              if (((ToggleButton)v).isChecked())
                  DisplayToast("Toggle button is On");
              else
                  DisplayToast("Toggle button is Off");
          }
      });
  }

  private void DisplayToast(String msg)
  {
      Toast.makeText (getBaseContext(), msg,
              Toast.LENGTH_SHORT).show();
  }

}
Use LinearLayout to layout common controls

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use LinearLayout to layout widgets

Layout (347/474)
« Previous

Use LinearLayout to layout widgets

Description

The following code shows how to use LinearLayout to layout widgets.

Example

Add the following code in bold to the res/layout/ your main xml file for layout:

<?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" >
// w  w w  . jav a2 s . c  om
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is my first Android Application!" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="And this is a clickable button!" />

</LinearLayout>

Java code

package com.java2s.app;
// w w  w .  ja  v  a  2 s . c  o  m
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

    }

}
Use LinearLayout to layout widgets

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use LinkMovementMethod in hyper link

TextView (427/474)
« Previous

Use LinkMovementMethod in hyper link

Description

The following code shows how to use LinkMovementMethod in hyper link.

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/my_text_view_html"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/my_text_view_spannable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/my_text_view_html"
        android:layout_below="@+id/my_text_view_html" />

</RelativeLayout>

Java code

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
//from  w ww. j  a  v  a 2s.  c o m
public class MainActivity extends Activity {

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

    final TextView textView1 = (TextView) findViewById(R.id.my_text_view_html);
    textView1.setText(Html.fromHtml("a string from http://java2s.com"));
    textView1.setMovementMethod(LinkMovementMethod.getInstance());

    final Spannable text2 = new SpannableString(getString(R.string.text2));
    text2.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
    text2.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 9, 0);

    ((TextView) findViewById(R.id.my_text_view_spannable)).setText(text2);
  }
}
Use LinkMovementMethod in hyper link

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use location service

Location (163/474)
« Previous

Use location service

Description

The following code shows how to Use location service.

Example

Register permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.examples.service"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="1" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ServiceActivity"
                  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=".MyService"></service>
    </application>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
</manifest>

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/enable"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Tracking"
  />
  <Button
    android:id="@+id/disable"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Tracking"
  />
  <TextView
    android:id="@+id/status"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

Main Activity Java code

package com.java2s.myapplication4.app;
/*  w w w . ja  va2 s.c  om*/
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;

public class MainActivity extends Activity implements View.OnClickListener {

    Button enableButton, disableButton;
    TextView statusView;

    MyService trackerService;
    Intent serviceIntent;

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

        enableButton = (Button)findViewById(R.id.enable);
        enableButton.setOnClickListener(this);
        disableButton = (Button)findViewById(R.id.disable);
        disableButton.setOnClickListener(this);
        statusView = (TextView)findViewById(R.id.status);

        serviceIntent = new Intent(this, MyService.class);
    }

    @Override
    public void onResume() {
        super.onResume();
        //Starting the service makes it stick, regardless of bindings
        startService(serviceIntent);
        //Bind to the service
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onPause() {
        super.onPause();
        if(!trackerService.isTracking()) {
            //Stopping the service let's it die once unbound
            stopService(serviceIntent);
        }
        //Unbind from the service
        unbindService(serviceConnection);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.enable:
                trackerService.startTracking();
                break;
            case R.id.disable:
                trackerService.stopTracking();
                break;
            default:
                break;
        }
        updateStatus();
    }

    private void updateStatus() {
        if(trackerService.isTracking()) {
            statusView.setText(String.format("Tracking enabled.  %d locations logged.",trackerService.getLocationsCount()));
        } else {
            statusView.setText("Tracking not currently enabled.");
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            trackerService = ((MyService.TrackerBinder)service).getService();
            updateStatus();
        }

        public void onServiceDisconnected(ComponentName className) {
            trackerService = null;
        }
    };
}

Service Java code

import java.util.ArrayList;
// w  ww  .  j a  v a 2s . c  om
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service implements LocationListener {

    private static final String LOGTAG = "TrackerService";

    private LocationManager manager;
    private ArrayList<Location> storedLocations;

    private boolean isTracking = false;

    /* Service Setup Methods */
    @Override
    public void onCreate() {
        manager = (LocationManager)getSystemService(LOCATION_SERVICE);
        storedLocations = new ArrayList<Location>();
        Log.i(LOGTAG, "Tracking Service Running...");
    }

    public void startTracking() {
        if(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            return;
        }
        Toast.makeText(this, "Starting Tracker", Toast.LENGTH_SHORT).show();
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);

        isTracking = true;
    }

    public void stopTracking() {
        Toast.makeText(this, "Stopping Tracker", Toast.LENGTH_SHORT).show();
        manager.removeUpdates(this);
        isTracking = false;
    }

    public boolean isTracking() {
        return isTracking;
    }

    @Override
    public void onDestroy() {
        manager.removeUpdates(this);
        Log.i(LOGTAG, "Tracking Service Stopped...");
    }

    /* Service Access Methods */
    public class TrackerBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    private final IBinder binder = new TrackerBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public int getLocationsCount() {
        return storedLocations.size();
    }

    public ArrayList<Location> getLocations() {
        return storedLocations;
    }

    /* LocationListener Methods */
    @Override
    public void onLocationChanged(Location location) {
        Log.i("TrackerService", "Adding new location");
        storedLocations.add(location);
    }

    @Override
    public void onProviderDisabled(String provider) { }

    @Override
    public void onProviderEnabled(String provider) { }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) { }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use MultiAutoCompleteTextView

TextView (438/474)
« Previous

Use MultiAutoCompleteTextView

Description

AutoCompleteTextView control offers suggestions only for the entire text in the text view. If you type a sentence, you don't get suggestions for each word.

You can use the MultiAutoCompleteTextView to provide suggestions as the user types.

The MultiAutoCompleteTextView control requires that you give it a tokenizer that can parse the sentence and tell it whether to start suggesting again.

Example

The following code shows how to use the MultiAutoCompleteTextView.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//from   ww w. ja  v a  2  s  . c  o m
    <MultiAutoCompleteTextView
        android:id="@+id/mactv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Java code

package com.java2s.app;
// w ww . j a v  a2  s .com
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.MultiAutoCompleteTextView;

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

        MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) this.findViewById(R.id.mactv);
        ArrayAdapter<String> aa2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
                new String[]{"English", "Hebrew", "Hindi", "Spanish", "German", "Greek"});

        mactv.setAdapter(aa2);

        mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
    }

}

Because of the CommaTokenizer, after a comma is typed into the EditText field, the field will again make suggestions using the array of strings. Any other characters typed in will not trigger the field to make suggestions.

Android provides another tokenizer for e-mail addresses called Rfc822Tokenizer.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use multiple string resource files

Resources (28/474)
« Previous

Use multiple string resource files

Description

To see that multiple string resource files are allowed in this subdirectory, you can place another file with the following content in the same subdirectory and call it strings1.xml.

Example

We can have one string resourde defined as follows.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">hello</string>
    <string name="app_name">hello appname</string>
</resources>

Example of an Additional strings.xml File.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello1">hello 1</string>
    <string name="app_name1">hello appname 1</string>
</resources>

The Eclipse ADT plug-in validates the uniqueness of these IDs at compile time and places them in R.java as two additional constants: R.string.hello1 and R.string.app_name1.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Near Field Communication

Network (186/474)
« Previous

Use Near Field Communication

Description

The following code shows how to Use Near Field Communication.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.NFC" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".NfcActivity"
            android:label="NfcActivity"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="application/com.example.androidrecipes.beamtext" />
            </intent-filter>
        </activity>
        <activity
            android:name=".BeamActivity"
            android:label="BeamActivity"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>
    </application>

</manifest>

res\layout\main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Image"
        android:onClick="onSelectClick" />
    <TextView
        android:id="@+id/text_uri"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/image_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="center" />
</LinearLayout>

BeamActivity.java

//from   w  w  w .  j a v  a  2  s . c o m
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateBeamUrisCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class BeamActivity extends Activity implements CreateBeamUrisCallback, OnNdefPushCompleteCallback {
    private static final String TAG = "NfcBeam";
    private static final int PICK_IMAGE = 100;

    private NfcAdapter mNfcAdapter;
    private Uri mSelectedImage;

    private TextView mUriName;
    private ImageView mPreviewImage;

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

        mUriName = (TextView) findViewById(R.id.text_uri);
        mPreviewImage = (ImageView) findViewById(R.id.image_preview);

        // Check for available NFC Adapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            mUriName.setText("NFC is not available on this device.");
        } else {
            // Register callback to set NDEF message
            mNfcAdapter.setBeamPushUrisCallback(this, this);
            // Register callback to listen for message-sent success
            mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            mUriName.setText( data.getData().toString() );
            mSelectedImage = data.getData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // Check to see that the Activity started due to an Android Beam
        if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }

    void processIntent(Intent intent) {
        Uri data = intent.getData();
        if(data != null) {
            mPreviewImage.setImageURI(data);
        } else {
            mUriName.setText("Received Invalid Image Uri");
        }
    }

    public void onSelectClick(View v) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE);
    }

    @Override
    public Uri[] createBeamUris(NfcEvent event) {
        if (mSelectedImage == null) {
            return null;
        }
        return new Uri[] {mSelectedImage};
    }

    @Override
    public void onNdefPushComplete(NfcEvent event) {
        Log.i(TAG, "Push Complete!");
    }
}

NfcActivity.java

import java.util.Date;
/* ww w . j  a  va2s . c o m*/
import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.TextView;

public class NfcActivity extends Activity implements
        CreateNdefMessageCallback, OnNdefPushCompleteCallback {
    private static final String TAG = "NfcBeam";
    private NfcAdapter mNfcAdapter;
    private TextView mDisplay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDisplay = new TextView(this);
        setContentView(mDisplay);

        // Check for available NFC Adapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            mDisplay.setText("NFC is not available on this device.");
        } else {
            // Register callback to set NDEF message.  Setting this makes
            // NFC data push active while the Activity is in the foreground.
            mNfcAdapter.setNdefPushMessageCallback(this, this);
            // Register callback to listen for message-sent success
            mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // Check to see if a Beam launched this Activity
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }

    void processIntent(Intent intent) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        mDisplay.setText(new String(msg.getRecords()[0].getPayload()));
    }

    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        String text = String.format("Sending A Message From Android Recipes at %s",
                DateFormat.getTimeFormat(this).format(new Date()));
        NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                "application/com.example.androidrecipes.beamtext", text.getBytes())
         /**
          * The Android Application Record (AAR) is commented out. When a device
          * receives a push with an AAR in it, the application specified in the AAR
          * is guaranteed to run. The AAR overrides the tag dispatch system.
          * You can add it back in to guarantee that this
          * activity starts when receiving a beamed message. For now, this code
          * uses the tag dispatch system.
          */
          //,NdefRecord.createApplicationRecord("com.examples.nfcbeam")
        );
        return msg;
    }

    @Override
    public void onNdefPushComplete(NfcEvent event) {
        //This callback happens on a binder thread, don't update
        // the UI directly from this method.
        Log.i(TAG, "Message Sent!");
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ObjectAnimator

Animation (238/474)
« Previous

Use ObjectAnimator

Description

The following code shows how to Use ObjectAnimator.

Example

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <ImageView
    android:id="@+id/flip_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
  />
</RelativeLayout>

Main Activity Java code

package com.java2s.myapplication3.app;
/*ww w .  ja  va 2  s  .  co m*/
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;

public class MainActivity extends Activity {

    boolean isHeads;
    ObjectAnimator flipper;
    Bitmap headsImage, tailsImage;
    ImageView flipImage;

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

        headsImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        tailsImage = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

        flipImage = (ImageView)findViewById(R.id.flip_image);
        flipImage.setImageBitmap(headsImage);
        isHeads = true;

        flipper = ObjectAnimator.ofFloat(flipImage, "rotationY", 0f, 360f);
        flipper.setDuration(1500);
        flipper.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (animation.getAnimatedFraction() >= 0.25f && isHeads) {
                    flipImage.setImageBitmap(tailsImage);
                    isHeads = false;
                }
                if (animation.getAnimatedFraction() >= 0.75f && !isHeads) {
                    flipImage.setImageBitmap(headsImage);
                    isHeads = true;
                }
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            if (flipper.isPaused()) {
                flipper.resume();
            } else {
                flipper.start();
            }
            return true;
        }
        if(event.getAction() == MotionEvent.ACTION_UP) {
            flipper.pause();
            return true;
        }
        return super.onTouchEvent(event);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use PagerAdapter to display Image

ImageView (334/474)
« Previous

Use PagerAdapter to display Image

Description

The following code shows how to Use PagerAdapter to display Image.

Example

import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
//from  ww  w .  j a  v a 2s.  c o m
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewPager pager = new ViewPager(this);
        pager.setAdapter(new ImagePagerAdapter(this));

        setContentView(pager);
    }
}

class ImagePagerAdapter extends PagerAdapter {
    private Context mContext;

    private static final int[] IMAGES = {
        android.R.drawable.ic_menu_camera,
        android.R.drawable.ic_menu_add,
        android.R.drawable.ic_menu_delete,
        android.R.drawable.ic_menu_share,
        android.R.drawable.ic_menu_edit
    };

    private static final int[] COLORS = {
        Color.RED,
        Color.BLUE,
        Color.GREEN,
        Color.GRAY,
        Color.MAGENTA
    };

    public ImagePagerAdapter(Context context) {
        super();
        mContext = context;
    }
    @Override
    public int getCount() {
        return 5;
    }
    @Override
    public float getPageWidth(int position) {
        return 0.333f;
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView iv = new ImageView(mContext);

        iv.setImageResource(IMAGES[position]);
        iv.setBackgroundColor(COLORS[position]);

        container.addView(iv);
        return iv;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == object);
    }

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use PendingIntent to create Notification

Intent (144/474)
« Previous

Use PendingIntent to create Notification

Description

The following code shows how to Use PendingIntent to create Notification.

Example

Add activity to the manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest...
    <application android:label="@string/app_name">

        <activity android:name=".SecondActivity" android:label="@string/app_name">
        </activity>
    </application>
</manifest>

Layout for main activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button android:id="@+id/notify"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight="1"
      android:text="Click to raise a notification in 5 seconds"
      />
  <Button android:id="@+id/cancel"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight="1"
      android:text="Click to clear the notification"
      />
</LinearLayout>

Java code

/***//ww w .ja  v a  2 s  .  c  o m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
  private static final int NOTIFY_ME_ID=1337;
  private Timer timer=new Timer();
  private int count=0;

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

    Button btn=(Button)findViewById(R.id.notify);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        TimerTask task=new TimerTask() {
          public void run() {
            notifyMe();
          }
        };
        timer.schedule(task, 5000);
      }
    });

    btn=(Button)findViewById(R.id.cancel);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        mgr.cancel(NOTIFY_ME_ID);
      }
    });
  }

  private void notifyMe() {
    final NotificationManager mgr= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Notification note=new Notification(R.drawable.red_ball,"Status message!",System.currentTimeMillis());
    PendingIntent i=PendingIntent.getActivity(this, 0,new Intent(this, SecondActivity.class),0);
    note.setLatestEventInfo(this, "Notification Title","This is the notification message", i);
    note.number=++count;

    mgr.notify(NOTIFY_ME_ID, note);
  }
}

Second activity

/***//ww  w  .j  av  a2s  .  c  o  m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

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

public class SecondActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView txt=new TextView(this);

    txt.setText("This is the message!");
    setContentView(txt);
  }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use PopupWindow

Dialog (285/474)
« Previous

Use PopupWindow

Description

The following code shows how to Use PopupWindow.

Example

res\layout\activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show PopupWindow"
        android:onClick="onShowWindowClick" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:text="Show PopupWindow"
        android:onClick="onShowWindowClick" />
</FrameLayout>

res\layout\popup.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is a PopupWindow" />
    <EditText
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Close" />
</LinearLayout>

menu main.xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <group
        android:id="@+id/group"
        android:checkableBehavior="all">
        <item
            android:id="@+id/menu_option_first"
            android:title="First Option"/>
        <item
            android:id="@+id/menu_option_second"
            android:title="Second Option"/>
    </group>
    <item
        android:id="@+id/menu_save"
        android:title="Save"/>
</menu>

MainActivity.java

package com.java2s.myapplication4.app;
//  w  w w  .  j ava  2 s  .  c om
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

public class MainActivity extends Activity implements View.OnTouchListener {

    PopupWindow mOverlay;

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

        View popupContent = getLayoutInflater().inflate(R.layout.popup, null);

        mOverlay = new PopupWindow();
        mOverlay.setWindowLayoutMode(WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);
        mOverlay.setWidth(350);
        mOverlay.setHeight(250);
        mOverlay.setContentView(popupContent);
        mOverlay.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));

    //    mOverlay.setAnimationStyle(R.style.PopupAnimation);
        mOverlay.setTouchInterceptor(this);
        //mOverlay.setOutsideTouchable(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mOverlay.dismiss();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    public void onShowWindowClick(View v) {
        if (mOverlay.isShowing()) {
            mOverlay.dismiss();
        } else {
            mOverlay.showAsDropDown(v);
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Raw Resources

Resources (40/474)
« Previous

Use Raw Resources

Description

Android allows raw files in addition to arbitrary XML files. These resources, placed in /res/raw folder.

The raw files could be audio, video, or text files that require localization or references through resource IDs.

These files are not compiled but are moved to the application package as they are.

Each file has an identifier generated in R.java.

Example

If you were to place a text file at /res/raw/test.txt, you would be able to read that file using the following code.

String getStringFromRawFile(Activity activity)
throws IOException{
   Resources r = activity.getResources();
   InputStream is = r.openRawResource(R.raw.test);
   String myText = workOnInputStream(is);
   is.close();/*ww w .j  a  v a  2 s  . c om*/
   return myText;
}

File names with duplicate base names generate a build error.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use RelativeLayout

Layout (350/474)
« Previous

Use RelativeLayout

Description

The following code shows how to use RelativeLayout.

Example

Layout xml

<RelativeLayout// w  ww  .  j  a  va 2  s  .com
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="5px">
  <TextView android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="URL:"
    android:paddingTop="15px"/>
  <EditText
    android:id="@+id/entry"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/label"
    android:layout_alignBaseline="@id/label"/>
  <Button
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/entry"
    android:layout_alignRight="@id/entry"
    android:text="OK" />
  <Button
    android:id="@+id/cancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/ok"
    android:layout_alignTop="@id/ok"
    android:text="Cancel" />
</RelativeLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
// www  . ja  v  a2  s  . c  o  m
public class RelativeLayoutDemo extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ScaleGestureDetector

Gesture (318/474)
« Previous

Use ScaleGestureDetector

Description

The following code shows how to Use ScaleGestureDetector.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

/*from  w w  w  .j  ava  2 s  .c om*/
import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.widget.ImageView;

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

public class ImageActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RotateZoomImageView imageView = new RotateZoomImageView(this);
        imageView.setImageResource(R.drawable.ic_launcher);

        setContentView(imageView);
    }
}
class RotateZoomImageView extends ImageView {

    private ScaleGestureDetector mScaleDetector;
    private Matrix mImageMatrix;
    /* Last Rotation Angle */
    private int mLastAngle = 0;
    /* Pivot Point for Transforms */
    private int mPivotX, mPivotY;

    public RotateZoomImageView(Context context) {
        super(context);
        init(context);
    }

    public RotateZoomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public RotateZoomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mScaleDetector = new ScaleGestureDetector(context, mScaleListener);

        setScaleType(ScaleType.MATRIX);
        mImageMatrix = new Matrix();
    }

    /*
     * Use onSizeChanged() to calculate values based on the view's size.
     * The view has no size during init(), so we must wait for this
     * callback.
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            //Shift the image to the center of the view
            int translateX = Math.abs(w - getDrawable().getIntrinsicWidth()) / 2;
            int translateY = Math.abs(h - getDrawable().getIntrinsicHeight()) / 2;
            mImageMatrix.setTranslate(translateX, translateY);
            setImageMatrix(mImageMatrix);
            //Get the center point for future scale and rotate transforms
            mPivotX = w / 2;
            mPivotY = h / 2;
        }
    }

    private SimpleOnScaleGestureListener mScaleListener = new SimpleOnScaleGestureListener() {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            // ScaleGestureDetector calculates a scale factor based on whether
            // the fingers are moving apart or together
            float scaleFactor = detector.getScaleFactor();
            //Pass that factor to a scale for the image
            mImageMatrix.postScale(scaleFactor, scaleFactor, mPivotX, mPivotY);
            setImageMatrix(mImageMatrix);

            return true;
        }
    };

    /*
     * Operate on two-finger events to rotate the image.
     * This method calculates the change in angle between the
     * pointers and rotates the image accordingly.  As the user
     * rotates their fingers, the image will follow.
     */
    private boolean doRotationEvent(MotionEvent event) {
        //Calculate the angle between the two fingers
        float deltaX = event.getX(0) - event.getX(1);
        float deltaY = event.getY(0) - event.getY(1);
        double radians = Math.atan(deltaY / deltaX);
        //Convert to degrees
        int degrees = (int)(radians * 180 / Math.PI);

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            //Mark the initial angle
            mLastAngle = degrees;
            break;
        case MotionEvent.ACTION_MOVE:
            // ATAN returns a converted value between -90deg and +90deg
            // which creates a point when two fingers are vertical where the
            // angle flips sign.  We handle this case by rotating a small amount
            // (5 degrees) in the direction we were traveling

            if ((degrees - mLastAngle) > 45) {
                //Going CCW across the boundary
                mImageMatrix.postRotate(-5, mPivotX, mPivotY);
            } else if ((degrees - mLastAngle) < -45) {
                //Going CW across the boundary
                mImageMatrix.postRotate(5, mPivotX, mPivotY);
            } else {
                //Normal rotation, rotate the difference
                mImageMatrix.postRotate(degrees - mLastAngle, mPivotX, mPivotY);
            }
            //Post the rotation to the image
            setImageMatrix(mImageMatrix);
            //Save the current angle
            mLastAngle = degrees;
            break;
        }

        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // We don't care about this event directly, but we declare
            // interest so we can get later multi-touch events.
            return true;
        }

        switch (event.getPointerCount()) {
        case 3:
            // With three fingers down, zoom the image
            // using the ScaleGestureDetector
            return mScaleDetector.onTouchEvent(event);
        case 2:
            // With two fingers down, rotate the image
            // following the fingers
            return doRotationEvent(event);
        default:
            //Ignore this event
            return super.onTouchEvent(event);
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ScrollView

Layout (356/474)
« Previous

Use ScrollView

Description

The following code shows how to use ScrollView.

Example

Layout xml

/*www . j a  va  2 s . c  o m*/
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <TableLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="0">
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#000000"/>
      <TextView android:text="#000000"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#440000" />
      <TextView android:text="#440000"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#884400" />
      <TextView android:text="#884400"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#aa8844" />
      <TextView android:text="#aa8844"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#ffaa88" />
      <TextView android:text="#ffaa88"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#ffffaa" />
      <TextView android:text="#ffffaa"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
    <TableRow>
      <View
        android:layout_height="80px"
        android:background="#ffffff" />
      <TextView android:text="#ffffff"
        android:paddingLeft="4px"
        android:layout_gravity="center_vertical" />
    </TableRow>
  </TableLayout>
</ScrollView>

Java code

import android.app.Activity;
import android.os.Bundle;
/*from   w ww  . j  ava 2 s  .c o m*/
public class ScrollViewDemo extends Activity {
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ShareActionProvider

Event (301/474)
« Previous

Use ShareActionProvider

Description

The following code shows how to Use ShareActionProvider.

Example

Main layout xml file

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

Menu xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_settings"
        android:showAsAction="never"
        android:title="Settings" />
    <item android:id="@+id/menu_share"
        android:showAsAction="ifRoom"
        android:title="Share"
        android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>

Main Activity Java code

package com.java2s.myapplication3.app;
/*from   w ww.j ava 2 s. c o m*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;

public class MainActivity extends Activity {

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

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

        //Find the item and set the share Intent
        MenuItem item = menu.findItem(R.id.menu_share);
        ShareActionProvider provider = (ShareActionProvider) item.getActionProvider();

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "Text Sharing Update");
        provider.setShareIntent(intent);

        return true;
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use SlidingDrawer

Layout (365/474)
« Previous

Use SlidingDrawer

Description

The following code shows how to Use SlidingDrawer.

Example

Main layout xml file

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

    <SlidingDrawer
        android:id="@+id/drawer"
        android:layout_width="320dip"
        android:layout_height="440dip"
        android:orientation="vertical"
        android:handle="@+id/handle"
        android:content="@+id/content">

        <ImageView
            android:id="@+id/handle"
            android:layout_width="48dip"
            android:layout_height="48dip"
            android:src="@drawable/ic_launcher"  />

        <AnalogClock android:id="@+id/content"
            android:background="#D0A0A0"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

    </SlidingDrawer>

</RelativeLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
/*  w ww  . j  a va 2  s.c o  m*/
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use SpannableString

TextView (428/474)
« Previous

Use SpannableString

Description

The following code shows how to use SpannableString.

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/my_text_view_html"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/my_text_view_spannable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/my_text_view_html"
        android:layout_below="@+id/my_text_view_html" />

</RelativeLayout>

Java code

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
//from  w w w  .ja va  2 s  .co  m
public class MainActivity extends Activity {

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

    final TextView textView1 = (TextView) findViewById(R.id.my_text_view_html);
    textView1.setText(Html.fromHtml("a string from http://java2s.com"));
    textView1.setMovementMethod(LinkMovementMethod.getInstance());

    final Spannable text2 = new SpannableString(getString(R.string.text2));
    text2.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
    text2.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 9, 0);

    ((TextView) findViewById(R.id.my_text_view_spannable)).setText(text2);
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use Static Resources

Resources (42/474)
« Previous

Use Static Resources

Description

Here is the three steps to use static resource:

  • Put files to your package's res/raw folder
  • Use the getResources() method from the Activity class to return a Resources object
  • Use its openRawResource() method to open the file contained in the res/raw folder

Example

package com.java2s.myapplication3.app;
//from   w  w  w. j a v  a2 s  .  com
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends Activity {
    EditText textBox;
    static final int READ_BLOCK_SIZE = 100;

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

        textBox = (EditText) findViewById(R.id.txtText1);

        InputStream is = this.getResources().openRawResource(R.raw.textfile);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str = null;
        try {
            while ((str = br.readLine()) != null) {
                Toast.makeText(getBaseContext(),
                        str, Toast.LENGTH_SHORT).show();
            }
            is.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Note

The resource ID of the resource stored in the res/raw folder is named after its filename without its extension. For example, if the text file is textfile.txt, then its resource ID is R.raw.textfile.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use string resource in layout resource

Resources (36/474)
« Previous

Use string resource in layout resource

Description

Once you've defined the strings as resources, you can set them directly on a view.

Example

The following example shows an example where an HTML string is set as the text content of a TextView.

The following code is for string.xml.

<resources>
    <string name="simple_string">simple string</string>
    <string name="tagged_string">
         Hello <b><i>Slanted Android</i></b>, You are bold.
    </string>
</resources>

The following code is for layout.xml.

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_horizontal"
          android:text="@string/tagged_string"/>

The TextView automatically realizes that this string is an HTML string and honors its formatting accordingly.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use SurfaceView to display camera preview

Camera (83/474)
« Previous

Use SurfaceView to display camera preview

Description

The following code shows how to Use SurfaceView to display camera preview.

Example

Register permission for camera.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout activity_main.xml

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

Main activity Java code

package com.java2s.myapplication3.app;
//  ww w  . j  av a2s . co  m
import java.util.List;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    Camera mCamera;
    SurfaceView mPreview;

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

        mPreview = (SurfaceView)findViewById(R.id.preview);
        mPreview.getHolder().addCallback(this);
        mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mCamera = Camera.open();
    }

    @Override
    public void onPause() {
        super.onPause();
        mCamera.stopPreview();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCamera.release();
    }
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Camera.Parameters params = mCamera.getParameters();
        List<Camera.Size> sizes = params.getSupportedPreviewSizes();
        Camera.Size selected = sizes.get(0);
        params.setPreviewSize(selected.width,selected.height);
        mCamera.setParameters(params);

        mCamera.startPreview();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera.setPreviewDisplay(mPreview.getHolder());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i("PREVIEW","surfaceDestroyed");
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use TabHost

Tab (420/474)
« Previous

Use TabHost

Description

The following code shows how to use TabHost.

Example

Add activity to the manifest xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.java2s.android.activities"
      android:versionCode="1"
      android:versionName="1.0.0">
  <uses-permission android:name="android.permission.INTERNET" />
  <application android:label="@string/app_name">
    <activity android:name=".IntentTabDemo"
          android:label="@string/app_name">
      <intent-filter>// w  w  w .  j a va 2  s  .  c om
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name=".MyBrowser" />
    <activity android:name=".AndroidBrowser" />
  </application>
</manifest>

Java code

import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TabHost;
//  w ww .  j  a va  2s .c o  m
public class IntentTabDemo extends TabActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TabHost host=getTabHost();

    host.addTab(host.newTabSpec("one")
            .setIndicator("CW")
            .setContent(new Intent(this, MyBrowser.class)));
    host.addTab(host.newTabSpec("two")
            .setIndicator("Android")
            .setContent(new Intent(this, AndroidBrowser.class)));
  }
}

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;

public class MyBrowser extends Activity {
  WebView browser;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    browser=new WebView(this);
    setContentView(browser);
    browser.loadUrl("http://java2s.com");
  }
}

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;

public class AndroidBrowser extends Activity {
  WebView browser;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    browser=new WebView(this);
    setContentView(browser);
    browser.loadUrl("http://code.google.com/android");
  }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use TextSwitcher with animation

TextView (433/474)
« Previous

Use TextSwitcher with animation

Description

The following code shows how to Use TextSwitcher with animation.

Example

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

    <TextSwitcher
        android:id="@+id/your_textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="onSwitchText"
        android:text="Click me" />

</RelativeLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
/*from w w w  .  j  a v  a  2  s .  c  o m*/
public class MainActivity extends Activity {

  private static final String[] TEXTS = { "First", "Second", "Third" };
  private int mTextsPosition = 0;
  private TextSwitcher mTextSwitcher;

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

    mTextSwitcher = (TextSwitcher) findViewById(R.id.your_textview);

    mTextSwitcher.setFactory(new ViewFactory() {
      @Override
      public View makeView() {
        TextView t = new TextView(MainActivity.this);
        t.setGravity(Gravity.CENTER);
        return t;
      }
    });

    mTextSwitcher.setInAnimation(this, android.R.anim.fade_in);
    mTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);

    onSwitchText(null);
  }

  public void onSwitchText(View v) {
    mTextSwitcher.setText(TEXTS[mTextsPosition]);
    setNextPosition();
  }

  private void setNextPosition() {
    mTextsPosition = (mTextsPosition + 1) % TEXTS.length;
  }
}
Use TextSwitcher with animation

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use TextView autoLink

TextView (429/474)
« Previous

Use TextView autoLink

Description

If you know that the content of the TextView is going to contain a URL or an e-mail address, you can set the autoLink property to email|web, and the TextView will highlight any e-mail addresses and URLs.

When the user clicks on one of these highlighted items, the system will take care of launching the e-mail application with the e-mail address, or a browser with the URL.

In XML, this attribute would be inside the TextView tag and would look something like this:

<TextView ...
          android:autoLink="email|web"
          ...
/>

You specify a pipe-delimited set of values including web, email, phone, or map, or use none (the default) or all.

To set autoLink behavior in code instead of using XML, the corresponding method call is setAutoLinkMask().

You would pass it an int representing the combination of values sort of like before, such as android.text.util.Linkify.EMAIL_ADDRESSES|Linkify.WEB_ADDRESSES.

TextView tv =(TextView)this.findViewById(R.id.tv);
tv.setAutoLinkMask(Linkify.ALL);
tv.setText("Please visit my website, http://www.java2s.com or email me at info@java2s.com.");

You have to set the auto-link options on TextView before setting the text. Setting the auto-link options after setting the text won't affect the existing text.

Example

The following is the xml layout file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
//  w w w  .ja  v a  2s  . co  m
    <TextView
        android:id="@+id/myEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="abc@yourserver.com"
        android:autoLink="email" />

</LinearLayout>

Java code

package com.java2s.app;
/* w w w  .jav  a 2s. c o m*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

}
Use TextView autoLink

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use TimePickerDialog

Clock Date Picker (275/474)
« Previous

Use TimePickerDialog

Description

The following code shows how to Use TimePickerDialog.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView android:id="@+id/dateAndTime"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
  <Button android:id="@+id/dateBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Set the Date"
    />
  <Button android:id="@+id/timeBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Set the Time"
    />
</LinearLayout>

Java code

/***//  w ww . jav  a  2s.  c o m
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.java2s.myapplication3.app;

import android.app.Activity;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Calendar;

public class MainActivity extends Activity {
    DateFormat fmtDateAndTime=DateFormat.getDateTimeInstance();
    TextView dateAndTimeLabel;
    Calendar dateAndTime=Calendar.getInstance();
    DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            dateAndTime.set(Calendar.YEAR, year);
            dateAndTime.set(Calendar.MONTH, monthOfYear);
            dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }
    };
    TimePickerDialog.OnTimeSetListener t=new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay,
                              int minute) {
            dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            dateAndTime.set(Calendar.MINUTE, minute);
            updateLabel();
        }
    };

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

        Button btn=(Button)findViewById(R.id.dateBtn);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new DatePickerDialog(MainActivity.this,
                        d,
                        dateAndTime.get(Calendar.YEAR),
                        dateAndTime.get(Calendar.MONTH),
                        dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        btn=(Button)findViewById(R.id.timeBtn);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new TimePickerDialog(MainActivity.this,
                        t,
                        dateAndTime.get(Calendar.HOUR_OF_DAY),
                        dateAndTime.get(Calendar.MINUTE),
                        true).show();
            }
        });

        dateAndTimeLabel=(TextView)findViewById(R.id.dateAndTime);

        updateLabel();
    }

    private void updateLabel() {
        dateAndTimeLabel.setText(fmtDateAndTime.format(dateAndTime.getTime()));
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ToggleButton

Button (249/474)
« Previous

Use ToggleButton

Description

The ToggleButton control is a two-state button. It can be in either the On or Off state.

By default ToggleButton sets the button's text to On when it's in the On state and Off when it's in the Off state.

You can modify the text for the ToggleButton if On/Off is not appropriate for your application.

The following code sets the button's On/Off text to Stop and Run by using android:textOn and android:textOff properties.

<ToggleButton android:id="@+id/cctglBtn"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Toggle Button"
              android:textOn="Stop"
              android:textOff="Run"/>

Because ToggleButtons have on and off text as separate attributes, the android:text attribute of a ToggleButton is not really used.

Example

XML layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
// w w w  .  j  av  a 2 s  . co  m
    <ToggleButton android:id="@+id/cctglBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toggle Button"
        android:textOn="Stop"
        android:textOff="Run"/>
</LinearLayout>

Java code

package com.java2s.app;
//from w w w .  j a  va2s .  c o m
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ViewFlipper

View (457/474)
« Previous

Use ViewFlipper

Description

The following code shows how to use ViewFlipper.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button android:id="@+id/flip_me"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Flip Me!"
      />
  <ViewFlipper android:id="@+id/details"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:textStyle="bold"
      android:textColor="#FF00FF00"
      android:text="This is the first panel"
    />
    <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:textStyle="bold"
      android:textColor="#FFFF0000"
      android:text="This is the second panel"
    />
    <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:textStyle="bold"
      android:textColor="#FFFFFF00"
      android:text="This is the third panel"
    />
  </ViewFlipper>
</LinearLayout>

Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ViewFlipper;
/*from  w w  w .  j ava  2 s  . c o m*/
public class MainActivity extends Activity {
  ViewFlipper flipper;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    flipper=(ViewFlipper)findViewById(R.id.details);

    Button btn=(Button)findViewById(R.id.flip_me);

    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        flipper.showNext();
      }
    });
  }
}
/***
  Copyright (c) 2008-2009 CommonsWare, LLC

  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.
*/

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use ViewPager

View (465/474)
« Previous

Use ViewPager

Description

The following code shows how to Use ViewPager.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Main layout 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" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Item"
        android:onClick="onAddClick" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Remove Item"
        android:onClick="onRemoveClick" />

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Java code

import java.util.ArrayList;
//from w w  w .j  av  a 2s  .  c  om
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;

public class FragmentPagerActivity extends FragmentActivity {

    private ArrayList<String> mListItems;
    private ListPagerAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Create the initial data set
        mListItems = new ArrayList<String>();
        mListItems.add("Mom");
        mListItems.add("Dad");
        mListItems.add("Sister");
        mListItems.add("Brother");
        mListItems.add("Cousin");
        mListItems.add("Niece");
        mListItems.add("Nephew");
        //Attach the data to the pager
        ViewPager pager = (ViewPager) findViewById(R.id.view_pager);
        mAdapter = new ListPagerAdapter(getSupportFragmentManager(), mListItems);

        pager.setAdapter(mAdapter);
    }

    public void onAddClick(View v) {
        //Add a new unique item to the end of the list
        mListItems.add("Crazy Uncle " + System.currentTimeMillis());
        mAdapter.notifyDataSetChanged();
    }

    public void onRemoveClick(View v) {
        //Remove an item from the head of the list
        if (!mListItems.isEmpty()) {
            mListItems.remove(0);
        }
        mAdapter.notifyDataSetChanged();
    }
}
class ListPagerAdapter extends FragmentPagerAdapter {

    private static final int ITEMS_PER_PAGE = 3;

    private List<String> mItems;

    public ListPagerAdapter(FragmentManager manager, List<String> items) {
        super(manager);
        mItems = items;
    }

    /*
     * This method will only get called the first time a Fragment is needed for this position.
     */
    @Override
    public Fragment getItem(int position) {
        int start = position * ITEMS_PER_PAGE;
        return ArrayListFragment.newInstance(getPageList(position), start);
    }

    @Override
    public int getCount() {
        //Get whole number
        int pages = mItems.size() / ITEMS_PER_PAGE;
        // Add one more page for any remaining values if list size is not divisible by page size
        int excess = mItems.size() % ITEMS_PER_PAGE;
        if (excess > 0) {
            pages++;
        }

        return pages;
    }

    /*
     * This will get called after getItem() for new Fragments, but also when Fragments
     * beyond the off-screen page limit are added back; we need to make sure to update the
     * list for these elements.
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ArrayListFragment fragment = (ArrayListFragment) super.instantiateItem(container, position);
        fragment.updateListItems(getPageList(position));
        return fragment;
    }

    /*
     * Called by the framework when notifyDataSetChanged() is called, we must decide how
     * each Fragment has changed for the new data set.  We also return POSITION_NONE if
     * a Fragment at a particular position is no longer needed so the adapter can
     * remove it.
     */
    @Override
    public int getItemPosition(Object object) {
        ArrayListFragment fragment = (ArrayListFragment)object;
        int position = fragment.getBaseIndex() / ITEMS_PER_PAGE;
        if(position >= getCount()) {
            //This page no longer needed
            return POSITION_NONE;
        } else {
            //Refresh fragment data display
            fragment.updateListItems(getPageList(position));

            return position;
        }
    }

    /*
     * Helper method to obtain the piece of the overall list that should be
     * applied to a given Fragment
     */
    private List<String> getPageList(int position) {
        int start = position * ITEMS_PER_PAGE;
        int end = Math.min(start + ITEMS_PER_PAGE, mItems.size());
        List<String> itemPage = mItems.subList(start, end);

        return itemPage;
    }

    /*
     * Internal custom Fragment that displays a list section inside
     * of a ListView, and provides external methods for updating the list
     */
    public static class ArrayListFragment extends Fragment {
        private ArrayList<String> mItems;
        private ArrayAdapter<String> mAdapter;
        private int mBaseIndex;

        //Fragments are created by convention using a Factory pattern
        static ArrayListFragment newInstance(List<String> page, int baseIndex) {
            ArrayListFragment fragment = new ArrayListFragment();
            fragment.updateListItems(page);
            fragment.setBaseIndex(baseIndex);
            return fragment;
        }

        public ArrayListFragment() {
            super();
            mItems = new ArrayList<String>();
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Make a new adapter for the list items
            mAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, mItems);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            //Construct and return a Listview with our adapter attached
            ListView list = new ListView(getActivity());
            list.setAdapter(mAdapter);
            return list;
        }

        //Save the index in the global list where this page starts
        public void setBaseIndex(int index) {
            mBaseIndex = index;
        }

        //Retrieve the index in the global list where this page starts
        public int getBaseIndex() {
            return mBaseIndex;
        }

        public void updateListItems(List<String> items) {
            mItems.clear();
            for (String piece : items) {
                mItems.add(piece);
            }

            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Use webkit

WebView (474/474)
« Previous

Use webkit

Description

The following code shows how to Use webkit.

Example

Main layout xml file

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

Main Activity Java code

//from w  w  w . ja  va  2 s.  com
package com.java2s.myapplication3.app;

import static android.webkit.ConsoleMessage.MessageLevel.ERROR;

import java.io.File;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    private static final int REQUEST_PIC = 5;
    private static final int REQUEST_CONTACT = 4;
    private static final String LOG_TAG = "InterWebActivity";
    private WebView webView;
    private InterWebInterface webInterface;
    private static int onCreateCount = 0;
    private int onResumeCount = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.web);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        webInterface = new InterWebInterface();
        webView.addJavascriptInterface(webInterface, "android");
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                Log.d(LOG_TAG, String.format("WebView JsAlert message = %s",
                        url, message));
                return false;
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                StringBuilder msg = new StringBuilder(consoleMessage
                        .messageLevel().name()).append('\t')
                        .append(consoleMessage.message()).append('\t')
                        .append(consoleMessage.sourceId()).append(" (")
                        .append(consoleMessage.lineNumber()).append(")\n");
                if (consoleMessage.messageLevel() == ERROR) {
                    Log.e(LOG_TAG, msg.toString());
                } else {
                    Log.d(LOG_TAG, msg.toString());
                }
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(LOG_TAG, "Loading url=" + url);
                return false;
            }
        });
        webView.loadUrl("file:///android_asset/interweb.html");
        onCreateCount++;
    }

    @Override
    protected void onResume() {
        super.onResume();
        onResumeCount++;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CONTACT && resultCode == RESULT_OK) {
            webInterface.executeContactCallback(data.getData());
        }
        if (requestCode == REQUEST_PIC && resultCode == RESULT_OK) {
            webInterface.executePicCallback(data.getData());
        }
    }

    private String getContactDisplayName(Uri contactUri) {
        String[] projection = { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };
        Cursor cursor = managedQuery(contactUri, projection, null, null, null);
        if (cursor.moveToNext()) {
            return cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }
        return "Couldn't find it";
    }

    private String getPictureData(Uri pictureUri) {
        String[] projection = { MediaStore.MediaColumns.DATA };
        Cursor cursor = managedQuery(pictureUri, projection, null, null, null);
        if (cursor.moveToNext()) {
            return cursor.getString(cursor
                    .getColumnIndex(MediaStore.MediaColumns.DATA));
        }
        return "";
    }

    class InterWebInterface {
        String callback;

        public String getCreateCount() {
            return String.valueOf(onCreateCount);
        }

        public String getResumeCount() {
            return String.valueOf(onResumeCount);
        }

        public String getUserName() {
            AccountManager mgr = AccountManager.get(MainActivity.this);
            Account gAccount = mgr.getAccountsByType("com.google")[0];
            return gAccount.name;
        }

        public void selectContact(String callback) {
            this.callback = callback;
            Intent intentContact = new Intent(Intent.ACTION_PICK,
                    ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intentContact, REQUEST_CONTACT);
        }

        public void selectPicture(String callback) {
            this.callback = callback;
            Intent intentPicture = new Intent(Intent.ACTION_GET_CONTENT);
            intentPicture.setType("image/*");
            startActivityForResult(intentPicture, REQUEST_PIC);
        }

        protected void executeContactCallback(Uri contact) {
            String name = getContactDisplayName(contact);
            webView.loadUrl(String.format("javascript:contactCallback('%s')",
                    name));
        }

        protected void executePicCallback(Uri picture) {
            String filePath = getPictureData(picture);
            File f = new File(filePath);
            String uri = Uri.fromFile(f).toString();
            webView.loadUrl(String.format("javascript:pictureCallback('%s')",
                    uri));
        }
    }
}

« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - User motion detector

Sensor (200/474)
« Previous

User motion detector

Description

The following code shows how to recongize user motion.

Code revised from
Android Recipes:A Problem-Solution Approach
http://www.apress.com/9781430234135
ISBN13: 978-1-4302-3413-5

Example

Register permission for ACTIVITY_RECOGNITION.

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

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

    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidrecipes.usermotionactivity.MainActivity"
            android:label="User Activity"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.androidrecipes.usermotionactivity.UserMotionService" />
    </application>

</manifest>

Main layout xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stackFromBottom="true"
        android:transcriptMode="normal" />
    <TextView
        android:id="@+id/blocker"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:clickable="true"
        android:textSize="32dp"
        android:textColor="#F55"
        android:text="It is not safe to operate your mobile device while in a vehicle!"
        android:background="#C333"
        android:visibility="gone" />
</FrameLayout>

Java code for Main activity

package com.androidrecipes.usermotionactivity;
/*from w ww  .  j a  v  a2 s.com*/
import com.androidrecipes.usermotionactivity.UserMotionService.LocalBinder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.ActivityRecognitionClient;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements
        ServiceConnection,
        UserMotionService.OnActivityChangedListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {
    private static final String TAG = "UserActivity";

    private Intent mServiceIntent;
    private PendingIntent mCallbackIntent;
    private UserMotionService mService;

    private ActivityRecognitionClient mRecognitionClient;
    //Custom list adapter to display our results
    private ActivityAdapter mListAdapter;

    private View mBlockingView;

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

        mBlockingView = findViewById(R.id.blocker);

        //Construct a simple list adapter that will display all the
        // incoming activity change events from the service.
        ListView list = (ListView) findViewById(R.id.list);
        mListAdapter = new ActivityAdapter(this);
        list.setAdapter(mListAdapter);

        //When the list is clicked, display all the probable activities
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                showDetails(mListAdapter.getItem(position));
            }
        });

        //Check if Google Play Services is up to date.
        switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)) {
            case ConnectionResult.SUCCESS:
                //Do nothing, move on
                break;
            case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                Toast.makeText(this,
                        "Activity service requires an update, please open Google Play.",
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
            default:
                Toast.makeText(this,
                        "Activity service is not available on this device.",
                        Toast.LENGTH_SHORT).show();
                finish();
                return;
        }
        //Create a client instance for talking to Google Services
        mRecognitionClient = new ActivityRecognitionClient(this, this, this);
        //Create an Intent to bind to the service
        mServiceIntent = new Intent(this, UserMotionService.class);
        //Create a PendingIntent that Google Services will use for callbacks
        mCallbackIntent = PendingIntent.getService(this, 0,
                mServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Connect to Google Services and our Service
        mRecognitionClient.connect();
        bindService(mServiceIntent, this, BIND_AUTO_CREATE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //Disconnect from all services
        mRecognitionClient.removeActivityUpdates(mCallbackIntent);
        mRecognitionClient.disconnect();

        disconnectService();
        unbindService(this);
    }

    /** ServiceConnection Methods */

    public void onServiceConnected(ComponentName name, IBinder service) {
        //Attach ourselves to our Service as a callback for events
        mService = ((LocalBinder) service).getService();
        mService.setOnActivityChangedListener(this);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        disconnectService();
    }

    private void disconnectService() {
        if (mService != null) {
            mService.setOnActivityChangedListener(null);
        }
        mService = null;
    }

    /** Google Services Connection Callbacks */

    @Override
    public void onConnected(Bundle connectionHint) {
        //We must wait until the services are connected
        // to request any updates.
        mRecognitionClient.requestActivityUpdates(5000, mCallbackIntent);
    }

    @Override
    public void onDisconnected() {
        Log.w(TAG, "Google Services Disconnected");
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.w(TAG, "Google Services Connection Failure");
    }

    /** OnActivityChangedListener Methods */

    @Override
    public void onUserActivityChanged(int bestChoice, int bestConfidence,
            ActivityRecognitionResult newActivity) {
        //Add latest event to the list
        mListAdapter.add(newActivity);
        mListAdapter.notifyDataSetChanged();

        //Determine user action based on our custom algorithm
        switch (bestChoice) {
            case DetectedActivity.IN_VEHICLE:
            case DetectedActivity.ON_BICYCLE:
                mBlockingView.setVisibility(View.VISIBLE);
                break;
            case DetectedActivity.ON_FOOT:
            case DetectedActivity.STILL:
                mBlockingView.setVisibility(View.GONE);
                break;
            default:
                //Ignore other states
                break;
        }
    }

    /*
     * Utility that builds a simple Toast with all the probable
     * activity choices with their confidence values
     */
    private void showDetails(ActivityRecognitionResult activity) {
        StringBuilder sb = new StringBuilder();
        sb.append("Details:");
        for(DetectedActivity element : activity.getProbableActivities()) {
            sb.append("\n"+UserMotionService.getActivityName(element)
                    + ", " + element.getConfidence() + "% sure");
        }

        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
    }

    /*
     * ListAdapter to display each activity result we receive from the service
     */
    private static class ActivityAdapter extends ArrayAdapter<ActivityRecognitionResult> {

        public ActivityAdapter(Context context) {
            super(context, android.R.layout.simple_list_item_1);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext())
                        .inflate(android.R.layout.simple_list_item_1, parent, false);
            }
            //Display the most probable activity with its confidence in the list
            TextView tv = (TextView) convertView;
            ActivityRecognitionResult result = getItem(position);
            DetectedActivity newActivity = result.getMostProbableActivity();
            String entry = DateFormat.format("hh:mm:ss", result.getTime())
                    + ": " + UserMotionService.getActivityName(newActivity) + ", "
                    + newActivity.getConfidence() + "% confidence";
            tv.setText(entry);

            return convertView;
        }
    }
}

User motion service

// ww  w  .j ava 2s.  c o m
package com.androidrecipes.usermotionactivity;

import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;

import android.app.IntentService;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class UserMotionService extends IntentService {
    private static final String TAG = "UserMotionService";

    /*
     * Callback interface for detected activity type changes
     */
    public interface OnActivityChangedListener{
        public void onUserActivityChanged(int bestChoice, int bestConfidence,
                ActivityRecognitionResult newActivity);
    }

    /* Last detected activity type */
    private DetectedActivity mLastKnownActivity;
    /*
     * Marshals requests from the background thread so the callbacks
     * can be made on the main (UI) thread.
     */
    private CallbackHandler mHandler;
    private static class CallbackHandler extends Handler {
        /* Callback for activity changes */
        private OnActivityChangedListener mCallback;

        public void setCallback(OnActivityChangedListener callback) {
            mCallback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            if (mCallback != null) {
                //Read payload data out of the message and fire callback
                ActivityRecognitionResult newActivity = (ActivityRecognitionResult) msg.obj;
                mCallback.onUserActivityChanged(msg.arg1, msg.arg2, newActivity);
            }
        }
    }

    public UserMotionService() {
        //String is used to name the background thread created
        super("UserMotionService");
        mHandler = new CallbackHandler();
    }

    public void setOnActivityChangedListener(OnActivityChangedListener listener) {
        mHandler.setCallback(listener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w(TAG, "Service is stopping...");
    }

    /*
     * Incoming action events from the framework will come
     * in here.  This is called on a background thread, so
     * we can do long processing here if we wish.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        if (ActivityRecognitionResult.hasResult(intent)) {
            //Extract the result from the Intent
            ActivityRecognitionResult result =
                    ActivityRecognitionResult.extractResult(intent);
            DetectedActivity activity = result.getMostProbableActivity();
            Log.v(TAG, "New User Activity Event");

            //If the highest probability is UNKNOWN, but the confidence is low,
            // check if another exists and select it instead
            if (activity.getType() == DetectedActivity.UNKNOWN
                    && activity.getConfidence() < 60
                    && result.getProbableActivities().size() > 1) {
                //Select the next probable element
                activity = result.getProbableActivities().get(1);
            }

            //On a change in activity, alert the callback
            if (mLastKnownActivity == null
                    || mLastKnownActivity.getType() != activity.getType()
                    || mLastKnownActivity.getConfidence() != activity.getConfidence()) {
                //Pass the results to the main thread inside a Message
                Message msg = Message.obtain(null,
                        0,                         //what
                        activity.getType(),        //arg1
                        activity.getConfidence(),  //arg2
                        result);
                mHandler.sendMessage(msg);
            }
            mLastKnownActivity = activity;
        }
    }

    /*
     * This is called when the Activity wants to bind to the
     * service.  We have to provide a wrapper around this instance
     * to pass it back.
     */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /*
     * This is a simple wrapper that we can pass to the Activity
     * to allow it direct access to this service.
     */
    private LocalBinder mBinder = new LocalBinder();
    public class LocalBinder extends Binder {
        public UserMotionService getService() {
            return UserMotionService.this;
        }
    }

    /*
     * Utility to get a good display name for each state
     */
    public static String getActivityName(DetectedActivity activity) {
        switch(activity.getType()) {
            case DetectedActivity.IN_VEHICLE:
                return "Driving";
            case DetectedActivity.ON_BICYCLE:
                return "Biking";
            case DetectedActivity.ON_FOOT:
                return "Walking";
            case DetectedActivity.STILL:
                return "Not Moving";
            case DetectedActivity.TILTING:
                return "Tilting";
            case DetectedActivity.UNKNOWN:
            default:
                return "No Clue";
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Using a PreferenceFragment

Fragment (313/474)
« Previous

Using a PreferenceFragment

Description

In Android, you can use the PreferenceActivity base class to display an activity for the user to edit the preferences.

You can use the PreferenceFragment class to do the same thing.

Example

Populate the res/xml/preferences.xml file as follows:

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

    <PreferenceCategory android:title="Category 1">
        <CheckBoxPreference
            android:title="Checkbox"
            android:defaultValue="false"
            android:summary="True of False"
            android:key="checkboxPref" />
        </PreferenceCategory>

    <PreferenceCategory android:title="Category 2">
        <EditTextPreference
            android:name="EditText"
            android:summary="Enter a string"
            android:defaultValue="[Enter a string here]"
            android:title="Edit Text"
            android:key="editTextPref" />
        <RingtonePreference
            android:name="Ringtone Preference"
            android:summary="Select a ringtone"
            android:title="Ringtones"
            android:key="ringtonePref" />
        <PreferenceScreen
            android:title="Second Preference Screen"
            android:summary=
                "Click here to go to the second Preference Screen"
            android:key="secondPrefScreenPref">
            <EditTextPreference
                android:name="EditText"
                  android:summary="Enter a string"
                  android:title="Edit Text (second Screen)"
                  android:key="secondEditTextPref" />
          </PreferenceScreen>
      </PreferenceCategory>

</PreferenceScreen>

Populate the Fragment1.java file as follows:

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class Fragment1 extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //---load the preferences from an XML file---
        addPreferencesFromResource(R.xml.preferences);
    }
}

Modify the MainActivity.java file as shown:

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
// www .  j  a  v a  2 s  .c o  m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction =
            fragmentManager.beginTransaction();
        Fragment1 fragment1 = new Fragment1();
        fragmentTransaction.replace(android.R.id.content, fragment1);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

If you look at the File Explorer (available in the DDMS perspective), you will be able to locate the preferences file located in the /data/data/com.java2s.PreferenceFragmentExample/shared_prefs/ folder.

All changes made by the user are persisted in this file.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Video capture with Intent

Video (453/474)
« Previous

Video capture with Intent

Description

The following code shows how to do Video capture with Intent.

Example

Setup permission for video capture

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <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="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
    android:id="@+id/capture"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take a Video"
  />
  <TextView
    android:id="@+id/file"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />
</LinearLayout>

Java code for main activity

import java.io.File;
/*ww w  .j  a  v  a  2 s .  co  m*/
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static final int REQUEST_VIDEO = 100;

    Button captureButton;
    TextView text;
    File destination;

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

        captureButton = (Button)findViewById(R.id.capture);
        captureButton.setOnClickListener(listener);

        text = (TextView)findViewById(R.id.file);

        destination = new File(Environment.getExternalStorageDirectory(),"myVideo");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_VIDEO && resultCode == Activity.RESULT_OK) {
            String location = data.getData().toString();
            text.setText(location);
        }
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, REQUEST_VIDEO);
        }
    };
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - View to display a true type font via Canvas

Canvas (261/474)
« Previous

View to display a true type font via Canvas

Description

The following code shows how to View to display a true type font via Canvas.

Example

Main Activity Java code

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.view.View;
import android.app.Activity;
import android.os.Bundle;
/*from  w  ww  .j  ava2s.co  m*/
public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ShapesAndTextFontView view = new ShapesAndTextFontView(this);
      view.setText("256 byte Style");
      setContentView(view);
   }
}
class ShapesAndTextFontView extends View {

   private Paint paint;
   private Typeface font;
   private String text;

   public ShapesAndTextFontView(Context context) {
      super(context);
      // Loading up the font
      font = Typeface.createFromAsset(context.getAssets(), "256bytes.ttf");
   }

   public void setText(String text) {
      this.text = text;
   }

   @Override
   protected void onDraw(Canvas canvas) {
      canvas.drawRGB(0, 0, 0);
      drawText(canvas);
   }
   private void drawText(Canvas canvas) {
      paint.setColor(Color.WHITE);
      paint.setTextSize(40);
      paint.setTypeface(font);
      canvas.drawText(text, 60, 300, paint);
   }
}

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Views and ViewGroups

View (455/474)
« Previous

Views and ViewGroups

Description

The basic unit of an Android application is an activity.

An activity by itself does not have a presence on the screen. Instead, it has to draw the screen using Views and ViewGroups.

A view is a widget that has an appearance on screen. Examples of views are buttons, labels, and textboxes. A view derives from the base class android.view.View.

One or more views can be grouped together into a ViewGroup. A ViewGroup, which is itself a special type of view, provides the layout in which you can order the appearance and sequence of views.

Examples of ViewGroups include LinearLayout and FrameLayout. A ViewGroup derives from the base class android.view.ViewGroup.

Android supports the following ViewGroups:

  • LinearLayout
  • AbsoluteLayout
  • TableLayout
  • RelativeLayout
  • FrameLayout
  • ScrollView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What are fragments

Fragment (304/474)
« Previous

What are fragments

Description

In a small-screen device, an activity typically fills the entire screen. And the activity is a container for views.

To better organize UI on a tablet we can use "mini-activities". Each mini-activities contains its own set of views.

An activity can contain one or more of these mini-activities. These mini-activities are known as fragments.

Fragments can contain views, just like activities. And fragments are always embedded in an activity.

Fragments form the atomic unit of your user interface, and they can be dynamically added or removed to activities.

We can think of the concept of a fragment in Android as the panel in a Desktop user interface.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What are Intents

Intent (126/474)
« Previous

What are Intents

Description

An intent is an action with its associated data.

Android uses intents to invoke components. The components in Android includes

  • activities (UI components),
  • services (background code),
  • broadcast receivers, and
  • content providers.

You can use intents to invoke external applications or internal components.

You can use intents to raise events so that others can respond in a manner similar to a publish-and-subscribe model.

You can use intents to raise alarms.

Example

The following code shows how to use Intent to open an Activity.

Imagine you've the following activity:

public class BasicViewActivity extends Activity
{//from w w  w . j  a  v a  2s  .co m
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ...
    }
}

Then you register this activity in the manifest file, making it available for other applications to invoke.

<activity android:name=".BasicViewActivity"
          android:label="Basic View Tests">
 <intent-filter>//from  w w  w  . j av  a2 s.  c  o m
   <action android:name="com.java2s.intent.action.ShowBasicView"/>
   <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>
</activity>

To use an intent to invoke this BasicViewActivity:

public static void invokeMyApplication(Activity parentActivity)
{/*from w w  w .ja v  a 2  s . c  om*/
   String actionName= "com.java2s.intent.action.ShowBasicView";
   Intent intent = new Intent(actionName);
   parentActivity.startActivity(intent);
}

Note

The general convention for an action name is

<your-package-name>.intent.action.YOUR_ACTION_NAME

BasicViewActivity can get the intent that invoked it.

class BasicViewActivity extends Activity
{/*  w w  w  .j a va  2 s .  c  om*/
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ...
        ...
        Intent intent = this.getIntent();
        if (intent == null)
        {
            Log.d("test tag", "This activity is invoked without an intent");
        }
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


What Is Android

Description

Android is a mobile operating system that is based on a modified version of Linux.

Most of the Android code was released under the open source Apache License.

Features of Android

There are no fixed hardware or software configurations. However, Android itself supports the following features:

  • Storage - Uses SQLite, a lightweight relational database, for data storage.
  • Connectivity - Supports GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, and WiMAX.
  • Messaging - Supports both SMS and MMS.
  • Web browser - Based on the open source WebKit, together with Chrome's V8 JavaScript engine
  • Media support - Includes support for the following media: H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
  • Hardware support - Accelerometer Sensor, Camera, Digital Compass, Proximity Sensor, and GPS
  • Multi-touch - Supports multi-touch screens
  • Multi-touch - Supports multi-touch screens
  • Multi-tasking - Supports multi-tasking applications
  • Tethering - Supports sharing of Internet connections as a wired/wireless hotspot

Architecture of Android

The Android OS is roughly divided into five sections in four main layers:

  • Linux kernel - This is the kernel on which Android is based.
  • Libraries - These contain all the code that provides the main features of an Android OS.
  • Android runtime - At the same layer as the libraries, the Android runtime provides a set of core libraries that enable developers to write Android apps using the Java programming language.
  • Application framework - Exposes the various capabilities of the Android OS to application developers so that they can make use of them in their applications.
  • Applications - Applications that ship with the Android device, as well as applications that you download and install from the Android Market. Any applications that you write are located at this layer.

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What is FrameLayout

Layout (354/474)
« Previous

What is FrameLayout

Description

The FrameLayout is a placeholder on screen that you can use to display a single view.

Views that you add to a FrameLayout are always anchored to the top left of the layout.

You can add multiple views to a FrameLayout, but each will be stacked on top of the previous one.

Example

Consider the following content in main.xml:

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

    <TextView
        android:id="@+id/lblComments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, Android!"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" />

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/lblComments"
        android:layout_below="@+id/lblComments"
        android:layout_centerHorizontal="true" >

        <ImageView
            android:src = "@drawable/droid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </FrameLayout>
</RelativeLayout>
What is FrameLayout

In the code above you have a FrameLayout within a RelativeLayout. Within the FrameLayout, you embed an ImageView.

If you add another view (such as a Button view) within the FrameLayout, the view will overlap the previous view:

<RelativeLayout
    android:id="@+id/RLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView
        android:id="@+id/lblComments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, Android!"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        />
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/lblComments"
        android:layout_below="@+id/lblComments"
        android:layout_centerHorizontal="true" >
        <ImageView
            android:src = "@drawable/droid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:layout_width="124dp"
            android:layout_height="wrap_content"
            android:text="Print Picture" />

    </FrameLayout>
</RelativeLayout>
What is FrameLayout

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What is GridView

GridView (320/474)
« Previous

What is GridView

Description

The GridView shows items in a two-dimensional scrolling grid.

You can use the GridView together with an ImageView to display a series of images.

Example

Populate the main.xml file with the following content:

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

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
      android:numColumns="auto_fit"
      android:verticalSpacing="10dp"
      android:horizontalSpacing="10dp"
      android:columnWidth="90dp"
      android:stretchMode="columnWidth"
      android:gravity="center" />

</LinearLayout>

Add the following statements to the MainActivity.java file:

package com.java2s.myapplication3.app;
/*from   w  w  w.ja  v a2  s  .  com*/
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    //the images to display
    Integer[] imageIDs = {
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView parent,
                                    View v, int position, long id)
            {
                Toast.makeText (getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;

        public ImageAdapter(Context c)
        {
            context = c;
        }

        //returns the number of images
        public int getCount() {
            return imageIDs.length;
        }

        //returns the item
        public Object getItem(int position) {
            return position;
        }

        //returns the ID of an item
        public long getItemId(int position) {
            return position;
        }

        //returns an ImageView view
        public View getView(int position, View convertView,
                            ViewGroup parent)
        {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new
                        GridView.LayoutParams(85, 85));
                imageView.setScaleType(
                        ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }
    }

}
What is GridView

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What is RelativeLayout

Layout (348/474)
« Previous

What is RelativeLayout

Description

The RelativeLayout enables you to specify how child views are positioned relative to each other.

Example

Consider the following main.xml file:

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

    <TextView
        android:id="@+id/lblComments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Comments"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" />

    <EditText
        android:id="@+id/txtComments"
           android:layout_width="fill_parent"
           android:layout_height="170px"
           android:textSize="18sp"
           android:layout_alignLeft="@+id/lblComments"
           android:layout_below="@+id/lblComments"
           android:layout_centerHorizontal="true" />
    <Button
           android:id="@+id/btnSave"
           android:layout_width="125px"
           android:layout_height="wrap_content"
           android:text="Save"
           android:layout_below="@+id/txtComments"
           android:layout_alignRight="@+id/txtComments" />

    <Button
           android:id="@+id/btnCancel"
           android:layout_width="124px"
           android:layout_height="wrap_content"
           android:text="Cancel"
           android:layout_below="@+id/txtComments"
           android:layout_alignLeft="@+id/txtComments" />
</RelativeLayout>
What is RelativeLayout

Note

Each view embedded within the RelativeLayout has attributes that enable it to align with another view.

These attributes are as follows:

  • layout_alignParentTop
  • layout_alignParentLeft
  • layout_alignLeft
  • layout_alignRight
  • layout_below
  • layout_centerHorizontal

The value for each of these attributes is the ID for the view that you are referencing.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What is TableLayout

Layout (351/474)
« Previous

What is TableLayout

Description

The TableLayout groups views into rows and columns.

You use the <TableRow> element to designate a row in the table. Each row can contain one or more views.

Each view you place within a row forms a cell. The width of each column is determined by the largest width of each cell in that column.

Example

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent" >
    <TableRow>
        <TextView
            android:text="User Name:"
            android:width ="120dp"
            />
        <EditText
            android:id="@+id/txtUserName"
            android:width="200dp" />
    </TableRow>
    <TableRow>
        <TextView
            android:text="Password:"
            />
        <EditText
            android:id="@+id/txtPassword"
            android:password="true"
            />
    </TableRow>
    <TableRow>
        <TextView />
        <CheckBox android:id="@+id/chkRememberPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Remember Password"
            />
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/buttonSignIn"
            android:text="Log In" />
    </TableRow>
</TableLayout>
What is TableLayout

Note

In the preceding example, there are two columns and four rows in the TableLayout. The cell directly under the Password TextView is populated with a <TextView/> empty element.

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - What is TextView

TextView (422/474)
« Previous

What is TextView

Description

The TextView view is used to display text to the user. This is the most basic view and one that you will frequently use when you develop Android applications.

If you need to allow users to edit the text displayed, you should use the subclass of TextView, EditText.

In some other platforms, the TextView is commonly known as the label view. Its sole purpose is to display text on the screen.

Example

The following layout xml resource file has a definition for TextView.

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

Next »
« Previous
Home »
Android »
Android UI »

UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Wrap log class to create your own logger

Hello Android (10/474)
« Previous

Wrap log class to create your own logger

Description

The following code shows how to Wrap log class to create your own logger.

Example

Layout activity_main.xml file

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>

Java code

package com.java2s.myapplication3.app;
//from w  w  w . ja  v a 2 s  .  c o m
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Logger.d("Activity Created");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.d("Activity Resume at %d", System.currentTimeMillis());
        Logger.i("It is now %d", System.currentTimeMillis());
    }

    @Override
    protected void onPause() {
        super.onPause();
        Logger.d("Activity Pause at %d", System.currentTimeMillis());
        Logger.w("on pause");
    }
}
class Logger {
    private static final String LOGTAG = "AndroidRecipes";

    private static String getLogString(String format, Object... args) {
        if(args.length == 0) {
            return format;
        }
        return String.format(format, args);
    }
    public static void e(String format, Object... args) {
        Log.e(LOGTAG, getLogString(format, args));
    }

    public static void w(String format, Object... args) {
        Log.w(LOGTAG, getLogString(format, args));
    }

    public static void w(Throwable throwable) {
        Log.w(LOGTAG, throwable);
    }

    public static void i(String format, Object... args) {
        Log.i(LOGTAG, getLogString(format, args));
    }
    public static void d(String format, Object... args) {
        if(!BuildConfig.DEBUG)
            return;
        Log.d(LOGTAG, getLogString(format, args));
    }

    public static void v(String format, Object... args) {
        if(!BuildConfig.DEBUG)
            return;

        Log.v(LOGTAG, getLogString(format, args));
    }
}
Wrap log class to create your own logger

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Write and read External storage with File Utilities

Resources (50/474)
« Previous

Write and read External storage with File Utilities

Description

The following code shows how to Write and read External storage with File Utilities.

Example

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Main layout xml file

<?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/external_storage_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10px"
        android:text="Enter some text to write on the external storage, then read back:" />

    <EditText
        android:id="@+id/external_storage_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10px" />

    <Button
        android:id="@+id/external_storage_write_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write" />

    <Button
        android:id="@+id/external_storage_read_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read" />

    <TextView
        android:id="@+id/external_storage_output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10px" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Environment;
import android.util.Log;
//w ww .j  a va  2s  .  c  om

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.channels.FileChannel;

import java.io.File;

public class MainActivity extends Activity {
   private EditText input;
   private TextView output;
   private Button write;
   private Button read;

   @Override
   public void onCreate(final Bundle icicle) {
      super.onCreate(icicle);
      this.setContentView(R.layout.external_storage);

      this.input = (EditText) findViewById(R.id.external_storage_input);
      this.output = (TextView) findViewById(R.id.external_storage_output);

      this.write = (Button) findViewById(R.id.external_storage_write_button);
      this.write.setOnClickListener(new OnClickListener() {
         public void onClick(final View v) {
            write();
         }
      });

      this.read = (Button) findViewById(R.id.external_storage_read_button);
      this.read.setOnClickListener(new OnClickListener() {
         public void onClick(final View v) {
            read();
         }
      });
   }

   private void write() {
      if (FileUtil.isExternalStorageWritable()) {
         File dir = FileUtil.getExternalFilesDirAllApiLevels(this.getPackageName());
         File file = new File(dir, "test.txt");
         FileUtil.writeStringAsFile(input.getText().toString(), file);
         Toast.makeText(this, "File written", Toast.LENGTH_SHORT).show();
         input.setText("");
         output.setText("");
      } else {
         Toast.makeText(this, "External storage not writable", Toast.LENGTH_SHORT).show();
      }
   }

   private void read() {
      if (FileUtil.isExternalStorageReadable()) {
         File dir = FileUtil.getExternalFilesDirAllApiLevels(this.getPackageName());
         File file = new File(dir, "test.txt");
         if (file.exists() && file.canRead()) {
            output.setText(FileUtil.readFileAsString(file));
            Toast.makeText(this, "File read", Toast.LENGTH_SHORT).show();
         } else {
            Toast.makeText(this, "Unable to read file: " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
         }
      } else {
         Toast.makeText(this, "External storage not readable", Toast.LENGTH_SHORT).show();
      }
   }
}

/**
 * FileUtil methods.
 *
 * @author ccollins
 *
 */
final class FileUtil {

   // from the Android docs, these are the recommended paths
   private static final String EXT_STORAGE_PATH_PREFIX = "/Android/data/";
   private static final String EXT_STORAGE_FILES_PATH_SUFFIX = "/files/";
   private static final String EXT_STORAGE_CACHE_PATH_SUFFIX = "/cache/";

   // Object for intrinsic lock (per docs 0 length array "lighter" than a normal Object)
   public static final Object[] DATA_LOCK = new Object[0];

   private FileUtil() {
   }

   /**
    * Use Environment to check if external storage is writable.
    *
    * @return
    */
   public static boolean isExternalStorageWritable() {
      return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
   }

   /**
    * Use environment to check if external storage is readable.
    *
    * @return
    */
   public static boolean isExternalStorageReadable() {
      if (isExternalStorageWritable()) {
         return true;
      }
      return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
   }

   /**
    * Return the recommended external files directory, whether using API level 8 or lower.
    * (Uses getExternalStorageDirectory and then appends the recommended path.)
    *
    * @param packageName
    * @return
    */
   public static File getExternalFilesDirAllApiLevels(final String packageName) {
      return FileUtil.getExternalDirAllApiLevels(packageName, EXT_STORAGE_FILES_PATH_SUFFIX);
   }

   /**
    * Return the recommended external cache directory, whether using API level 8 or lower.
    * (Uses getExternalStorageDirectory and then appends the recommended path.)
    *
    * @param packageName
    * @return
    */
   public static File getExternalCacheDirAllApiLevels(final String packageName) {
      return FileUtil.getExternalDirAllApiLevels(packageName, EXT_STORAGE_CACHE_PATH_SUFFIX);
   }

   private static File getExternalDirAllApiLevels(final String packageName, final String suffixType) {
      File dir =
               new File(Environment.getExternalStorageDirectory() + EXT_STORAGE_PATH_PREFIX + packageName + suffixType);
      synchronized (FileUtil.DATA_LOCK) {
         try {
            dir.mkdirs();
            dir.createNewFile();
         } catch (IOException e) {
            Log.e(Constants.LOG_TAG, "Error creating file", e);
         }
      }
      return dir;
   }

   /**
    * Copy file, return true on success, false on failure.
    *
    * @param src
    * @param dst
    * @return
    */
   public static boolean copyFile(final File src, final File dst) {
      boolean result = false;
      FileChannel inChannel = null;
      FileChannel outChannel = null;
      synchronized (FileUtil.DATA_LOCK) {
         try {
            inChannel = new FileInputStream(src).getChannel();
            outChannel = new FileOutputStream(dst).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            result = true;
         } catch (IOException e) {

         } finally {
            if (inChannel != null && inChannel.isOpen()) {
               try {
                  inChannel.close();
               } catch (IOException e) {
                  // ignore
               }
            }
            if (outChannel != null && outChannel.isOpen()) {
               try {
                  outChannel.close();
               } catch (IOException e) {
                  // ignore
               }
            }
         }
      }
      return result;
   }

   /**
    * Replace entire File with contents of String, return true on success, false on failure.
    *
    * @param fileContents
    * @param file
    * @return
    */
   public static boolean writeStringAsFile(final String fileContents, final File file) {
      boolean result = false;
      try {
         synchronized (FileUtil.DATA_LOCK) {
            if (file != null) {
               file.createNewFile(); // ok if returns false, overwrite
               Writer out = new BufferedWriter(new FileWriter(file), 1024);
               out.write(fileContents);
               out.close();
               result = true;
            }
         }
      } catch (IOException e) {
         Log.e(Constants.LOG_TAG, "Error writing string data to file " + e.getMessage(), e);
      }
      return result;
   }

   /**
    * Append String to end of File, return true on success, false on failure.
    *
    * @param appendContents
    * @param file
    * @return
    */
   public static boolean appendStringToFile(final String appendContents, final File file) {
      boolean result = false;
      try {
         synchronized (FileUtil.DATA_LOCK) {
            if ((file != null) && file.canWrite()) {
               file.createNewFile(); // ok if returns false, overwrite
               Writer out = new BufferedWriter(new FileWriter(file, true), 1024);
               out.write(appendContents);
               out.close();
               result = true;
            }
         }
      } catch (IOException e) {
         Log.e(Constants.LOG_TAG, "Error appending string data to file " + e.getMessage(), e);
      }
      return result;
   }

   /**
    * Read file as String, return null if file is not present or not readable.
    *
    * @param file
    * @return
    */
   public static String readFileAsString(final File file) {
      StringBuilder sb = null;
      try {
         synchronized (FileUtil.DATA_LOCK) {
            if ((file != null) && file.canRead()) {
               sb = new StringBuilder();
               String line = null;
               BufferedReader in = new BufferedReader(new FileReader(file), 1024);
               while ((line = in.readLine()) != null) {
                  sb.append(line + System.getProperty("line.separator"));
               }
            }
         }
      } catch (IOException e) {
         Log.e(Constants.LOG_TAG, "Error reading file " + e.getMessage(), e);
      }
      if (sb != null) {
         return sb.toString();
      }
      return null;
   }
}
Write and read External storage with File Utilities

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Write and read file

Resources (52/474)
« Previous

Write and read file

Description

The following code shows how to Write and read file.

Example

Mark the permission for WRITE_EXTERNAL_STORAGE

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <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="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Java code to write and read file

package com.java2s.myapplication3.app;
// www . j a  v  a2s .c o m
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

public class MainActivity extends Activity {

    private static final String FILENAME = "data.txt";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        setContentView(tv);

        try {
            FileOutputStream mOutput = openFileOutput(FILENAME, Activity.MODE_PRIVATE);
            String data = "THIS DATA WRITTEN TO A FILE";
            mOutput.write(data.getBytes());
            mOutput.close();

            //Read the created file and display to the screen

            FileInputStream mInput = openFileInput(FILENAME);
            byte[] data1 = new byte[128];
            mInput.read(data1);
            mInput.close();

            String display = new String(data1);
            tv.setText(display.trim());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        deleteFile(FILENAME);
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Write and read file in External Storage Directory

Resources (51/474)
« Previous

Write and read file in External Storage Directory

Description

The following code shows how to Write and read file in External Storage Directory.

Example

Register permission for WRITE_EXTERNAL_STORAGE

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.myapplication3.app" >
    <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="java2s.com"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.java2s.myapplication3.app.MainActivity"
            android:label="java2s.com"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main activity Java code

package com.java2s.myapplication3.app;
/*  w w  w  .j  av a2s  .  c  om*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

public class MainActivity extends Activity {

    private static final String FILENAME = "data.txt";
    private static final String DNAME = "myfiles";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        setContentView(tv);

        File rootPath = new File(Environment.getExternalStorageDirectory(), DNAME);
        if(!rootPath.exists()) {
            rootPath.mkdirs();
        }
        File dataFile = new File(rootPath, FILENAME);
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "Cannot use storage.", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        try {
            FileOutputStream mOutput = new FileOutputStream(dataFile, false);
            String data = "THIS DATA WRITTEN TO A FILE";
            mOutput.write(data.getBytes());
            mOutput.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Read the created file and display to the screen
        try {
            FileInputStream mInput = new FileInputStream(dataFile);
            byte[] data = new byte[128];
            mInput.read(data);
            mInput.close();

            String display = new String(data);
            tv.setText(display.trim());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataFile.delete();
    }
}

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.


Android - Write and read from Internal Storage

Resources (53/474)
« Previous

Write and read from Internal Storage

Description

The following code shows how to Write and read from Internal Storage.

Example

Main layout xml file

<?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/internal_storage_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10px"
        android:text="Enter some text to write on the internal storage, then read back:" />

    <EditText
        android:id="@+id/internal_storage_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10px" />

    <Button
        android:id="@+id/internal_storage_write_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write" />

    <Button
        android:id="@+id/internal_storage_read_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read" />

    <TextView
        android:id="@+id/internal_storage_output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10px" />

</LinearLayout>

Main Activity Java code

//from  www. j  a  va 2 s .  c  om
package com.java2s.myapplication3.app;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class MainActivity extends Activity {
    private static final String LINE_SEP = System.getProperty("line.separator");

    private EditText input;
    private TextView output;
    private Button write;
    private Button read;

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

        this.input = (EditText) findViewById(R.id.internal_storage_input);
        this.output = (TextView) findViewById(R.id.internal_storage_output);

        this.write = (Button) findViewById(R.id.internal_storage_write_button);
        this.write.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                write();
            }
        });

        this.read = (Button) findViewById(R.id.internal_storage_read_button);
        this.read.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                read();
            }
        });
    }

    private void write() {
        FileOutputStream fos = null;
        try {
            // note that there are many modes you can use
            fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
            fos.write(input.getText().toString().getBytes());
            Toast.makeText(this, "File written", Toast.LENGTH_SHORT).show();
            input.setText("");
            output.setText("");
        } catch (FileNotFoundException e) {
            Log.e("java2s.com", "File not found", e);
        } catch (IOException e) {
            Log.e("java2s.com", "IO problem", e);
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                // ignore, and take the verbosity punch from Java ;)
            }
        }
    }

    private void read() {
        FileInputStream fis = null;
        Scanner scanner = null;
        StringBuilder sb = new StringBuilder();
        try {
            fis = openFileInput("test.txt");
            // scanner does mean one more object, but it's easier to work with
            scanner = new Scanner(fis);
            while (scanner.hasNextLine()) {
                sb.append(scanner.nextLine() + LINE_SEP);
            }
            Toast.makeText(this, "File read", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Log.e("java2s.com", "File not found", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // ignore, and take the verbosity punch from Java ;)
                }
            }
            if (scanner != null) {
                scanner.close();
            }
        }
        output.setText(sb.toString());
    }
}
Write and read from Internal Storage

Next »
« Previous
Home »
Android »
Android Basics »

Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS
java2s.com | Email:info at java2s.com | © Demo Source and Support. All rights reserved.