Saturday, 25 February 2012

Parsing JSON in Android and Show in List

//main
package com.pxr.tutorial.json;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.pxr.tutorial.xmltest.R;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);
       
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
      
        JSONObject json = JSONfunctions.getJSONfromURL("http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo");
               
        try{
           
            JSONArray  earthquakes = json.getJSONArray("earthquakes");
           
            for(int i=0;i<earthquakes.length();i++){                       
                HashMap<String, String> map = new HashMap<String, String>();   
                JSONObject e = earthquakes.getJSONObject(i);
               
                map.put("id",  String.valueOf(i));
                map.put("name", "Earthquake name:" + e.getString("eqid"));
                map.put("magnitude", "Magnitude: " +  e.getString("magnitude"));
                mylist.add(map);           
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }
       
        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
                        new String[] { "name", "magnitude" },
                        new int[] { R.id.item_title, R.id.item_subtitle });
       
        setListAdapter(adapter);
       
        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);   
        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(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();

            }
        });
    }
}


//json function
package com.pxr.tutorial.json;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
       
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
       
      //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
       
        try{
           
            jArray = new JSONObject(result);           
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
   
        return jArray;
    }
}

Thursday, 23 February 2012

Image Showing in DataList

Showproduct.aspx
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage2.master" CodeFile="ShowProducts.aspx.cs" EnableEventValidation="false" Inherits="ShowProducts" %>

<script runat="server">

  
</script>

<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 
        <div>
            <asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
                RepeatDirection="Horizontal" ShowFooter="False" BackColor="White"
                BorderColor="Black" BorderStyle="Double" BorderWidth="5px" CellPadding="10"
                CellSpacing="20" Font-Bold="False" Font-Italic="False" Font-Overline="False"
                Font-Strikeout="False" Font-Underline="False" ForeColor="Black"
                GridLines="Both" HorizontalAlign="Center">
                <FooterStyle BackColor="White" ForeColor="#333333" />
                <ItemStyle BackColor="White" ForeColor="#333333" />
                <SeparatorStyle BackColor="#3333FF" Font-Bold="False" Font-Italic="False"
                    Font-Overline="False" Font-Strikeout="False" Font-Underline="False"
                    ForeColor="#CC00FF" HorizontalAlign="Center" VerticalAlign="Middle" />
                <SelectedItemStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
                <ItemTemplate>
                <table><tr>
                   
                <td><%#DataBinder.Eval(Container.DataItem,"images") %></td>
                <td>&nbsp;&nbsp;&nbsp</td>
                <td><h3><%#DataBinder.Eval(Container.DataItem,"productname") %></h3><br>
                <b>MRP</b> <%#DataBinder.Eval(Container.DataItem, "productmrp") %><br>
                <b>Our Price</b> <%#DataBinder.Eval(Container.DataItem, "plashprice") %><br>
                <b>Discount</b> <%#DataBinder.Eval(Container.DataItem, "Discount")%>%
                <br />
                <asp:Button ID="Button2" runat="server" Text="Get Details" CommandArgument='<%#Eval("productid") %>'
                        onclick="Button2_Click" />
                </td>
               
                </tr></table>
                 
                </ItemTemplate>
           
            </asp:DataList>
         
   
            <asp:Button ID="Button1" runat="server" Text="Button" />
   
    </div>
    </asp:Content>


//handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data.Odbc;

public class Handler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {

        OdbcConnection con = new OdbcConnection(connection.connection1);
        con.Open();
        string imagegetquery = "select imagepath from tblproductimagemap where productid='" + context.Request.QueryString["productid"] + "'";
        OdbcCommand imagegetcommand = new OdbcCommand(imagegetquery, con);
        OdbcDataReader imagereader = imagegetcommand.ExecuteReader();
        imagereader.Read();
        context.Response.BinaryWrite((byte[])imagereader["imagepath"]);
        imagereader.Close();
        con.Close();
      
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}


//showproduct.aspx.cs

  private void binddatalist()
    {
        DataTable dt= new DataTable();
        OdbcConnection con = new OdbcConnection(connection.connection1);
        con.Open();
        string imagegetquery = "select productid, productname, productbrand, productmrp, plashprice, discount from tblproductmaster";
        OdbcCommand imagegetcommand = new OdbcCommand(imagegetquery, con);
        OdbcDataAdapter imageadpter = new OdbcDataAdapter(imagegetcommand);
        imageadpter.Fill(dt);

        DataColumn imagecolumn = new DataColumn("images", typeof(string));
        dt.Columns.Add(imagecolumn);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][imagecolumn]=string.Format("<img src='Handler.ashx?productid={0}' alt='View Details' style='width:100px; height:100px'/>", dt.Rows[i][0].ToString());

            }
        }
       
       
        DataList1.DataSource = dt;
        DataList1.DataBind();

       

    }
   

Monday, 20 February 2012

Calling WebService in Android and Parse its XML

package Act.dscl;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

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

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
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.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class displayall extends Activity {
    String result;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle bundle= getIntent().getExtras();
        String result1=null;
        final String dateid=bundle.getString("datenew");
        final String userid=bundle.getString("userid");
        setContentView(R.layout.displaylayout);
       
        Button backbutton=(Button)findViewById(R.id.back);
        backbutton.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                Intent jl= new Intent(getBaseContext(),myactivity.class);
                jl.putExtra("userid", userid);
               
                startActivity(jl);
               
            }
        });
       
        HttpClient httpclient1=new DefaultHttpClient();
           HttpPost httppost1= new HttpPost("http://14.102.87.2/dsclwebservice/service.asmx/displayactivitywithdate");
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
          nameValuePairs.add(new BasicNameValuePair("userid",userid));
          nameValuePairs.add(new BasicNameValuePair("datein",dateid));
         
           try {
                httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         
          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          try {
                 result1= httpclient1.execute(httppost1, responseHandler);
             }
               
             catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //parse result message
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            DocumentBuilder db = null;
            try {
                db = dbf.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            InputSource is =new InputSource();

            is.setCharacterStream(new StringReader(result1));

            Document doc = null;
            try {
                doc = db.parse(is);
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //Get the xml string from the server

            NodeList nodes = doc.getElementsByTagName("string");

            //fill in the list items from the XML document

       
            String Message = null;
           
            try
            {
                Node es1= nodes.item(0);
                NodeList fstNm1=((Node)es1).getChildNodes();
                Message=(fstNm1.item(0)).getNodeValue();
            }
            catch(Exception ex)
            {
                String message= ex.getMessage();
            }
           
           
           
            String[] temp= new String[5];
           
            temp=Message.split("\\.");
       
           TextView txtview=(TextView)findViewById(R.id.textView1);
           String abcd=temp[0].toString();
           txtview.setText(abcd.toUpperCase());
          
           String alltext=temp[1];
           String[] alltextarray=alltext.split("2");
          
           String alltextsecond=alltextarray[1];
           String[] alltextsecondarray=alltextsecond.split("3");
          
          
           TextView firstactivity=(TextView)findViewById(R.id.textView2);
           firstactivity.setText("Activity 1"+alltextsecondarray[1].toString());
          
           TextView secondActivity=(TextView)findViewById(R.id.textView3);
           secondActivity.setText("Activity 2 "+alltextsecondarray[0].toString());
          
           TextView thirdActivity=(TextView)findViewById(R.id.textView4);
           thirdActivity.setText("Activity 3"+alltextarray[0].toString());

         
       
    }

}

Email Sending Codes for C#

using System;
using System.Net;
using System.Net.Mail;
using System.Collections;
public class MailSender
{
    public static bool SendEmail(
        string pGmailEmail,
        string pGmailPassword,
        string pTo,
        string pSubject,
        string pBody,

        ArrayList pAttachmentPath)
    {
        try
        {
            NetworkCredential loginInfo = new NetworkCredential(pGmailEmail, pGmailPassword);
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(pGmailEmail);
            msg.To.Add(new MailAddress(pTo));
            //msg.Bcc.Add(new MailAddress("ashok.prasad@akshamaala.com"));
            msg.Subject = pSubject;
            msg.Body = pBody;
            msg.IsBodyHtml = true;
            System.Net.Mail.Attachment attachment;
            for (int i = 0; i < pAttachmentPath.Count; i++)
            {
                attachment = new System.Net.Mail.Attachment(Convert.ToString(pAttachmentPath[i]));
                msg.Attachments.Add(attachment);
            }
            SmtpClient client = new SmtpClient("smtp.gmail.com");
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = loginInfo;
            client.Send(msg);
            msg.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }