Thursday, August 18, 2011

ListView in Android (Advance)

We have already know how to show the list in Android see tutorial ListView in Android (Basic)


This tutorial describes how to use ListView and ListActivity in Android.
While we will create array list in a separate XML file.
also it will show the new page when you click on List Item.

Project Structure is look like this


okay! so let's try this small app 


 -------------------------------------------
App Name: ListViewBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default ListActivity Name: ActivityListView
------------------------------------------- 

ActivityListView.java


package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ActivityGamesList extends Activity {

 private String[] gamelistArray;
 private String[] gameDetailsListArray;
 private ListView listGames = null;
 ArrayAdapter<String> adapter;

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

  listGames = (ListView) findViewById(R.id.listViewGame);
  gamelistArray = getResources().getStringArray(R.array.gameslist);
  gameDetailsListArray = getResources().getStringArray(
    R.array.gamesDetails);

  adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, android.R.id.text1,
    gamelistArray);

  listGames.setAdapter(adapter);

  listGames.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {

    // Get the item that was clicked
    Object itemName = listGames.getItemAtPosition(position);
    String keyword = itemName.toString();
    String info = gameDetailsListArray[position];
    Toast.makeText(getApplicationContext(),
    "You have selected:  " + keyword, Toast.LENGTH_SHORT)
      .show();
    Intent i = new Intent(getBaseContext(),
      ActivityGameDetails.class);
    i.putExtra("info", info);
    i.putExtra("name", keyword);
    startActivity(i);

   }
  });
 }
}


ActivityGameDetails.java
package com.rdc;

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

public class ActivityGameDetails extends Activity {

 private TextView txtTitle = null;
 private TextView txtDetails = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.game_details);
  Bundle bundle = new Bundle();
  String info = getIntent().getStringExtra("info");
  txtTitle = (TextView) findViewById(R.id.textView1);
  txtTitle.setText(info);
  String name = getIntent().getStringExtra("name");
  txtDetails = (TextView) findViewById(R.id.txtgamedetailsTitle);
  txtDetails.setText("Details of " + name);
 }
}


create these xml files in res/layout folder 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="match_parent"
 android:layout_height="match_parent">
 <ListView
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:id="@+id/listViewGame"></ListView>

</LinearLayout>

game_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:weightSum="1">
 <TextView
  android:text="TextView"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:layout_weight="0.30"
  android:gravity="center"
  android:textSize="20sp"
  android:id="@+id/txtgamedetailsTitle"></TextView>
 <ScrollView
  android:id="@+id/layscroll"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.70">
  <TextView
   android:id="@+id/textView1"
   android:text="@string/gameDetails"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"></TextView>
 </ScrollView>

</LinearLayout>


create these below xml files in res/values folder arraylist_games.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
       <string-array name="gameslist">
        <item>Soccer</item>
        <item>Cricket</item>
        <item>Chess</item>
        <item>WWE</item>
        <item>NFS Most Wanted</item>
        <item>Counter Strike</item>
        <item>Angry Birds</item>
        <item>Lord of the Rings</item>
        <item>Mario</item>
        <item>Prince of Persia</item>
        <item>Resident Evil</item>
        <item>Far Cry</item>
        <item>Minesweeper</item>
        <item>Jumper</item>      
        
    </string-array>
       
    
    <string-array name="gamesDetails">
        <item>Association football, more commonly known as football or soccer, is a sport played between two teams of eleven players with a spherical ball. At the turn of the 21st century, the game was played by over 250 million players in over 200 countries, making it the world\'s most popular sport..</item>
        <item>Cricket is a bat-and-ball game played between two teams of 11 players on a field, at the centre of which is a rectangular 22-yard long pitch</item>
        <item>Chess is a two-player board game played on a chessboard, a square checkered board with 64 squares arranged in an eight-by-eight grid.</item>
        <item> WWE is an American publicly traded, privately controlled entertainment company dealing primarily in professional wrestling which despite being scripted and not real are very popular, with major revenue sources also coming from film, music, product licensing, and direct product sales.</item>
        <item>Need for Speed: Most Wanted is an upcoming 2012 racing video game, developed by British games developer Criterion Games and published by Electronic Arts. Announced on 4 June 2012, during EA\'s E3 press conference, Most Wanted is the nineteenth title in the long-running Need for Speed series and second game in the Most Wanted series.</item>
        <item>The game was the most played Half-Life modification in terms of players, according to GameSpy in 2008.</item>
        <item>Angry Birds is a strategy puzzle video game developed by Finnish computer game developer Rovio Mobile. Inspired primarily by a sketch of stylized wingless birds, the game was first released for Apple\'s iOS in December 2009.</item>
        <item>The Lord of the Rings is an epic film trilogy consisting of three fantasy adventure films, directed by Peter Jackson, based on the three-volume book of the same name by English author J. R. R. Tolkien.</item>
        <item>Mario is a fictional character in the Mario video game franchise by Nintendo, created by Japanese video game designer Shigeru Miyamoto. Serving as Nintendo\'s mascot and the eponymous protagonist of the series, Mario has appeared in over 200 video games since his creation.</item>
        <item>Prince of Persia is a video game franchise created by Jordan Mechner, originally developed for and released on the Apple II Computer in 1989. The original game and its first sequel were 2D platform games, but the series made the switch to three-dimensional following the release of Prince of Persia 3D in 1999.</item>
        <item>Resident Evil, originally released as Bio Hazardin Japan, is a survival horror video game by Capcom. The first installment in the Resident Evil series was originally released in 1996 for the PlayStation and was soon ported to the Sega Saturn and PC, as well as the Nintendo DS some years later.</item>
        <item>Far Cry is first-person shooter video game developed by Crytek Studios and published by Ubisoft on March 23, 2004, for Microsoft Windows. Far Cry sold 730,000 units within four months of release.It received positive reviews upon release. The original game has since spawned a series of sequels and spin-off games and a movie.</item>
        <item>Minesweeper is a single-player video game. The object of the game is to clear an abstract minefield without detonating a mine. </item>
        <item>City Jumper : You can leap over buildings in a single bound, but scrape your back on the Golden Gate bridge and you will be cut in half.</item>
        
    </string-array>    
</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

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

  <activity
   android:name=".ActivityGameDetails"
   android:label="Game Details">
   <intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The output Screen will be like this..
                                   
                                                                Games Name List

When you select any one it will show the Game Details like this..



You can download the complete source code zip file here : ListViewAdvance

 cheers!!

 I'd love to hear your thoughts!

Wednesday, August 10, 2011

ListView in Android (Basic)

ListView: ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array and converts each item result into a view that's placed into the list.

This tutorial describes how to use ListView and ListActivity in Android.

okay! so let's try this small app


 -------------------------------------------
App Name: ListViewBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default ListActivity Name: ActivityListView
-------------------------------------------


ActivityListView.java






package com.rdc;

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 ActivityListView extends ListActivity {

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

 // Create an array of Strings, that will be put to our ListActivity
 String[] namesArray = new String[] { "Linux", "Windows7", "Eclipse",
    "Suse", "Ubuntu", "Solaris", "Android", "iPhone" };
 
 /* Create an ArrayAdapter, that will actually make the Strings above
  appear in the ListView */
 this.setListAdapter(new ArrayAdapter<String>(this,
   android.R.layout.simple_list_item_1, namesArray));
 }

  @Override
  protected void onListItemClick(ListView l, View v, 
  int position, long id) {
 super.onListItemClick(l, v, position, id);
 
 // Get the item that was clicked
 Object o = this.getListAdapter().getItem(position);
 String keyword = o.toString();
 Toast.makeText(this, "You selected: " + keyword, 
   Toast.LENGTH_SHORT).show();
 }
}

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>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

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

The output Screen will be like this..


You can download the complete source code zip file here : ListViewBasic 

 cheers!!

 I'd love to hear your thoughts!

Tuesday, August 2, 2011

Download Image from URL in Android

Some time we need to download Image from Internet (specific URL)..
how can we achieve this i am going to write step by step.

We will download image from internet and show on Image View


-------------------------------------------
App Name: DownloadImageFromURL
Package Name: com.rdc
Android SDK: Android SDK 2.2 / API 8
Default Activity Name: DownloadImageFromURL
-------------------------------------------


DownloadImageFromURL.java
package com.rdc;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class DownloadImageFromURL extends Activity {

 private ImageView img = null;

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

  Bitmap bitmap = DownloadImage
 ("http://www.streetcar.org/streetcars/uploads/560px/560-130.png");

  img = (ImageView) findViewById(R.id.imageView);
  img.setImageBitmap(bitmap);
 }

 private Bitmap DownloadImage(String URL) {
  Bitmap bitmap = null;
  InputStream in = null;
  try {
   in = OpenHttpConnection(URL);
   bitmap = BitmapFactory.decodeStream(in);
   in.close();
  } catch (IOException e1) {
   Toast.makeText(this, e1.getLocalizedMessage(), 
                                       Toast.LENGTH_SHORT)
     .show();
   e1.printStackTrace();
  }
  return bitmap;
 }

 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 and 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 Connectiong");
  }
  return in;
 }
}

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"
 android:weightSum="1">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.04"
  android:text="The image downlaoded from Internet" >
  </TextView>
 <ImageView
  android:layout_height="wrap_content"
  android:src="@drawable/icon"
  android:layout_width="match_parent"
  android:layout_weight="0.35"
  android:id="@+id/imageView">
  </ImageView>
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="8" />

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

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

The output Screen will be like this..


You can download the complete source code zip file here : DownloadImageFromURL

 cheers!!

 I'd love to hear your thoughts!