Tuesday, December 27, 2011

Share data android

 Intent msg = new Intent(Intent.ACTION_SEND);
 String[] recipients = { "" }; // this.is@recipient.com
  String[] carbonCopies = { "" }; // hey.another@recipient.
  msg.putExtra(Intent.EXTRA_EMAIL, recipients);
  msg.putExtra(Intent.EXTRA_CC, carbonCopies);
 msg      .putExtra(        Intent.EXTRA_TEXT,        "your text");
  // Change from ApplicationStep class subject line     // Html.
  msg.putExtra(Intent.EXTRA_SUBJECT, ApplicationStep.EMAIL_SUBJECT);     msg.putExtra(Intent.EXTRA_STREAM, Uri.parse(sUri)); // attachment
   msg.setType("image/png");  
startActivity(Intent.createChooser(msg,      "Please choose an email client"));

Monday, December 19, 2011

Get ImageFile form server and Store onto Device's memory and display it

public class DataStoreActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        DownloadFile("image file path www.");
        byte b[] = readInternalStoragePrivate("download.jpg");
       
        Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
       
        ImageView imageView = new ImageView(this);
        imageView.setImageBitmap(bmp);
        setContentView(imageView);
    }

    /**
     * Reads a file from internal storage
     * @param filename the file to read from
     * @return the file content
     */
    public byte[] readInternalStoragePrivate(String filename) {
        int len = 1024;
        byte[] buffer = new byte[len];
        try {
            FileInputStream fis = openFileInput(filename);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int nrb = fis.read(buffer, 0, len); // read up to len bytes
            while (nrb != -1) {
                baos.write(buffer, 0, nrb);
                nrb = fis.read(buffer, 0, len);
            }
            buffer = baos.toByteArray();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
    /**
     * Writes content to internal storage making the content private to
     * the application. The method can be easily changed to take the MODE
     * as argument and let the caller dictate the visibility:
     * MODE_PRIVATE, MODE_WORLD_WRITEABLE, MODE_WORLD_READABLE, etc.
     *
     * @param filename - the name of the file to create
     * @param content - the content to write
     */
    public void writeInternalStoragePrivate(
            String filename, byte[] content) {
        try {
            //MODE_PRIVATE creates/replaces a file and makes
            //  it private to your application. Other modes:
            //    MODE_WORLD_WRITEABLE
            //    MODE_WORLD_READABLE
            //    MODE_APPEND
            FileOutputStream fos =
               openFileOutput(filename, Context.MODE_PRIVATE);
            fos.write(content);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * Delete internal private file
     * @param filename - the filename to delete
     */
    public void deleteInternalStoragePrivate(String filename) {
        File file = getFileStreamPath(filename);
        if (file != null) {
            file.delete();
        }
    }

    public  void DownloadFile(String fileURL) {
        try {
              // File file = new File(fileName,);
              // file.createNewFile();
             //  FileOutputStream f = new FileOutputStream(file);
            FileOutputStream f = openFileOutput("download.jpg", Context.MODE_PRIVATE);
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
        

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.close();
          // Log.d("Download Completed", )
        } catch (Exception e) {
           e.printStackTrace();
        }

    }
}

Friday, December 16, 2011

EditText limitation InputFilter


// you can add length limit to edit text using InputFilter .

InputFilter lengthFilter = new InputFilter.LengthFilter(30);
editText.setFilters(new InputFilter[]{lengthFilter});
 //want one line of text from the user
 editText.setSingleLine(true);

Tuesday, December 13, 2011

Simple Android Audio record Example Android


public class AudioRecorder {
  final MediaRecorder recorder = new MediaRecorder();
  public void start() throws IOException {
  
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(sdCardPath+"/xyz.3gp");
    recorder.prepare();
    recorder.start();
  }

 
  public void stop() throws IOException {
    recorder.stop();
    recorder.release();
  }

}

Monday, December 5, 2011

ProgressDialog in android


ProgressDialog progressDialog = null;
   
// ...
    progressDialog
= ProgressDialog.show(this, "Please wait...", true);
   
new Thread() {
       
public void run() {
           
try{
                 
// Grab your data                                                
           
} catch (Exception e) { }

           
// When grabbing data is finish: Dismiss your Dialog
            progressDialog
.dismiss();
       
}
   
}.start();


ProgressDialog using Handler Use


Step 1: Create Global Handler Class.
private EventHandler mEventHandler = new EventHandler();


class EventHandler extends Handler {
int tempMsg = 0;

@Override
public void handleMessage(Message msg) {
try {

switch (msg.what) {
case 1:
// call method whatever you want.
break;

dialog.dismiss();

} catch (Exception e) {
Log.d("XReader", "Error in " + e.getMessage());
}
}
};



step2: call Hender using Msg
ProgressDialog dialog = ProgressDialog.show(XReaderActivity.this, "", "Please wait",true);
Message message = new Message();
message.what = 1;
mEventHandler.sendMessage(message);


Friday, December 2, 2011

ESRI using Eclipse setup guide


Please follow these steps to install the ArcGIS for Android 1.0 Beta Eclipse plug-ins:
1. Start Eclipse, then select Help > Install New Software....

2. In the top-right corner, Click Add.
3. In the Add Repository dialog that appears, enter “ArcGIS Android” for the Name and the following URL for the Location: http://downloads.esri.com/software/arcgis/android
4. In the Available Software dialog, select the checkbox next to ArcGIS for Android and click Next.
5. In the next window, you'll see two plug-ins to be installed. Click Next.

6. Display the License text by clicking on "IMPORTANT-READ CAREFULLY". Read the license text, then click the radio button to accept the license agreements, then click Finish.
7. When the installation completes, restart Eclipse.
* Notes for users of ArcGIS for Android Early Adopter release only
If you had installed the plug-ins for the ArcGIS for Android Early Adopter release, please refer to the Help for ArcGIS API for Android > Esri’s Eclipse tooling > Updating the plug-ins for installation instructions.


Hw to use android:layout_weight


Use android:layout_weight
<LinearLayout 
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:weightSum="100"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <LinearLayout 
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_weight="70" >

        </LinearLayout>
        <LinearLayout android:id="@+id/widget32" android:orientation="horizontal"
            android:layout_weight="30" android:layout_width="fill_parent"

            android:layout_height="wrap_content">

        </LinearLayout>
    </LinearLayout>

Tuesday, November 29, 2011

EditText white space validation


psvm(){
String str = "     ";
if(trim(str).legth()>0){
 sysout("valid")
}else{
sysout("not valid")
}

}
public String trim(String source) {
        return source.replaceAll("\\s+$", "");
    }

Monday, November 28, 2011

URL validation for android


// include
import android.webkit.URLUtil;

public boolean URLValidation(String string) {

return URLUtil.isValidUrl(string);
}

Email validation for android Edittext


public boolean eMailValidation(String emailstring) {
emailPattern = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}"
+ "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+");
emailMatcher = emailPattern.matcher(emailstring);
return emailMatcher.matches();
}

Monday, November 21, 2011

GET TEXT FROM ASSERT ANDROID



private String getAssertText(String path) {
String javascrips="";
try {
InputStream input = getAssets().open(path);
int size;
size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
javascrips = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return javascrips;
}

Friday, November 18, 2011

Call webservice using restclient android


package com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class RestClient {

    private static final int GET = 0;
private static final int POST = 1;
private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;

    private int responseCode;
    private String message;

    private String response;

    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RestClient(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void Execute(int method) throws Exception
    {
        switch(method) {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }

                HttpGet request = new HttpGet(url + combinedParams);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                executeRequest(request, url);
                break;
            }
            case POST:
            {
                HttpPost request = new HttpPost(url);

                //add headers
                for(NameValuePair h : headers)
                {
                    request.addHeader(h.getName(), h.getValue());
                }

                if(!params.isEmpty()){
                    request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                }

                executeRequest(request, url);
                break;
            }
        }
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
public static void main(String s){

/**
* Calling Webservice
*
*
*/
RestClient client = new RestClient(LOGIN_URL);
client.AddParam("accountType", "GOOGLE");
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");

try {
   client.Execute(RequestMethod.POST);
} catch (Exception e) {
   e.printStackTrace();
}

String response = client.getResponse();


}

Thursday, November 17, 2011

Parsing JSON using GSON in Android


Parsing JSON using GSON in Android

Download GSON lib :
http://code.google.com/p/google-gson/downloads/list
As part of the college mini project,  I along with my group, developed a micro-blogging platform for Android. One of the biggest hurdles I had to face was of choosing the proper data format for receiving responses from the web service. I needed something that was fast as well as easy to understand and parse.  I first chose XML as it was easy to read and mostly because I knew no other alternatives. But parsing XML certainly wasn’t easy. With the variety of tags in the responses from the server and the heaviness of XML format, it just became impossible to use it.
That’s when JSON(JavaScript Object Notation) came up as an alternative to XML. I was circumspect about using JSON at first as I had doubts about its readability and ease of deserialization. But those doubts were not much more than just superstitions. JSON is smaller and easier to parse, than it’s XML equivalent. Many say its less readable than XML, but considering it was used for data interchange, readability was not important.
The easiest way to parse JSON and convert to POJO (Plain Old Java Objects) in Android is to use the Google’s GSON library.

Download GSON

Download the latest GSON library from
Add this library into your Android Project as an external by right clicking on the desired project and
Properties -> Java Build Path -> Libraries -> Add External JARs and point to the downloaded gson library.

Format of JSON response.

Suppose, the JSON response recieved from the webservice is of the following format.
{ "posts":
  [      
     { "post": 
        {
       "username": "John",  
       "message": "I'm back",
       "time": "2010-5-6 7:00:34"
            }},
        {    "post":
            {
                "username": "Smith",
                "message": "I've been waiting",
                "time": "2010-4-6 10:30:26"
            }}]}


It is an array of JSON Objects.  You have to develop a class structure in accordance with the structure of the JSON response received.  For the above example I had the class structure based on the following logic.
The “posts” data structure contain multiple posts, each of which contains an “post” type. In order to match this structure, I need to have 3 classes namely PostList, PostContainer and Posts. The PostList class should have an ArrayList of objects of type PostContainer. PostContainer needs just one field which is an object of type Posts. Posts classes must have  3 fields namely username, message and time.
public class PostList {
private List<PostContainer> posts = new ArrayList<PostContainer>();
public List<PostContainer> getPostContainterList() {
return posts;
}
}
class PostContainer{
Posts post;
public Posts getPost(){
return post;
}
}
public class Posts {
String message;
String time;
String username;
}

Deserialization Part

Now let’s get into the real business of Deserialization. Using GSON this can be done very easily.
First, import the Google gson library into the class in which JSON String is to be deserialized
import com.google.gson.Gson;
I am initializing an ArrayList which contains objects of type Posts
private List<Posts> mObjectList =  new ArrayList<Posts>() ;
This can be latter on used for adding the Posts objects after deserialization is done.
String jsonString = “Insert your JSON Data here”
Instantiate an Object of type PostList
PostList list = null;
list = getPostList(jsonString);
The following function deserializes JSON response to an Object of type PostList and returns it.
protected PostList getPostList (String jsonString){
PostList pl = null;
Gson gson = new GSON;
pl = gson.fromJson(jsonString, PostList.class);
return pl;
}
What the function getPostList does is, it creates an object of type GSON and deserialize the JSON String to POJO using that object(gson).
gson.fromJson(jsonString, PostList.class)
The first parameter to the function is the JSON String and second parameter is the name of the class to which it should be deserialized. Two important things have to be taken care of while using GSON to parse JSON
  • Tags in JSON String and name of fields of the respective classes should match exactly.
  • Object hierarchy should be built correctly.
Failure to comply to the both conditions above would result in some or all of the fields of the classes being left null.
Having parsed the JSON string to POJO, we can get various Posts objects separately and add it to the ArrayList which we created earlier as follows.
List <PostContainer> post_list = list.getPostContainterList();
PostContainer pc;
for (int i = 0; i < post_list.size(); i++) {
pc = post_list.get(i);
mObjectList.add(pc.getPost()); //Adding each post to the list
This ArrayList can be used to populate a custom list view. If you have any doubts regarding this post, feel free to ask through comments. In the next post, I will post an tutorial on how to build a custom listview which looks the twitter timeline efficiently.










































content -->