Wednesday, 30 January 2013

Adding Rows dynamically in Android

public class MainActivity extends Activity {

    String companies[] = {"Google","iPhone","Nokia","Samsung",
                          "Google","Windows","iPhone","Nokia","Samsung",
                          "Google","Windows","iPhone","Nokia","Samsung","waseela"};
    String os[]       =  {"Android","iOS","Bada",
                          "Android","Mango","iOS","Symbian","Bada",
                          "Android","Mango","iOS","Symbian","Bada","wwwwwwww","wx"};

    TableLayout tl;
    TableRow tr;
    TextView companyTV,valueTV;
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       tl = (TableLayout) findViewById(R.id.maintable);
       addHeaders();
       addData();
   }
   /** This function add the headers to the table **/
   public void addHeaders(){

        /** Create a TableRow dynamically **/
       tr = new TableRow(this);
       tr.setLayoutParams(new LayoutParams(
               LayoutParams.FILL_PARENT,
               LayoutParams.WRAP_CONTENT));

       /** Creating a TextView to add to the row **/
       TextView companyTV = new TextView(this);
       companyTV.setText("Companies");
       companyTV.setTextColor(Color.GRAY);
       companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
       companyTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
       companyTV.setPadding(5, 5, 5, 0);
       tr.addView(companyTV);  // Adding textView to tablerow.

       /** Creating another textview **/
       TextView valueTV = new TextView(this);
       valueTV.setText("Operating Systems");
       valueTV.setTextColor(Color.GRAY);
       valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
       valueTV.setPadding(5, 5, 5, 0);
       valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
       tr.addView(valueTV); // Adding textView to tablerow.

       // Add the TableRow to the TableLayout
       tl.addView(tr, new TableLayout.LayoutParams(
               LayoutParams.FILL_PARENT,
               LayoutParams.WRAP_CONTENT));

       // we are adding two textviews for the divider because we have two columns
       tr = new TableRow(this);
       tr.setLayoutParams(new LayoutParams(
               LayoutParams.FILL_PARENT,
               LayoutParams.WRAP_CONTENT));

       /** Creating another textview **/
       TextView divider = new TextView(this);
       divider.setText("-----------------");
       //divider.setTextColor(Color.<span class="IL_AD" id="IL_AD11">GREEN</span>);
       divider.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
       divider.setPadding(5, 0, 0, 0);
       divider.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
       tr.addView(divider); // Adding textView to tablerow.

       TextView divider2 = new TextView(this);
       divider2.setText("-------------------------");
       divider2.setTextColor(Color.GREEN);
       divider2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
       divider2.setPadding(5, 0, 0, 0);
       divider2.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
       tr.addView(divider2); // Adding textView to tablerow.

       // Add the TableRow to the TableLayout
       tl.addView(tr, new TableLayout.LayoutParams(
               LayoutParams.FILL_PARENT,
               LayoutParams.WRAP_CONTENT));
   }
   /** This function add the data to the table **/
   public void addData(){

       for (int i = 0; i < companies.length; i++)
       {
           /** Create a TableRow dynamically **/
           tr = new TableRow(this);
           tr.setLayoutParams(new LayoutParams(
                   LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));

           /** Creating a TextView to add to the row **/
           companyTV = new TextView(this);
           companyTV.setText(companies[i]);
           companyTV.setTextColor(Color.RED);
           companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
           companyTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
           companyTV.setPadding(5, 5, 5, 5);
           tr.addView(companyTV);  // Adding textView to tablerow.

           /** Creating another textview **/
           valueTV = new TextView(this);
           valueTV.setText(os[i]);
           valueTV.setTextColor(Color.GREEN);
           valueTV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
           valueTV.setPadding(5, 5, 5, 5);
           valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
           tr.addView(valueTV); // Adding textView to tablerow.

           // Add the TableRow to the TableLayout
           tl.addView(tr, new TableLayout.LayoutParams(
                   LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));
       }
   }
}

Tuesday, 29 January 2013

Handling HTTP POST method in Android

Hello Androidies… :-) Today I am going to talk about handling HTTP POST method in an Android program. This is little bit relate to my previous post which I have explained the same scenario for GET method. POST method is more secure when we transfer confidential data to a different location by using HTTP. The reason is the content goes inside the body, not with the header as in GET method.
Let me explain the scenario that I am going to accomplish with this blog post. I want to send some confidential data to a different server by using one of my native Android application. In the server side there is a PHP page listen to the parameters that I am passing and grab relevant data.
This is the UI (User Interface) part for this project.
HTTP POST method in Android
Figure 1
Actually, giving a username and a password is something additional when we concern about our main requirement. Our main requirement is sending a request to a web page by using HTTP POST method and listen to the response if it succeed. Additionally what I have done here is, prompting a Toast message if we get a response. Figure 2 shows the possible Toast messages that you will get. But understand clearly, that is NOT the response we get from the server. That is something we hard code in our program to show for the user, after getting the response.
HTTP POST method in Android
Figure 2
Are we ready to dive in to the source code :D Don’t forget to copy the code in to an IDE and read the comments, because I have explained the logic in the code and I am not going to repeat it here again.
package com.anuja.httppost;

/**
 * @author AnujAroshA
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyHttpPostProjectActivity extends Activity implements OnClickListener {

 private EditText usernameEditText;
 private EditText passwordEditText;
 private Button sendPostReqButton;
 private Button clearButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        usernameEditText = (EditText) findViewById(R.id.login_username_editText);
        passwordEditText = (EditText) findViewById(R.id.login_password_editText);

        sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);
        sendPostReqButton.setOnClickListener(this);

        clearButton = (Button) findViewById(R.id.login_clear_button);
        clearButton.setOnClickListener(this);        
    }

 @Override
 public void onClick(View v) {

  if(v.getId() == R.id.login_clear_button){
   usernameEditText.setText("");
   passwordEditText.setText("");
   passwordEditText.setCursorVisible(false);
   passwordEditText.setFocusable(false);
   usernameEditText.setCursorVisible(true);
   passwordEditText.setFocusable(true);
  }else if(v.getId() == R.id.login_sendPostReq_button){
   String givenUsername = usernameEditText.getEditableText().toString();
   String givenPassword = passwordEditText.getEditableText().toString();

   System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);

   sendPostRequest(givenUsername, givenPassword);
  } 
 }

 private void sendPostRequest(String givenUsername, String givenPassword) {

  class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{

   @Override
   protected String doInBackground(String... params) {

    String paramUsername = params[0];
    String paramPassword = params[1];

    System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);

    HttpClient httpClient = new DefaultHttpClient();

    // In a POST request, we don't pass the values in the URL.
    //Therefore we use only the web page URL as the parameter of the HttpPost argument
    HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php");

    // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
    //uniquely separate by the other end.
    //To achieve that we use BasicNameValuePair    
    //Things we need to pass with the POST request
    BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
    BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);

    // We add the content that we want to pass with the POST request to as name-value pairs
    //Now we put those sending details to an ArrayList with type safe of NameValuePair
    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
    nameValuePairList.add(usernameBasicNameValuePair);
    nameValuePairList.add(passwordBasicNameValuePAir);

    try {
     // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
     //This is typically useful while sending an HTTP POST request. 
     UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

     // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
     httpPost.setEntity(urlEncodedFormEntity);

     try {
      // HttpResponse is an interface just like HttpPost.
      //Therefore we can't initialize them
      HttpResponse httpResponse = httpClient.execute(httpPost);

      // According to the JAVA API, InputStream constructor do nothing. 
      //So we can't initialize InputStream although it is not an interface
      InputStream inputStream = httpResponse.getEntity().getContent();

      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

      StringBuilder stringBuilder = new StringBuilder();

      String bufferedStrChunk = null;

      while((bufferedStrChunk = bufferedReader.readLine()) != null){
       stringBuilder.append(bufferedStrChunk);
      }

      return stringBuilder.toString();

     } catch (ClientProtocolException cpe) {
      System.out.println("First Exception caz of HttpResponese :" + cpe);
      cpe.printStackTrace();
     } catch (IOException ioe) {
      System.out.println("Second Exception caz of HttpResponse :" + ioe);
      ioe.printStackTrace();
     }

    } catch (UnsupportedEncodingException uee) {
     System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
     uee.printStackTrace();
    }

    return null;
   }

   @Override
   protected void onPostExecute(String result) {
    super.onPostExecute(result);

    if(result.equals("working")){
     Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
    }else{
     Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
    }
   }   
  }

  SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
  sendPostReqAsyncTask.execute(givenUsername, givenPassword);  
 }
}
Compare above code set with the HTTP GET method code set that I have posted in my previous post. Then you will get a clear idea about what I have changed, where I have changed and why I have changed that code set. Don’t forget to see the differences in the PHP pages also ;-)
<?php

$varUsername = $_POST['paramUsername'];
$varPassword = $_POST['paramPassword'];

if($varUsername == "anuja" && $varPassword == "123"){
 echo 'working';
}else{
 echo 'invalid';
}

?>
Now time for wrap-up. Thanks “Nirman” for hosting my “postLogin.php”.
Let’s meet with something different in next time :-)

Monday, 28 January 2013

Gradient Drawing Example in Android

This example shows how you can draw different gradient shapes in android.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it GradientDrawingExample.
2.) Create and write following into src/GraphicsActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.example.GradientDrawingExample;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
 
class GraphicsActivity extends Activity {
    private static final boolean TEST_PICTURE = false;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
 
    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }
 
        super.setContentView(view);
    }
}
3.) Create and write following into src/PictureLayout.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package com.example.GradientDrawingExample;
 
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
 
public class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();
 
    public PictureLayout(Context context) {
        super(context);
    }
 
    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }
 
        super.addView(child);
    }
 
    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }
 
        super.addView(child, index);
    }
 
    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }
 
        super.addView(child, params);
    }
 
    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }
 
        super.addView(child, index, params);
    }
 
    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
 
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();
 
        int maxHeight = 0;
        int maxWidth = 0;
 
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
 
        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();
 
        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }
 
        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }
 
    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }
 
    @SuppressWarnings("unused")
    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();
 
        int x = getWidth()/2;
        int y = getHeight()/2;
 
        if (false) {
            canvas.drawPicture(mPicture);
        } else {
            drawPict(canvas, 0, 0, x, y,  11);
            drawPict(canvas, x, 0, x, y, -11);
            drawPict(canvas, 0, y, x, y,  1, -1);
            drawPict(canvas, x, y, x, y, -1, -1);
        }
    }
 
    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }
 
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();
 
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());
 
            }
        }
    }
}
4.) Create and write following into res/drawable/line.xml:
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
    <stroke android:width="1dp" android:color="#FF000000"
            android:dashWidth="1dp" android:dashGap="2dp" />
    <size android:height="5dp" />
</shape>
5.) Create and write following into res/drawable/shape_1.xml:
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
 
    <solid android:color="#00000000"/>
    <stroke android:width="2dp" android:color="#ff000000"/>
    <padding android:left="1dp" android:top="1dp"
            android:right="1dp" android:bottom="1dp" />
</shape>
6.) Create and write following into res/drawable/shape_2.xml:
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
    <solid android:color="#FF0000FF"/>
    <stroke android:width="4dp" android:color="#FFFFFFFF"
            android:dashWidth="1dp" android:dashGap="2dp" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape>
7.) Create and write following into res/drawable/shape_3.xml:
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#00000000"/>
    <stroke android:width="4dp" android:color="#99000000"
            android:dashWidth="4dp" android:dashGap="2dp" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape>
8.) Create and write following into res/drawable/shape_4.xml:
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line">
    <stroke android:width="1dp" android:color="#FF000000"
            android:dashWidth="1dp" android:dashGap="2dp" />
</shape>
9.) Create and write following into res/drawable/shape_5.xml:
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
            android:angle="270"/>
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>
10.) Write following into main.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
     
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
         
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:src="@drawable/shape_1" />
             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:src="@drawable/shape_2" />
             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:src="@drawable/shape_3" />
             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
                     
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:src="@drawable/shape_4" />
             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
                             
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:src="@drawable/shape_5" />
    </LinearLayout>
</ScrollView>
11.) Run for output.
Steps:
1.) Create a project named GradientDrawingExample and set the information as stated in the image.
Build Target: Android 4.0
Application Name: GradientDrawingExample
Package Name: com. example. GradientDrawingExample
Activity Name: GradientDrawingExampleActivity
Min SDK Version: 14

2.) Open GradientDrawingExampleActivity.java file and write following code there:
1
2
3
4
5
6
7
8
9
10
11
package com.example.GradientDrawingExample;
 
import android.os.Bundle;
 
public class GradientDrawingExampleActivity extends GraphicsActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
3.) Compile and build the project.
Output