Saturday, 1 June 2013

XML Pasring in Android

Files Used:-
XMLParsingExample.java ( Main Activity )
SitesList.java ( Getter & Setter Method )
MyXMLHandler.java ( XML Handling )
example.xml ( XML file from net )

The output will looks similar to



example.xml ( http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml )
[sourcecode language="xml"]
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
[/sourcecode]
If tag names are different, then we can use string to set & get the value. But here item,name & website tags are repeating 2 times.
So we can use ArrayList to store & get the data.
XMLParsingExample.java
This is main activity class. when App. starts this file will be called first.
This file contains how to use SAX Parser to handle XML tags.
[sourcecode language="java"]

package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingExample extends Activity
{
    /** Create Object For SiteList Class */
    SitesList sitesList = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(1);
        /** Create a new textview array to display the results */
        TextView name[];
        TextView website[];
        TextView category[];
        try
        {
            /** Handling XML */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            /** Send URL to parse XML Tags */
            URL sourceUrl = new URL(
                "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));
        }
        catch (Exception e)
        {
            System.out.println("XML Pasing Excpetion = " + e);
        }
        /** Get result from MyXMLHandler SitlesList Object */
        sitesList = MyXMLHandler.sitesList;
        /** Assign textview array lenght by arraylist size */
        name = new TextView[sitesList.getName().size()];
        website = new TextView[sitesList.getName().size()];
        category = new TextView[sitesList.getName().size()];
        /** Set the result text in textview and add it to layout */
        for (int i = 0; i < sitesList.getName().size(); i++)
        {
            name[i] = new TextView(this);
            name[i].setText("Name = "+sitesList.getName().get(i));
            website[i] = new TextView(this);
            website[i].setText("Website = "+sitesList.getWebsite().get(i));
            category[i] = new TextView(this);
            category[i].setText("Website Category = "+sitesList.getCategory().get(i));
            layout.addView(name[i]);
            layout.addView(website[i]);
            layout.addView(category[i]);
        }
        /** Set the layout view to display */
        setContentView(layout);
    }
}
[/sourcecode]
MyXMLHandler.java
This file is used to handle the XML tags. So we need to extends with DefaultHandler.
we need to override startElement, endElement & characters method .
startElemnt method called when the tag starts.
endElemnt method called when the tag ends
characres method to get characters inside tag.
[sourcecode language="java"]

package com.androidpeople.xml.parsing;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler
{
    Boolean currentElement = false;
    String currentValue = null;
    public static SitesList sitesList = null;
    public static SitesList getSitesList()
    {
        return sitesList;
    }
    public static void setSitesList(SitesList sitesList)
    {
        MyXMLHandler.sitesList = sitesList;
    }
    /** Called when tag starts ( ex:- <name>AndroidPeople</name>
    * -- <name> )*/
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException
    {
        currentElement = true;
        if (localName.equals("maintag"))
        {
            /** Start */
            sitesList = new SitesList();
        }
        else if (localName.equals("website"))
        {
            /** Get attribute value */
            String attr = attributes.getValue("category");
            sitesList.setCategory(attr);
        }
    }
    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
    * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
    throws SAXException
    {
        currentElement = false;
        /** set value */
        if (localName.equalsIgnoreCase("name"))
            sitesList.setName(currentValue);
        else if (localName.equalsIgnoreCase("website"))
            sitesList.setWebsite(currentValue);
    }
    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
    * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
    throws SAXException
    {
        if (currentElement)
        {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }
    }
}
[/sourcecode]

SitesList.java

Contains Getter & Setter Method

[sourcecode language="java"]
package com.androidpeople.xml.parsing;
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList
{
    /** Variables */
    private ArrayList<String> name = new ArrayList<String>();
    private ArrayList<String> website = new ArrayList<String>();
    private ArrayList<String> category = new ArrayList<String>();
    /** In Setter method default it will return arraylist
    * change that to add */
    public ArrayList<String> getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name.add(name);
    }
    public ArrayList<String> getWebsite()
    {
        return website;
    }
    public void setWebsite(String website)
    {
        this.website.add(website);
    }
    public ArrayList<String> getCategory()
    {
        return category;
    }
    public void setCategory(String category)
    {
        this.category.add(category);
    }
}

Json parsing in Android

main.xml

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

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

</LinearLayout>


Json_ReadActivity :

public class Json_ReadActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        String readTwitterFeed  = readTwitterFeed();
     
        try {
JSONArray jsonArray = new JSONArray(readTwitterFeed); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i);
} } catch (Exception e) { e.printStackTrace(); }
    }
 
    public String readTwitterFeed()
    {
   
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
   
    HttpGet httpget = new HttpGet("Your 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) { builder.append(line); } }
    else
    {
Log.e(Json_ReadActivity.class.toString(), "Failed to download file"); }  
   
    }catch (ClientProtocolException e) {
// TODO: handle exception
    e.printStackTrace();
}
    catch (IOException e) {
e.printStackTrace(); } return builder.toString();
   
   
    }

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

Create Database in Android

public class MyDatabaseDemo extends Activity
{private static final String DATABASE_NAME = "JADB.db";
private static final String DATABASE_TABLE = "myTable";
private static final String DATABASE_CREATE = "create table "+DATABASE_TABLE+" (_id integer
primary key autoincrement, col1 text not null);";


//for create the databse .

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button butCreate = (Button)findViewById(R.id.myButCreate);
Button butAdd = (Button)findViewById(R.id.myButAdd);
Button butCount = (Button)findViewById(R.id.myButCount);
Button butShow = (Button)findViewById(R.id.myButShow);
butCreate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
myDB.execSQL(DATABASE_CREATE);
myDB.close();
Toast.makeText(getApplicationContext(), "Table created",
Toast.LENGTH_SHORT).show();
}
});

//for add data.

butAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
ContentValues newRow = new ContentValues();
newRow.put("col1", "ok");
myDB.insert(DATABASE_TABLE, null, newRow);
myDB.close();
Toast.makeText(getApplicationContext(), "row added", Toast.LENGTH_SHORT).show();
}
});

//for count records.

butCount.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
String[] resultColumns = new String[] {"_id", "col1"};
Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null);
Integer c = allRows.getCount();
myDB.close();
Toast.makeText(getApplicationContext(), "count: "+c.toString(), Toast.LENGTH_SHORT).show();
}
});

//for show rows.

butShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
String[] resultColumns = new String[] {"_id", "col1"};
Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null);
String res = "RESULT IS:";
Integer cindex = allRows.getColumnIndex("col1");
if (allRows.moveToFirst()) {
do {
res += allRows.getString(cindex)+"-";
} while (allRows.moveToNext());
}
myDB.close();

SOAP in Android


Soap in Android

In this post I'm going to illustrate how we can access web service in Android usingksoap2-android project that provides a lightweight and efficient SOAP library for the Android platform. 

You can download the jar file from following link; 
http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.8/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar 

After that just follow these steps:

-> Creating a folder "libs" in the project
-> Copying the external jars in to the folder
-> Refresh the folder
-> Go to properties -> Build path -> Add Jar (not external JAR)
-> Clean the project
-> Restart Eclipse 


AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pxr.tutorial.soap.weather"
      android:versionCode="1"
      android:versionName="1.0">
    <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-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest> 

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

    <EditText
        android:id="@+id/txt_from_currency" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="FromCurrency"/>
      <EditText
         android:id="@+id/txt_to_currency" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="ToCurrency"/> 
     <Button 
         android:id="@+id/btn"
         android:layout_height="wrap_content"
         android:layout_width="fill_parent"
         android:text="Submit"/>
     <TextView  
android:id="@+id/lbl_rate"
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent"   
   android:gravity="center"
   android:textSize="40dip" />
</LinearLayout>

Main.java


public class Main extends Activity {

private final String NAMESPACE = "http://www.webserviceX.NET/";
private final String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
private final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
private final String METHOD_NAME = "ConversionRate";
    
    EditText from;
    EditText to;
    Button btn;
    TextView rate;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        from = (EditText)findViewById(R.id.txt_from_currency);
        to = (EditText)findViewById(R.id.txt_to_currency);
        btn = (Button)findViewById(R.id.btn);        
        rate = (TextView)findViewById(R.id.lbl_rate);
        
        
        btn.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

String from_ = from.getText().toString();
String to_ = to.getText().toString();

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        
       PropertyInfo _from =new PropertyInfo();
       _from.setName("FromCurrency");
       _from.setValue(from_);
       _from.setType(double.class);
       request.addProperty(_from);
       
       PropertyInfo _to =new PropertyInfo();
       _to.setName("ToCurrency");
       _to.setValue(to_);
       _to.setType(double.class);
       request.addProperty(_to);          
       
        
       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
       envelope.dotNet = true;
       envelope.setOutputSoapObject(request);
       HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
 
       try 
       {
               
           androidHttpTransport.call(SOAP_ACTION, envelope);          
           SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
          
           //SoapObject result = (SoapObject)envelope.getResponse();
           
           rate.setText(result.toString());

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




Read csv file in Android

InputStream is = getResources().openRawResource(R.raw.your_csv_file);
     
        try
        {
       
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
       
        while ((line = reader.readLine()) != null )
        {
String [] rowData = line.split(",");

String val1 = rowData[0];
String val2 = rowData[1];

                              //and so on...

    }


        }
        catch (FileNotFoundException e)
        {
// TODO Auto-generated catch block
e.printStackTrace();

        } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to delete Facebook Account?

1. Go to this link: http://www.facebook.com/help/delete_account

2. The above link takes you to a page carrying an ‘account deletion form’, where we need to confirm and verify our deletion again.

3. Submit the form, and you are done!