Friday, 12 September 2014

example for parsing methods using Saxparsers

Step1 : for getting single tag value use below code:


public static ArrayList getListByTag(String msg,final String tag){
 
final ArrayList list=new ArrayList();
try{
list.clear();  
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
// parser.parse(is, dh)//
parser.parse(new InputSource(new StringReader(msg)),new DefaultHandler(){
boolean tag_value=false; 
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equalsIgnoreCase(tag)){
tag_value=true; 
}
 
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(tag_value){
list.add(new String(ch,start,length));  
}
}   
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(qName.equalsIgnoreCase(tag)){
tag_value=false; 
}
});  
}catch (Exception e) {
e.printStackTrace(); 
}
return list; 
}  






Step 2 : for getting list of tag values use below code:



public static ArrayList> getListofHouseHoldsByTag(String msg , final String tag){
final ArrayList>  list_values=new ArrayList>();  
 
try{
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();

 
parser.parse(new InputSource(new StringReader(msg)),new DefaultHandler(){

ArrayList list;
boolean tag_value=false; 
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equalsIgnoreCase(tag)){
tag_value=true; 
list=new ArrayList();
}  
 
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(tag_value){
list.add(new String(ch,start,length));  
}   
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(qName.equalsIgnoreCase(tag)){
tag_value=false;  
list_values.add(list);   
}
}
});  
}catch (Exception e) {
e.printStackTrace(); 
}
return list_values;   


Friday, 5 September 2014

expandablelistview example in android

Step1: Create a project with the name of MainActivity.

Step2: design activity_main.xml and add code as below..
 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

            android:id="@+id/laptop_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"/>  





Step3: add new xml file with the name of  group_item.xml and add code as below.

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

            android:id="@+id/laptop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Small Text"
        android:paddingLeft="25dp"
        android:textAppearance="?android:attr/textAppearanceSmall" />




Step4: add new xml file with the name of  Child_item.xml and add code as below.

    android:layout_width="match_parent"
    android:layout_height="match_parent">

              android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_delete"
        android:contentDescription="@string/app_name"/>

              android:id="@+id/laptop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/delete"
        android:layout_alignParentLeft="true"
        android:text="textview"
        android:paddingLeft="25dp" />





Step5: add code in MainActivity.java

package com.example.expandablelistviewex;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

public class MainActivity extends Activity
{
ExpandableListView expListView;
List groupList;
List childList;
Map> laptopCollection;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expListView=(ExpandableListView)findViewById(R.id.laptop_list);
createGroupList();
createCollection();

final ExpandableListAdapter expandableListadapter=new ExpandableListAdapter(this,groupList,laptopCollection);
expListView.setAdapter(expandableListadapter);

//setGroupIndicatorToRight();
expListView.setOnChildClickListener(new OnChildClickListener()
{
           public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
           {
               final String selected = (String) expandableListadapter.getChild(groupPosition, childPosition);
               Toast.makeText(getBaseContext(), selected, Toast.LENGTH_LONG).show();
         
               return true;
           }
       });
}
public void createGroupList()
{
groupList=new ArrayList();
groupList.add("HP");
        groupList.add("Dell");
        groupList.add("Lenovo");
        groupList.add("Sony");
        groupList.add("HCL");
        groupList.add("Samsung");
}

public void createCollection()
{
String[] hpModels = { "HP Pavilion G6-2014TX", "ProBook HP 4540","HP Envy 4-1025TX" };
String[] hclModels = { "HCL S2101", "HCL L2102", "HCL V2002" };
String[] lenovoModels = { "IdeaPad Z Series", "Essential G Series","ThinkPad X Series", "Ideapad Z Series" };
String[] sonyModels = { "VAIO E Series", "VAIO Z Series","VAIO S Series", "VAIO YB Series" };
String[] dellModels = { "Inspiron", "Vostro", "XPS" };
String[] samsungModels = { "NP Series", "Series 5", "SF Series" };

laptopCollection=new LinkedHashMap>();
        for(String laptop:groupList)
        {
        if(laptop.equalsIgnoreCase("HP"))
        {
        loadchild(hpModels);
        }
        else if(laptop.equalsIgnoreCase("Dell"))
        {
        loadchild(dellModels);
        }
        else if(laptop.equalsIgnoreCase("Lenovo"))
        {
        loadchild(lenovoModels);
        }
       
        else if(laptop.equalsIgnoreCase("Sony"))
        {
        loadchild(sonyModels);
        }
        else if(laptop.equalsIgnoreCase("HCL"))
        {
        loadchild(hclModels);
        }
        else if(laptop.equalsIgnoreCase("Samsung"))
        {
        loadchild(samsungModels);
        }
       
       
        laptopCollection.put(laptop, childList);
        }
}
private void loadchild(String[] laptopmodels)
{
childList=new ArrayList();
for(String models:laptopmodels)
{
childList.add(models);
}
}

private void setGroupIndicatorToRight()
{
        /* Get the screen width */
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        expListView.setIndicatorBounds(width - getDipsFromPixel(35), width- getDipsFromPixel(5));
    }
private int getDipsFromPixel(float pixels)
{
 // Get the screen's density scale
        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale
        return (int) (pixels * scale + 0.5f);
}

}

Step6: Add adapter class with the name of  ExpandableListAdapter.java and add the following code like as below.

package com.example.expandablelistviewex;

import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ExpandableListAdapter extends BaseExpandableListAdapter
{
MainActivity mainActivity;
List laptops;
Map> laptopCollection;

public ExpandableListAdapter(MainActivity mainActivity,List groupList, Map> laptopCollection) 
{

this.mainActivity=mainActivity;
this.laptops=groupList;
this.laptopCollection=laptopCollection;
}


public Object getChild(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return laptopCollection.get(laptops.get(groupPosition)).get(childPosition);
}

public long getChildId(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return childPosition;
}

public View getChildView(final int groupPosition, final int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
{

String laptop=(String)getChild(groupPosition, childPosition);

LayoutInflater inflater = mainActivity.getLayoutInflater();

if(convertView==null)
{
convertView = inflater.inflate(R.layout.child_item, null);
}

TextView item = (TextView) convertView.findViewById(R.id.laptop);


item.setTypeface(null, Typeface.BOLD);
item.setText(laptop);
       ImageView delete = (ImageView) convertView.findViewById(R.id.delete);
       delete.setOnClickListener(new OnClickListener() {
         
           public void onClick(View v) {
               AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
               builder.setMessage("Do you want to remove?");
               builder.setCancelable(false);
               builder.setPositiveButton("Yes",
                       new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                               List child = 
                                   laptopCollection.get(laptops.get(groupPosition));
                               child.remove(childPosition);
                               notifyDataSetChanged();
                           }
                       });
               builder.setNegativeButton("No",
                       new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                               dialog.cancel();
                           }
                       });
               AlertDialog alertDialog = builder.create();
               alertDialog.show();
           }
       });

return convertView;
}
public int getChildrenCount(int groupPosition)
{
return laptopCollection.get(laptops.get(groupPosition)).size();
}

public Object getGroup(int groupPosition)
{
return laptops.get(groupPosition);
}

public int getGroupCount()
{
return laptops.size();
}

public long getGroupId(int groupPosition)
{
// TODO Auto-generated method stub
return groupPosition;
}

public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
String laptopname=(String)getGroup(groupPosition);

if(convertView==null)
{
LayoutInflater infalInflater = (LayoutInflater)mainActivity.getSystemService(mainActivity.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.group_item,null);
}
TextView item = (TextView) convertView.findViewById(R.id.laptop);
item.setText(laptopname);
return convertView;
}

public boolean hasStableIds()
{
// TODO Auto-generated method stub
return true;
}

public boolean isChildSelectable(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return true;
}

}



Step7: Now Run the project, You will get output

Note: for more details have a look in this blog.
 http://theopentutorials.com/tutorials/android/listview/android-expandable-list-view-example/