Saturday, 29 October 2011

Change Java Symbol in Frame

We can Change the Java Coffee symbol into our own symbol,By using this code,



package com.symbol.test;

import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JFrame;


public class Test {

public Test() {
Image icon = Toolkit.getDefaultToolkit().getImage("lock_abt.png");
JFrame frame2 = new JFrame("Hi");
frame2.setIconImage(icon);
frame2.setVisible(true);
                frame2.setSize(250, 250);
}

public static void main(String[] args) {
Test test = new Test();

}
}


U can get the Output as,

See the Frame Image in Top left Corner

Saturday, 15 October 2011

List View With Index

To Display List view With Index,I created two layout,The first layout is,

separator.XML,From res/layout/separator.XML


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:id="@+id/textSeparator"
android:layout_height="wrap_content"
android:gravity="center"
android:visibility="visible"
android:layout_width="fill_parent"
android:textColor="#FFFFFF"
android:background="#808080" />
</LinearLayout>

And the List Item Layout must present in res/layout/list_item.XML


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:id="@+id/text"
android:layout_height="50dp"
android:gravity="center_vertical"
android:visibility="visible"
android:layout_width="fill_parent"
android:textColor="#FF000000"
android:background="#FFFFFFFF" />
</LinearLayout>


Below is the Code for List View With Index,

ListViewIndex.java




package com.test.list;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.TreeSet;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MultipleItemsList extends ListActivity {


static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania",
"Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
"Antarctica", "Antigua and Barbuda", "Argentina", "Armenia",
"Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Bouvet Island", "Brazil",
"British Indian Ocean Territory", "British Virgin Islands",
"Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cote d'Ivoire",
"Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
"Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia",
"Comoros", "Congo", "Cook Islands", "Costa Rica", "Croatia",
"Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti",
"Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt",
"El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
"Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji",
"Finland", "Former Yugoslav Republic of Macedonia", "France",
"French Guiana", "French Polynesia", "French Southern Territories",
"Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece",
"Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala",
"Guinea", "Guinea-Bissau", "Guyana", "Haiti",
"Heard Island and McDonald Islands", "Honduras", "Hong Kong",
"Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq",
"Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
"Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
"Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Madagascar",
"Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Martinique", "Mauritania", "Mauritius",
"Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia",
"Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
"New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria",
"Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama",
"Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe",
"Saint Helena", "Saint Kitts and Nevis", "Saint Lucia",
"Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
"Samoa", "San Marino", "Saudi Arabia", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Slovakia", "Slovenia",
"Solomon Islands", "Somalia", "South Africa",
"South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname",
"Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
"Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
"The Bahamas", "The Gambia", "Togo", "Tokelau", "Tonga",
"Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine",
"United Arab Emirates", "United Kingdom", "United States",
"United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
"Virgin Islands", "Vanuatu", "Vatican City", "Venezuela",
"Vietnam", "Wallis and Futuna", "Western Sahara", "Yemen",
"Yugoslavia", "Zambia", "Zimbabwe" };
private MyCustomAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();

Collections.sort(Arrays.asList(COUNTRIES)); //Sorting the Array
for (int i = 0; i < COUNTRIES.length - 1; i++) {

if (i == 0) {  
mAdapter.addSeparatorItem(COUNTRIES[i].toString().substring(0,
1));

} else if (COUNTRIES[i].toString().substring(0, 1).equalsIgnoreCase(COUNTRIES[i - 1].toString().substring(0, 1))) {  //Comparing previous position and current position


} else if (COUNTRIES[i + 1].toString().substring(0, 1)
.equalsIgnoreCase(COUNTRIES[i].toString().substring(0, 1))) {   //Comparing next position and current position

mAdapter.addSeparatorItem(COUNTRIES[i].toString().substring(0,
1));

} else {

mAdapter.addSeparatorItem(COUNTRIES[i].toString().substring(0,
1));

}
mAdapter.addItem(COUNTRIES[i].toString());

}
setListAdapter(mAdapter);
}

private class MyCustomAdapter extends BaseAdapter {

private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;

private final ArrayList<String> data = new ArrayList<String>();
private final LayoutInflater mInflater;

private final TreeSet<Integer> separator = new TreeSet<Integer>();

public MyCustomAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public void addItem(final String item) {
data.add(item);
notifyDataSetChanged();
}

public void addSeparatorItem(final String item) {
data.add(item);
// save separator position
separator.add(data.size() - 1);
notifyDataSetChanged();
}

@Override
public int getItemViewType(int position) {
return separator.contains(position) ? TYPE_SEPARATOR
: TYPE_ITEM;
}

@Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}

@Override
public int getCount() {
return data.size();
}

@Override
public String getItem(int position) {
return data.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + view
+ " type = " + type);
if (view == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
view = mInflater.inflate(R.layout.list_item, null);
holder.textView = (TextView) view
.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
view = mInflater.inflate(R.layout.separator, null);
holder.textView = (TextView) view
.findViewById(R.id.textSeparator);
break;
}
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.textView.setText(data.get(position));
return view;
}

}

public static class ViewHolder {
public TextView textView;
}
}


And Here is the Output Window.





Friday, 14 October 2011

Custom List View with Search Box

To generate Custom List View in our application,we need to create List View in main. XML,

The main.XML file is look like this,


<?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/search" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:hint="Search"
    />
    <ListView 
         android:id="@+id/custom" 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content">
   </ListView>
</LinearLayout>



Here I used one Edit text in the top of the List View,the Edit Text will show when user clicked search menu item from menu,

Here is my source code of custom List View.,




package com.custom.listview;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;


import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;


public class CustomListView extends Activity {


EditText search_box;
ListView custom_list;
static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania",
"Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
"Antarctica", "Antigua and Barbuda", "Argentina", "Armenia",
"Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Bouvet Island", "Brazil",
"British Indian Ocean Territory", "British Virgin Islands",
"Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cote d'Ivoire",
"Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
"Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia",
"Comoros", "Congo", "Cook Islands", "Costa Rica", "Croatia",
"Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti",
"Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt",
"El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
"Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji",
"Finland", "Former Yugoslav Republic of Macedonia", "France",
"French Guiana", "French Polynesia", "French Southern Territories",
"Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece",
"Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala",
"Guinea", "Guinea-Bissau", "Guyana", "Haiti",
"Heard Island and McDonald Islands", "Honduras", "Hong Kong",
"Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq",
"Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
"Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
"Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Madagascar",
"Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Martinique", "Mauritania", "Mauritius",
"Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia",
"Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
"New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria",
"Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama",
"Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe",
"Saint Helena", "Saint Kitts and Nevis", "Saint Lucia",
"Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
"Samoa", "San Marino", "Saudi Arabia", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Slovakia", "Slovenia",
"Solomon Islands", "Somalia", "South Africa",
"South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname",
"Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
"Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
"The Bahamas", "The Gambia", "Togo", "Tokelau", "Tonga",
"Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay",
"Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam",
"Wallis and Futuna", "Western Sahara", "Yemen", "Yugoslavia",
"Zambia", "Zimbabwe" };


ArrayList<String> searched_list;


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


search_box = (EditText) findViewById(R.id.search);
custom_list = (ListView) findViewById(R.id.custom);
Collections.shuffle(Arrays.asList(COUNTRIES));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_list_item_1,
COUNTRIES);
custom_list.setAdapter(adapter);

search_box.setVisibility(View.GONE);
searched_list = new ArrayList<String>();
search_box.addTextChangedListener(new TextWatcher() {


@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
int length = search_box.getText().length();
searched_list.clear();


for (int i = 0; i < COUNTRIES.length; i++) {
if (length <= COUNTRIES[i].length()) {
if (search_box.getText().toString().equalsIgnoreCase((String)COUNTRIES[i].subSequence(0,
length))) {
searched_list.add(COUNTRIES[i].toString());
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1, searched_list);
custom_list.setAdapter(adapter);


}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub


}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub


}
});
}


@Override
public boolean onCreateOptionsMenu(final Menu menu) {
// call the base class to include system menus
super.onCreateOptionsMenu(menu);

// Group 1
final int group1 = 1;
final MenuItem infoBtn = menu.add(group1, 1, 1, "Search").setIcon(R.drawable.icon);


// Group 2
final int group2 = 2;
final MenuItem appSettings = menu.add(group2, 2, 2, "Cancel").setIcon(R.drawable.icon);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1: {
search_box.setVisibility(View.VISIBLE);
break;
}
case 2: {
search_box.setVisibility(View.GONE);
break;
}
}
return false;
}


@Override
public void onBackPressed() {                  //It will work only on v2.2 and above 
search_box.setVisibility(View.GONE);
}
}




And here is the Output:














Saturday, 8 October 2011

Parse XML file in Android

Below is the XML file,we going to parse..

The XML file must present in res/raw/books.XML


<?xml version="1.0"?>
<catalog>


   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>


   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>


   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>


   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>


   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>


   <book id="bk106">
      <author>Randall, Cynthia</author>
      <title>Lover Birds</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-09-02</publish_date>
      <description>When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.</description>
   </book>


   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty
      thousand leagues beneath the sea.</description>
   </book>


   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.</description>
   </book>


   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.</description>
   </book>


   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.</description>
   </book>


   <book id="bk111">
      <author>O'Brien, Tim</author>
      <title>MSXML3: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-01</publish_date>
      <description>The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.</description>
   </book>


   <book id="bk112">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
   </book>


</catalog>



This is the code to parse XML file from raw folder.


import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

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

public class ResourceParsing extends Activity {
/** Called when the activity is first created. */
File file;
DocumentBuilder db;
Document d;
TextView[] author;
TextView[] title;
LinearLayout layout;
ScrollView scrollview;

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

InputSource myInputSource = new InputSource(this.getResources()
.openRawResource(R.raw.books));
scrollview= new ScrollView(this);
layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
db = dbf.newDocumentBuilder();
d = db.parse(myInputSource);
d.getDocumentElement().normalize();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NodeList nodeList = d.getElementsByTagName(new String("book"));
System.out.println(nodeList.getLength());
author = new TextView[nodeList.getLength()];
title = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println(node.getNodeName());
author[i] = new TextView(this);
System.out.println(author[i].getText());
Element element = (Element) node;
NodeList nameList = element.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
author[i].setText("author = " + (nameList.item(0)).getNodeValue());
System.out.println((nameList.item(0)).getNodeValue());

Node node1 = nodeList.item(i);
System.out.println(node1.getNodeName());
title[i] = new TextView(this);
System.out.println(title[i].getText());
Element element1 = (Element) node;
NodeList nameList1 = element1.getElementsByTagName("title");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
title[i].setText("Title = " + (nameList1.item(0)).getNodeValue());
System.out.println((nameList1.item(0)).getNodeValue());
layout.addView(author[i]);
layout.addView(title[i]);
}
scrollview.addView(layout);
setContentView(scrollview);
}
}



The Output Screen will look like this..





Saturday, 1 October 2011

Check and Create Directory inside SD Card


                     

         If you need to access the SD card means,First you have to get this permission,

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


in Android Manifest. XML file.

Here the Code to Create a Directory inside SD Card



public class CheckAndCreateDir extends Activity {
/** Called when the activity is first created. */

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

try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
File sdCard = Environment.getExternalStorageDirectory(); //getting sdcard content
File check = new File(Environment.getExternalStorageDirectory()
+ "/your own Director name"); //getting our own directory path
if (check.exists()) { //checking our own directory is present or not
if (check.isDirectory()) { //checking that path is directory or not
File[] list = check.listFiles(); //getting list of files inside the directory
int size = list.length;
if (size == 0) {
file = new File(check, "Android");
file.createNewFile(); //Creating a new file inside our directory
FileOutputStream f = new FileOutputStream(file);
f.write("Hai This is First Text".getBytes());  //writing value inside that file
f.close();
Log.v("Created","=======>>Created Successfully<<=======");
} else {
FileWriter file_writer = new FileWriter(check+ "/Android", true);
BufferedWriter Buffered_writer = new BufferedWriter(file_writer);
Buffered_writer.write(" This is Second Text");
Buffered_writer.close();
Log.v("Append","=======>>Appended Successfully<<=======");
}
}
} else {
System.out.println("===========Directory Not Present=========");
check.mkdirs();
}


}

} catch (Exception e) {
}
}
}


After run this application,Change the mode of USB debugging from charge the phone to disk drive.

Then Check the folder is present or not in removable disk.


You can see below Screen inside the folder.