Wednesday, August 7, 2013

Simple XML parsing

All the beginners have a confusion on using XML parsing methods like Pull, DOM or SAX. Follow the below simple customized method to parser your XML string. No need to use any parsing methods.

String strOutputXML = (Your XML String to parse)

Document objDocument = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try 
{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(strOutputXML));
objDocument = db.parse(is);
catch (ParserConfigurationException e) 
{
return null;
catch (SAXException e) 
{
return null;
catch (IOException e) 
{
return null;
}

Document doc = objDocument ;

NodeList objNodeList = doc.getElementsByTagName("rule");
int intRuleCount = objNodeList.getLength();

for(int i=0;i<intRuleCount;i++)
{
String[] strStarting = strOutputXML.split("<rule id=");
String[] strEnding = strStarting[i+1].split("</rule>");
String strRule = strEnding[0];

NodeList objNodeListItem = doc.getElementsByTagName("item");
int intItemCount = objNodeListItem.getLength();

for(int j=0;j<intItemCount;j++)
{
strStarting = strRule.split("<item>");
strEnding = strStarting[i+1].split("</item>");
String[] strItems = strEnding[0];
}
}

Tuesday, January 8, 2013

ListView with Checkbox and Click

Android ListView items with CheckBox and Click Action. I searched a lot and found this example for duel action of ListView Item.

activity_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:padding="10dp"
        android:text="@string/some_text"
        android:textSize="20sp" />

    <Button

        android:id="@+id/findSelected"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_String" />

    <ListView

        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


listitem.xml


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

    <CheckBox

        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false"
        android:focusableInTouchMode="false" />

    <TextView

        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/checkBox1"
        android:layout_alignBottom="@+id/checkBox1"
        android:layout_toRightOf="@+id/checkBox1" >
    </TextView>

</RelativeLayout>


String.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">CheckBoxList</string>

    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="some_text">Some Mobile OS!</string>
    <string name="btn_String">Find OS that are Selected</string>

</resources>



MainActivity.java


public class MainActivity extends Activity 
{
MyCustomAdapter dataAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Generate list View from ArrayList
displayListView();
checkButtonClick();
}

private void displayListView() 
{
//Array list of countries
ArrayList<Mobile> MobileOSList = new ArrayList<Mobile>();
Mobile MobileOS = new Mobile("AND","Android",false);
MobileOSList.add(MobileOS);
MobileOS = new Mobile("IPH","Iphone",true);
MobileOSList.add(MobileOS);
MobileOS = new Mobile("BLB","Blackberry",false);
MobileOSList.add(MobileOS);
MobileOS = new Mobile("WIN","Windows",true);
MobileOSList.add(MobileOS);
MobileOS = new Mobile("SYM","Symbian",true);
MobileOSList.add(MobileOS);
MobileOS = new Mobile("BADA","Bada",false);
MobileOSList.add(MobileOS);
MobileOS = new Mobile("OTH","Others",false);
MobileOSList.add(MobileOS);

//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,R.layout.listitem, MobileOSList);
ListView listView = (ListView) findViewById(R.id.listView1);

// Assign adapter to ListView
listView.setAdapter(dataAdapter);

listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
Mobile country = (Mobile) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Clicked on Row: " + country.getName(),Toast.LENGTH_LONG).show();
}
});
}

private class MyCustomAdapter extends ArrayAdapter<Mobile> 
{
private ArrayList<Mobile> MobileOSList;
public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<Mobile> countryList) 
{
super(context, textViewResourceId, countryList);
this.MobileOSList = new ArrayList<Mobile>();
this.MobileOSList.addAll(countryList);
}

private class ViewHolder 
{
TextView code;
CheckBox name;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
ViewHolder holder = null;

if (convertView == null) 
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener() 
{
public void onClick(View v) 
{
CheckBox cb = (CheckBox) v ;
Mobile country = (Mobile) cb.getTag();
Toast.makeText(getApplicationContext(),"Clicked on Checkbox: " + cb.getText() +" is " + cb.isChecked(),Toast.LENGTH_LONG).show();
country.setSelected(cb.isChecked());
}
});
}
else 
{
holder = (ViewHolder) convertView.getTag();
}
Mobile MobileOS = MobileOSList.get(position);
holder.code.setText(" (" +  MobileOS.getCode() + ")");
holder.name.setText(MobileOS.getName());
holder.name.setChecked(MobileOS.isSelected());
holder.name.setTag(MobileOS);
return convertView;
}
}

private void checkButtonClick() 
{
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() 
{
@Override
public void onClick(View v) 
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Mobile> MobileOSList = dataAdapter.MobileOSList;
for(int i=0;i<MobileOSList.size();i++)
{
Mobile MobileOS = MobileOSList.get(i);
if(MobileOS.isSelected())
{
responseText.append("\n" + MobileOS.getName());
}
}
Toast.makeText(getApplicationContext(),responseText, Toast.LENGTH_LONG).show();
}
});
}
}

Mobile.java


public class Mobile 
{
String code = null;
String name = null;
boolean selected = false;

public Mobile(String code, String name, boolean selected)
{
super();
this.code = code;
this.name = name;
this.selected = selected;
}

public String getCode() 
{
return code;
}

public void setCode(String code) 
{
this.code = code;
}

public String getName() 
{
return name;
}

public void setName(String name) 
{
this.name = name;
}

public boolean isSelected() 
{
return selected;
}

public void setSelected(boolean selected) 
{
this.selected = selected;
}
}








Monday, October 29, 2012

Android ActionBar Example

Hi developers, here the simple example for the action bar control android.

menu_ctrl.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item

        android:id="@+id/menuitem1"
        android:showAsAction="always"
        android:title="Add">
    </item>
    <item
        android:id="@+id/menuitem2"
        android:showAsAction="always"
        android:title="Sub">
    </item>
    <item
        android:id="@+id/menuitem3"
        android:showAsAction="always"
        android:title="Mul">
    </item>
    <item
        android:id="@+id/menuitem4"
        android:showAsAction="always"
        android:title="Div">
    </item>

</menu>


main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="20dp" >

        <TextView

            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/str_firstnumber"
            android:textSize="15dp" />

        <EditText

            android:id="@+id/FirstNumberET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number" />
    </LinearLayout>

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" >

        <TextView

            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/str_secnumber"
            android:textSize="15dp" />

        <EditText

            android:id="@+id/SecondNumberET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number" />
    </LinearLayout>

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp" >

        <TextView

            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="@string/str_answer"
            android:textSize="15dp" />

        <EditText

            android:id="@+id/AnswerET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:editable="false"
            android:inputType="numberSigned"
            android:textColor="#FF0000" />
    </LinearLayout>

</LinearLayout>


MainActivity.java



public class MainActivity extends Activity 
{
private EditText etFirstName, etSecondName, etAnswer;
private Double intAns;

@Override

public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialisation();
}

public void Initialisation() 

{
etFirstName = (EditText) findViewById(R.id.FirstNumberET);
etSecondName = (EditText) findViewById(R.id.SecondNumberET);
etAnswer = (EditText) findViewById(R.id.AnswerET);
}

@Override

public boolean onCreateOptionsMenu(Menu menu) 
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_ctrl, menu);
return true;
}

@Override

public boolean onOptionsItemSelected(MenuItem item) 
{
switch (item.getItemId()) 
{
case R.id.menuitem1:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
+ (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

case R.id.menuitem2:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
- (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

case R.id.menuitem3:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
* (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

case R.id.menuitem4:
if(etFirstName.length()==0||etSecondName.length()==0)
{
Toast.makeText(getApplicationContext(), "Enter First and Second Values", Toast.LENGTH_LONG).show();
}
else
{
intAns = (Double.parseDouble(etFirstName.getText().toString()))
/ (Double.parseDouble(etSecondName.getText().toString()));
etAnswer.setText(Double.toString(intAns));
}
break;

default:

break;
}
return true;
}
}


Tuesday, September 18, 2012

Sax Parser android Example

XML parsing in android

Here is the simplest way to parse XML and displaying into list view accordingly.You just have to care about how many tag you want  from your XML. Accordingly create a XML and base adapter.Now work is finish.

If you want to use this common XML file in  more than one ListView with different design then only create switch case.

AndroidChennaiActivity.java

public class AndroidChennaiActivity extends Activity 
{
private CommonClassFunction ccF;
ParsingXml sm=new ParsingXml();
 private ArrayList<String> tagName=new ArrayList<String>();
private ListView list;private ProgressDialog pd;
 @Override
 public void onCreate(Bundle savedInstanceState
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  list=(ListView) findViewById(R.id.list);

  tagName.add("vSmallImageDetail");

  tagName.add("vDescriptionDetail");
  tagName.add("vDurationDetail");
  tagName.add("dAddedDateDetail");
  pd=ProgressDialog.show(this,"Please wait","Loading...");
  pd.setCancelable(false);
  
  String url="www.demo.com";
  ccF=sm.new CommonClassFunction(this,tagName,list,pd,url);
  ccF.start();
 }
}

Common class that will perform everything in background thread and will display data in ListView

ParsingXml.java

public class ParsingXml extends DefaultHandler
{
 private int length;
 private boolean Error=false,flag=false;
 private ListView listview;
 private ProgressDialog pd;


 private ArrayList<String> [] store; 

 private ArrayList<String> tagName=new ArrayList<String>();
 private Activity act;
public ParsingXml(ArrayList<String> tag,int len)
 {
length=len;store=new ArrayList[length];
tagName=tag;
for(int i=0;i<length;i++)
  {
store[i]=new ArrayList<String>();
}
}

@Override

public void characters(char[] ch, int start, int lengthh)throws SAXException 
 {
super.characters(ch, start, lengthh);
String str=new String(ch,start,lengthh);
str=str.trim();
if(flag)
  {
for(int i=0;i<length;i++)
   {
if(tagName.get(i).equalsIgnoreCase(local))
    {
store[i].add(str);
}
}
}
}
 String local="";
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException 
 {
super.endElement(uri, localName, qName);
for(int i=0;i<length;i++)
  {
if(tagName.get(i).equalsIgnoreCase(localName))
   {
flag=false;
}
}
}

@Override

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException 
 {
  super.startElement(uri, localName, qName, attributes);
for(int i=0;i<length;i++)
  {
if(tagName.get(i).equalsIgnoreCase(localName))
   {
flag=true;local=localName;
}
}
}

 private String str;

public class CommonClassFunction extends Thread
 {
  public CommonClassFunction(Activity actt,ArrayList<String> tag,ListView list,
  ProgressDialog pdD,String url)
  {
act=actt;tagName=tag;listview=list;pd=pdD;str=url;
}
@Override
public void run() 
  {
try
   {
  length=tagName.size();
act.runOnUiThread(all);
}
catch(Exception e)
   {
e.getMessage();
}
}
}

private Runnable all=new Runnable() 

 {
public void run() 
  {
try
   {
SAXParserFactory sFactory=SAXParserFactory.newInstance();
SAXParser sParser=sFactory.newSAXParser();
XMLReader xmlReader=sParser.getXMLReader();
px=new ParsingXml(tagName,length);
xmlReader.setContentHandler(px);
URL url=new URL(str);
url.openConnection();
xmlReader.parse(new InputSource(url.openStream()));
}
  catch(Exception e)
  {
e.getMessage();Error=true;
}
handler.sendEmptyMessage(0);
}
};

ParsingXml px;

private Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg) 
  {
super.handleMessage(msg);
try
   {
if(length==0)
    {
Error=true;
}
    else if(Error)
    {
length=0;
}
if(Error)
    {
length=0;
}
switch(length)
    {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
      DealsAdapter da=new DealsAdapter(act, px.store[0],px.store[1],px.store[2],px.store[3]);
   listview.setAdapter(da);
break;
case 5:
break;
case 0: 
     ShowDialogBox("Error has occurred unknown reason");
}
pd.dismiss();
}
  catch(Exception e)
  {
e.getMessage();
}
 }
};

private void ShowDialogBox(String msg)

{
Builder builder=new AlertDialog.Builder(act);
builder.setTitle("Alerting");
builder.setMessage(msg);
builder.setPositiveButton("Ok",new DialogInterface.OnClickListener() 
  {
public void onClick(DialogInterface dialog, int which) 
   {
dialog.dismiss();
}
});
builder.show();
}
}