Tuesday, October 30, 2012

what is meant by Stick Intents

Its interview questions i search some sites my knowledge to share to you.

A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intentyou are sending stays around after the broadcast is complete.


// Register for the battery changed event
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

/ Intent is sticky so using null as receiver works fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null, filter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
  || status == BatteryManager.BATTERY_STATUS_FULL;

boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; 
Sticky Broadcast Intents typically require special permissions.  reference link



first u understand intents and intents filters:

its also nice blog are here:intents and filters


and u study  services also: services





Wednesday, October 24, 2012

convert text to url.


Linkify is used to convert text to link and text to dial phone number also used.

so we used us Linkify.ALL method.


TextView link = (TextView) findViewById(R.id.link);

link.setText("www.google.com");
Linkify.addLinks(link, Linkify.ALL);

Friday, September 21, 2012

SENDING FILE TO WEB SERVER USING ANDROID


FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(image);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     
           bitmap=BitmapFactory.decodeStream(fileInputStream);
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
           byte[] data = baos.toByteArray();
           IMAGE= Base64.encodeBytes(data);
           Log.e("THE IMAGE BYTES",""+IMAGE);




IMAGE IS STRING TO SEND TO WEB SERVER 

Thursday, September 20, 2012

how to find file path extension and size not exceeded to 1 mb in android





String s="file path";
File file = new File(s);
   
long sizeInBytes = file.length();
sizeInBytes = sizeInBytes/1024;
Log.e("login bytes", ""+sizeInBytes);
     //transform in MB
     //double sizeInMb = sizeInBytes/(1024*1024);
               
     if(sizeInBytes<=2048)
   
        {
    Log.e("login", ""+sizeInBytes);
      int dot = c.lastIndexOf(".");
      String ff= c.substring(dot+1);
         
    //  tv1.setText(ff);
    if(ff=="pdf"||ff.compareTo("txt")==0||ff=="docx"||ff=="doc"||ff=="xls"||ff=="xlsx"||ff=="ppt"||ff=="pptx")
      {
    //Log.e("login if", ""+ff);
        exsistingFileName=c;
        Log.e("path file", ""+exsistingFileName);
    String searchFor = "bit.ly/yyyyyy";
    String s1=feed1.getText().toString();
        int len = searchFor.length();
        int result = 0;
        if (len > 0) {
        int start = s1.indexOf(searchFor);
        while (start != -1) {
        result++;
        start =s1.indexOf(searchFor, start+len);                
             
        }
        }        
       if(result==0)
    {
    feed1.append(" bit.ly/yyyyyy ");
    }
       else
       {
     
       }
     
      }
    else
    {
    showAlertDialog("file type only doc,txt,doc,docx,ppt,xls,xls");
    }

//Log.e("path", ""+exsistingFileName);
        }
    else
    {
    showAlertDialog("file size not exceed to 2mb");
    }

}

how to use bit.ly url in ur android program


int leng=ulink.length();
     
         for (int i = 0;  i <= (leng - 7);i++) {
                if (ulink.regionMatches(i, "http://", 0, 6)) {
                youtubelink=ulink;}}
         for (int i = 0;  i <= (leng - 4);i++) {
                if (ulink.regionMatches(i, "www.", 0, 3)) {
                youtubelink=ulink.replace("www.", "http://");
                youtubelink=youtubelink.trim();}}  
       try{
   
          url = as("user name", "api key").call(shorten(youtubelink));
          String s1=url.getShortUrl();
          feed1.append(" "+s1);
       }
       catch(Exception e)
       {
        showAlertDialog("please check your url and its wrong");
       }
       
     
         // Do something with value!
         }




public class BitActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
     
       
        Url url = as("username", "key").call(shorten("http://google.com"));
        String s=url.getShortUrl();
        Log.e("url",s);
   
        URLConnection conn = null;
       
       conn =  connectURL(s);
     
       String sss=conn.toString();
       Log.e("expand",sss);

           
    }

private URLConnection connectURL(String s) {
// TODO Auto-generated method stub
URLConnection conn =null;
try {
        URL inputURL = new URL(s);
        conn = inputURL.openConnection();
             //  int test = 0;

    }catch(MalformedURLException e) {
        System.out.println("Please input a valid URL");
    }catch(IOException ioe) {
        System.out.println("Can not connect to the URL");
    }
return conn;
}





its very simple
       

how to get a device id in android phone


 final TelephonyManager tm = (TelephonyManager) this
  .getSystemService(Context.TELEPHONY_SERVICE);

  final String tmDevice, tmSerial, androidId;
  tmDevice = "" + tm.getDeviceId();
  tmSerial = "" + tm.getSimSerialNumber();
  androidId = ""
  + android.provider.Settings.Secure.getString(this
  .getContentResolver(),
  android.provider.Settings.Secure.ANDROID_ID);

  UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice
  .hashCode() << 32)
  | tmSerial.hashCode());
  DID = deviceUuid.toString();


important user permission is  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Friday, August 31, 2012

KSOAP2 USING SEND IMAGE TO WEB SERVER IN ANDROID

its ksoap codes to send image and file to web server :



public class SoapuploadActivity extends Activity {
    /** Called when the activity is first created. */
public final String SOAP_ACTION = "http://tempuri.org/Add";

public  final String OPERATION_NAME = "Add";

public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

public  final String SOAP_ADDRESS = "http://grasshoppernetwork.com/NewFile.asmx";
TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv=(TextView)findViewById(R.id.textView2);
     
        Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bMap .compress(Bitmap.CompressFormat.PNG, 100, baos);
        //bMap is the bitmap object
        byte[] b = baos.toByteArray();
        int i=b.length;
        Log.e("the output is",""+i);
String  IMAGE= Base64.encodeBytes(b);
        Call(IMAGE);
     
    }
 
 

public void Call(byte[] b)
{

SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo pi=new PropertyInfo();

        pi=new PropertyInfo();
        pi.setName("b");
        pi.setValue(b);
        pi.setType(byte[].class);
        request.addProperty(pi);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(request);

HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Object response=null;
try

{

httpTransport.call(SOAP_ACTION, envelope);

response = envelope.getResponse();



}

catch (Exception exception)

{

response=exception.toString();
Log.e("the error is",""+response);

}

Log.e("the output is",""+response);
tv.setText(response.toString());



}
 
 
}



its download and add library file to project:  link
its download and add base64conversion to project:  base 64


CONTENT TYPE USING SEND IMAGE OR FILE TO WEB SERVER IN ANDROID

its send file or image send to web server:

This is content value type :



private void doFileUpload(){

   HttpURLConnection conn = null;
   DataOutputStream dos = null;
   DataInputStream inStream = null;

  z=1;
 
   // Is this the place are you doing something wrong.

   String lineEnd = "\r\n";
   String twoHyphens = "--";
   String boundary =  "*****";
         String exsistingFileName="given to file path";

   int bytesRead, bytesAvailable, bufferSize;

   byte[] buffer;

   int maxBufferSize = 1*1024*1024;

   String responseFromServer = "";

   String urlString = "server url";


   try
   {
    //------------------ CLIENT REQUEST
 
   Log.e("MediaPlayer","Inside second Method");

   FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

    // open a URL connection to the Servlet

    URL url = new URL(urlString);


    // Open a HTTP connection to the URL

    conn = (HttpURLConnection) url.openConnection();

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");

    conn.setRequestProperty("Connection", "Keep-Alive");
 
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    dos = new DataOutputStream( conn.getOutputStream() );

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
    dos.writeBytes(lineEnd);

    Log.e("MediaPlayer","Headers are written");

    // create a buffer of maximum size

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...

    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
     dos.write(buffer, 0, bufferSize);
     bytesAvailable = fileInputStream.available();
     bufferSize = Math.min(bytesAvailable, maxBufferSize);
     bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...

    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    BufferedReader in = new BufferedReader(
    new InputStreamReader(
                conn.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)
tv.append(inputLine);

 
 
 
    // close streams
    Log.e("MediaPlayer","File is written");
    fileInputStream.close();
    dos.flush();
    dos.close();


   }
   catch (MalformedURLException ex)
   {
        Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
   }

   catch (IOException ioe)
   {
        Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
   }


   //------------------ read the SERVER RESPONSE


   try {
         inStream = new DataInputStream ( conn.getInputStream() );
         String str;
     
         while (( str = inStream.readLine()) != null)
         {
              Log.e("MediaPlayer","Server Response"+str);
         }
         inStream.close();

   }
   catch (IOException ioex){
        Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
   }

  }


this code just call main activity and the method name is doFileUpload() its working .

MME USING SEND IMAGE OR FILE TO WEB SERVER IN ANDROID

hi friends Today see to how to upload a image and file to web server using method

I'm discuss with few technique and method are:

1. mime method
2.content type method
3.ksoap method
4.mime with json .


mime :

if its using to add jar file download jar file link

download to the binary file.



public class UploadActivity extends Activity {
    /** Called when the activity is first created. */
Bitmap bm;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
//bm = BitmapFactory.decodeResource(getResources(),
//R.drawable.forest);
bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
executeMultipartPost();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}

public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("your server link");

ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}


you just create the project and copy the code and paste and add to library file. Its working.


if you want to download a mine with json project just :http://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/

Friday, August 24, 2012

ANDROID XML PARSER PART 3



PULL PARSER:

pull-parsing is the "pull" to SAX parsing's "push". SAX pushes content at you by firing events as it encounters constructs within the xml document. 

Pull-parsing lets you ask for (pull) the next significant construct you are interested in.

You still have to take the data in the order it appears in the document - you can't go back and forth through the document like you can with DOM - but you can skip over bits you aren't interested in.



XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API (visit this website to learn more about API and its implementations).
There are following different kinds of parser depending on which features are set:
  • non-validating parser as defined in XML 1.0 spec when FEATURE_PROCESS_DOCDECL is set to true
  • validating parser as defined in XML 1.0 spec when FEATURE_VALIDATION is true (and that implies that FEATURE_PROCESS_DOCDECL is true)
  • when FEATURE_PROCESS_DOCDECL is false (this is default and if different value is required necessary must be changed before parsing is started) then parser behaves like XML 1.0 compliant non-validating parser under condition that no DOCDECL is present in XML documents (internal entites can still be defined with defineEntityReplacementText()). This mode of operation is intended for operation in constrained environments such as J2ME.
There are two key methods: next() and nextToken(). While next() provides access to high level parsing events, nextToken() allows access to lower level tokens.
The current event state of the parser can be determined by calling the getEventType() method. Initially, the parser is in the START_DOCUMENT state.
The method next() advances the parser to the next event. The int value returned from next determines the current parser state and is identical to the value returned from following calls to getEventType ().
Th following event types are seen by next()
START_TAG
An XML start tag was read.
TEXT
Text content was read; the text content can be retrieved using the getText() method. (when in validating mode next() will not report ignorable whitespace, use nextToken() instead)
END_TAG
An end tag was read
END_DOCUMENT
No more events are available


SOURCE CODE LINK: DOWNLOAD
USEFULL LINK: TUTORIAL


ANDROID XML PARSER PART 2




SAX Parser:
SAX stands for Simple API for XML. It uses a "push" approach: whereas with DOM you can dig around in the document in whatever order you like, SAX parsing is event-driven which means you have to handle the data as it is given to you.

SAX parsers fire events when they encounter the various components that make up an XML file. You register a ContentHandler whose methods are called-back when these events occur (for example when the parser finds a new start element, it invokes the startElement method of yourContentHandler).

The API assumes that the consumer (ContentHandler) is going to maintain some awareness of its state (e.g. where it currently is within the document). I sometimes use a java.util.Stack to push/pop/peek at which element I'm currently working in, but here I can get away with just recording the name of the current element.

I'm extending DefaultHandler because I'm not interested in many of the events (it provides a default empty implementation of those methods for me).

SOME KEYS POINTS:


·        A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
·        A SAX parser serves the client application always only with pieces of the document at any given time.
·        A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What’s more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.

SAX:
  1. Parses node by node
  2. Doesnt store the XML in memory
  3. We cant insert or delete a node
  4. Top to bottom traversing.

Sequence of events It doesn't use any memory preferred for large documents. Faster at runtime, because of the above mentioned point. Objects are to be created. Need to write code for creating objects In SAX Backward navigation is not possible as it sequentially processes the document
So if you have very large files then you should use SAX parser since it will fire events and releasing them ,nothing is stored in memory ,and using SAX parser you can't access element in a random way there is no going back ! , but Dom let you access any part of the xml file since it keeps the whole file/document in memory

EXAMPLE CODE:
SOURCE CODE IS HERE :  DOWNLOAD


















ANDROID XML PARSER PART1

hi guys ,


android web services is very important. sending data to web server and receiving data to web server importance. we are using few parsing techniques.

That's are:

                      1. DOM  PARSER.
                      2. SAX PARSER.
                      3. XML PULL  PARSER.


DOM PARSER:

DOM (Document Object Model) parsing builds an in-memory object representation of the entire XML document.

 You can then rummage around in the DOM, going and back and forth between elements and reading data from them in whatever order you like.

Because the entire document is read into memory, there is an upper limit on the size of document you can read (constrained by the size of your Java heap).
Memory is not used particularly efficiently either - a DOM may consist of very many sparsely populated List objects (backed by mostly empty arrays). 

A side effect of all these objects in memory is that when you're finished with them there's a lot for the Garbage Collector to clean up.
On the plus side, DOM parsing is straight-forward to work with, particularly if you don't care much about speed and use getElementsByTagName() wherever possible.

DOM Features:
  1. Stores the entire XML document into memory before processing.
  2. Occupies more memory.
  3. We can insert or delete nodes.
  4. Traverse in any direction.

some point:
 A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.
·        A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
·        A DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.




SAMPLE CODE FOR HOW TO PARSING TO XML:





public class domparser extends Activity {


    /** Called when the activity is first created. */
    @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        /** 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[];
        
        try {
        URL url = new URL( "your url ");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        
        Document doc = db.parse(new InputSource(url.openStream()));
        
        doc.getDocumentElement().normalize();
        
        NodeList nodeList = doc.getElementsByTagName("results");// chance to your tag name
        
        /** Assign textview array lenght by arraylist size */
        name = new TextView[nodeList.getLength()];
        
        
        for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        name[i] = new TextView(this);
        
        Element fstElmnt = (Element) node;
        NodeList nameList = fstElmnt.getElementsByTagName("output");
// chance to your  sub tag name

        Element nameElement = (Element) nameList.item(0);
        nameList = nameElement.getChildNodes();
        name[i].setText("results = "
        + ((Node) nameList.item(0)).getNodeValue());
     
     
        layout.addView(name[i]);
     
        }
        } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
        }
        /** Set the layout view to display */
        setContentView(layout);
        }
     


     


    }




The xml source code is:

<result>
<output>successfully received</output>
</result>















Sunday, June 24, 2012

how to use android

if you want to create new android application.

I'd take my time and learn Java. I had a look at The Java™ Tutorials the other day and Eclipse And Java Video Tutorials was really simple and easy to understand.