Skip to main content

Parsing an XML from Online in Android

Create a fresh project and name it ParseXMLDemo
Then in the ParseXMLDemo.java file copy this code
|
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ParseXMLDemo extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        ArrayList<String> mylist = new ArrayList<String>();
        String xml = ParseXMLMethods.getXML();
        Document doc = ParseXMLMethods.XMLfromString(xml);
        int numResults = ParseXMLMethods.numResults(doc);

        if((numResults <= 0)){
          Toast.makeText(ParseXMLDemo.this, "There is no data in the xml file", Toast.LENGTH_LONG).show();
              finish();
        }

        NodeList children = doc.getElementsByTagName("os");
        for (int i = 0; i < children.getLength(); i++)
          {
            HashMap<string string=""> map =new HashMap<string string="">();
            Element e = (Element)children.item(i);
            map.put("id", ParseXMLMethods.getValue(e, "id"));
            map.put("name", ParseXMLMethods.getValue(e, "name"));
            map.put("site", ParseXMLMethods.getValue(e, "site"));
            mylist.add(map);
          }
        ListAdapter adapter = new SimpleAdapter(this,mylist ,R .layout.list_layout,
                          new String[] { "name", "site" },
                          new int[] { R.id.title, R.id.subtitle});

       setListAdapter(adapter);

       
        final ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                Toast.makeText(ParseXMLDemo.this,o.get("name"), Toast.LENGTH_LONG).show();
            }
        });
    } }
            

Now create another java file inside the src folder and name it ParseXMLMethods.java and copy this contents into it.
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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;

public class ParseXMLMethods {

    public final static Document XMLfromString(String xml){

        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);
        }  
            catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        }
            catch (SAXException e) {
            System.out.println("Wrong XML file structure: " +e.getMessage());
            return null;
        }
            catch (IOException e) {
            System.out.println("I/O exeption: " +e.getMessage());
            return null;
        }
        return doc;
    }
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null;kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }
     public static String getXML(){
            String line = null;
            try {
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpPost httpPost = new HttpPost("http://new ABC.com/xml/test.xml");
           HttpResponse httpResponse = httpClient.execute(httpPost);
           HttpEntity httpEntity = httpResponse.getEntity();
           line = EntityUtils.toString(httpEntity);
            } catch (Exception e) {
             line = "Internet Connection Error >> " + e.getMessage();
            }
            return line;
    }

    public static int numResults(Document doc)
      {
        Node results = doc.getDocumentElement();
        int res = -1;
        try
        {
          res = Integer.valueOf(results.getAttributes()
                         .getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }
        return res;
    }

    public static String getValue(Element item, String str)
    {
        NodeList n = item.getElementsByTagName(str);
        return ParseXMLMethods.getElementValue(n.item(0));
    }
}
in main.xml:
<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="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#FF0000"
        android:drawSelectorOnTop="false"/> 
</LinearLayout> 
list_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"
    android:padding="7dp"> 
<TextView
    android:id="@+id/title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp"
    android:textStyle="bold"/> 
    <TextView
    android:id="@+id/subtitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:textSize="14dp"
    android:textColor="#000000"/> 
</LinearLayout> 
Strings.xml:
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string name="hello"> Hello World, ParseXMLDemo!</string> 
    <string name="app_name"> ParseXMLDemo New ABC.com</string> 
</resources> 

Comments

Popular posts from this blog

Passing Images between Activities in Android

in First Activity:
Intent intent=new Intent(FirstClass.this, SecondClass.class); Bundle bundle=new Bundle(); bundle.putInt("image",R.drawable.ic_launcher); intent.putExtras(bundle); startActivity(intent); in Second Acticity:
Bundle bundle=this.getIntent().getExtras(); int pic=bundle.getInt("image"); v.setImageResource(pic);another method:
in First Activity:
Drawable drawable=imgv.getDrawable(); Bitmap bitmap= ((BitmapDrawable)drawable).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); Intent intent=new Intent(Passimage.this,myclass.class); intent.putExtra("picture", b); startActivity(intent); in Second Acticity:
Bundle extras = getIntent().getExtras(); byte[] b = extras.getByteArray("picture"); Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length); Image…

Get a single record from SQLite in ANDROID

For COMPLETE TUTORIALS see here :
in DATABASE HELPER class: String[] coloumns = new String[] { KEY_ROWID, KEY_NAME, KEY_NICKNAME }; // calling elements in an array Cursor c = db.query(DATABASE_TABLE, coloumns, KEY_ROWID + "=" + l,null, null, null, null); if (c != null) { c.moveToFirst(); String name = c.getString(1); // since name is in position 1 ie second coloumn return name; } return null; in sqlite.java : String s =editinfo.getText().toString(); long l=Long.parseLong(s); DBAdapter adapter=new DBAdapter(SQliteExample.this); adapter.open(); String returnedname=adapter.returnName(l); String returnednickname=adapter.returnickname(l); adapter.close(); editName.setText(returnedname); editNickName.setText(returnednickname);

TextView Animation or Alpha animation (FadeIn , FadeOut) in ANDROID

An Alpha Animation is animation that controls the alpha level of an object, i.e. fading it in and out. In Android, you can apply that fading effect to almost anything, from simple text, to images, buttons, check boxes, etc…

This can be done both from xml and from java class.

Here I will explain a simple way to give a FadeIn and FadeOut for a textview on button click.. public class Textviewanimation extends Activity { Animation fadeIn,fadeOut; TextView tv; Button startanimation; Boolean fadeflag=true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_textviewanimation); tv=(TextView) findViewById(R.id.textview); startanimation=(Button) findViewById(R.id.button1); fadeIn = new AlphaAnimation(0.0f , 1.0f ) ; fadeIn.setDuration(1200); fadeIn.setFillAfter(true); fadeOut = new AlphaAnimation(1.0f , 0.0f); fadeOut.setDurati…