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.










































Wednesday, November 16, 2011

custom PopupWindow android

private void showAddTextPopup()
{ PopupWindow window1 = new PopupWindow(this);
 window1.setWidth(500);
 window1.setHeight(300);
 window1.setTouchable(true);
 window1.setFocusable(true);
 LayoutInflater inflater = (LayoutInflater) NotesActivity.this .getLayoutInflater();// .getSystemService // (Context.LAYOUT_INFLATER_SERVICE);
 View bottomView = inflater.inflate(R.layout.addtext, null);
 window1.setContentView(bottomView);
 window1.showAtLocation(bottomView, Gravity.CENTER_VERTICAL, 50, 50); }

Sunday, November 13, 2011

Android AlertDialog Example :-

Android AlertDialog Example :-
To ask user permission for "Exit ?" we can use Android AlertDialog with Yes or No Button. So, by clicking Yes we can Exit the Application  and by clicking No we need not to do any action.
[sourcecode language="java"]
public class ExampleApp extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Do you want to close this window ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//  Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Title");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
}
}
[/sourcecode]
The output will looks like
alertdialogexample

Tuesday, November 8, 2011

Change system screen brightness, using android.provider.Settings.System.SCREEN_BRIGHTNESS

Change system screen brightness, using android.provider.Settings.System.SCREEN_BRIGHTNESS



android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
SysBackLightValue);

Change system screen brightness

To access Settings.System.SCREEN_BRIGHTNESS, we have to modify AndroidManifest.xml to grant premission of "android.permission.WRITE_SETTINGS".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exercise.AndroidScreenBrightness"
    android:versionCode="1"
    android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
      <activity android:name=".AndroidScreenBrightness"
                android:label="@string/app_name">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>

  </application>
  <uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</manifest>


main code
package com.exercise.AndroidScreenBrightness;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class AndroidScreenBrightness extends Activity {
  /** Called when the activity is first created. */

float BackLightValue = 0.5f; //dummy default value

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      SeekBar BackLightControl = (SeekBar)findViewById(R.id.backlightcontrol);
      final TextView BackLightSetting = (TextView)findViewById(R.id.backlightsetting);
      Button UpdateSystemSetting = (Button)findViewById(R.id.updatesystemsetting);
    
      UpdateSystemSetting.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
  
   int SysBackLightValue = (int)(BackLightValue * 255);
  
   android.provider.Settings.System.putInt(getContentResolver(),
     android.provider.Settings.System.SCREEN_BRIGHTNESS,
     SysBackLightValue);
  
  }});
    
      BackLightControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
   // TODO Auto-generated method stub
   BackLightValue = (float)arg1/100;
   BackLightSetting.setText(String.valueOf(BackLightValue));
  
   WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
   layoutParams.screenBrightness = BackLightValue;
   getWindow().setAttributes(layoutParams);

  
  }

  @Override
  public void onStartTrackingTouch(SeekBar arg0) {
   // TODO Auto-generated method stub
  
  }

  @Override
  public void onStopTrackingTouch(SeekBar arg0) {
   // TODO Auto-generated method stub
  
  }});
  }
}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Set BackLight of the App"
  />
<SeekBar
  android:id="@+id/backlightcontrol"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="10px"
  android:max="100"
  android:progress="50"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/backlightsetting"
  android:text="0.50"
  />
<Button
  android:id="@+id/updatesystemsetting"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Update Settings.System.SCREEN_BRIGHTNESS"
  />
</LinearLayout>
content -->