Monday 29 September 2014

How to add Rounded Corner borders to Android Layout


 How to add Rounded Corner borders to Android Layout


Create a xml file under your drawable folder with following code. (The name of the file I created is rounded_corner.xml)

rounded_corner.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
    android:shape="rectangle">
    <!-- view background color -->
    <solid
        android:color="#a9c5ac" >
    </solid>
    <!-- view border color and width -->
    <stroke
        android:width="3dp"
        android:color="#1c1b20" >
    </stroke>
    <!-- If you want to add some padding -->
    <padding
        android:left="4dp"
        android:top="4dp"
        android:right="4dp"
        android:bottom="4dp"    >
    </padding>
    <!-- Here is the corner radius -->
    <corners
        android:radius="10dp"   >
    </corners>
</shape>

And keep this drawable as background for the view to which you want to keep rounded corner border. Let’s keep it for a LinearLayout

<LinearLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner"
        android:layout_centerInParent="true">
         
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hi, This layout has rounded corner borders ..."
            android:gravity="center"
            android:padding="5dp"/>
         
    </LinearLayout>

C Program For DFS–Depth First Search

C Program For DFS–Depth First Search

#include<stdio.h>
#include<conio.h>
void dfs(int v);
typedef enum boolean{false,true}bool;
int n,a[10][10];
bool visited[10];
void main()
{
int i,j,v;
printf("Enter the no. of nodes in the graph\n");
scanf("%d",&n);
printf("Enter the adjacency matrix \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The adjacency matrix shown as\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
printf("Enter the starting node for Depth First search\n");
scanf("%d",&v);
for(i=1;i<=n;i++)
visited[i]=false;
dfs(v);
getch();
}
void dfs(int v)
{
int i,stack[10],top=-1,pop;
top++;
stack[top]=v;
while(top>=0)
{
pop=stack[top];
top--;
if(visited[pop]==false)
{
printf("%d",pop);
visited[pop]=true;
}
else
continue;
for(i=n;i>=1;i--)
{
if(a[pop][i]==1 && visited[i]==false)
{
top++;// push all the unvisited neighbours in the stack
stack[top]=i;
}
}
}
}

C Animation for a Moving Kite

C Animation for a Moving Kite

#include<conio.h>
#include<stdio.h>
#include<graphics.h>
void main()
{
int i;
int gd=DETECT,gm;
initgraph(&gd,&gm,”C:\\TC\\bgi”);
line(250,200,200,250);
line(200,250,250,300);
line(250,300,300,250);
line(300,250,250,200);
line(250,300,225,325);
line(225,325,275,325);
line(275,325,250,300);
i=0;
while(i<200)
                {
                cleardevice();
                line(250-i,200-i,200-i,250-i);        
                line(200-i,250-i,250-i,300-i);
                line(250-i,300-i,300-i,250-i);
                line(300-i,250-i,250-i,200-i);
                line(250-i,300-i,225-i,325-i);
                line(225-i,325-i,275-i,325-i);
                line(275-i,325-i,250-i,300-i);
                i+=5;
                delay(100);
                }
getch();
closegraph();
}

C Program for Animation Sunrise

C Program for Animation Sunrise

#include<graphics.h>

#include<conio.h>

#include<stdio.h>

void main()

{

int gd=DETECT,gm;

int i,j,k,t,q;

float x,y;

initgraph(&gd,&gm,"c:\\tc\\bgi");

setcolor(3);

rectangle(0,0,getmaxx(),getmaxy());

&nbsp;setcolor(2);

&nbsp;i=0;

for(t=0;t<getmaxx();t+=120)

{

line(t,250,t+60,170);

line(t+60,170,t+120,250);

}

line(0,400,getmaxx(),350);

setfillstyle(11,CYAN);

floodfill(2,420,2);

setfillstyle(4,LIGHTGREEN);

floodfill(1,300,2);

 

i=0;

while(i!=150)

{

 

setcolor(BLACK);

setfillstyle(SOLID_FILL,BLACK);

fillellipse(k,j,30,30);

setfillstyle(SOLID_FILL,LIGHTRED);

fillellipse(170+i,235-i,30,30);

j=235-i;

k=170+i;

i++;

setcolor(2);

for(t=0;t<getmaxx();t+=120)

{

line(t,250,t+60,170);

line(t+60,170,t+120,250);

}

setfillstyle(1,GREEN);

floodfill(202,200,GREEN);

delay(25);

}

 

for(i=36;i<80;i++)

for(j=0;j<=360;j+=20)

{

x=319+i*cos(((float)j*3.14)/180);

y=86+i*sin(((float)j*3.14)/180);

putpixel(x,y,LIGHTRED);

delay(1);

}

getch();

}

Friday 26 September 2014

Apply animation on Button

Apply animation on Button

Apply animation on ButtonCreate four XML files for animation:
/res/anim/anim_alpha.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/linear_interpolator">
   <alpha
       android:fromAlpha="1.0"
       android:toAlpha="0.1"
       android:duration="500"
       android:repeatCount="1"
       android:repeatMode="reverse" />
</set>


/res/anim/anim_rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/linear_interpolator">
   <rotate
       android:fromDegrees="0"
       android:toDegrees="360"
       android:pivotX="50%"
       android:pivotY="50%"
       android:duration="500"
       android:startOffset="0"
       android:repeatCount="1"
       android:repeatMode="reverse" />
</set>


/res/anim/anim_scale.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/linear_interpolator">
   <scale
       android:fromXScale="1.0"
       android:toXScale="3.0"
       android:fromYScale="1.0"
       android:toYScale="3.0"
       android:pivotX="50%"
       android:pivotY="50%"
       android:duration="500"
       android:repeatCount="1"
       android:repeatMode="reverse" />
</set>


/res/anim/anim_translate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/linear_interpolator">
   <translate
       android:fromXDelta="0"
       android:toXDelta="100%p"
       android:duration="500"
       android:repeatCount="1"
       android:repeatMode="reverse"/>
</set>


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello" />

   <Button
       android:id="@+id/translate"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:text="Translate" />
   <Button
       android:id="@+id/alpha"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:text="Alpha" />
   <Button
       android:id="@+id/scale"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:text="Scale" />
   <Button
       android:id="@+id/rotate"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:text="Rotate" />

</LinearLayout>


Main activity:
package com.exercise.AndroidAnimButtons;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

public class AndroidAnimButtonsActivity extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       final Animation animTranslate = AnimationUtils.loadAnimation(this, R.anim.anim_translate);
       final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
       final Animation animScale = AnimationUtils.loadAnimation(this, R.anim.anim_scale);
       final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
      
       Button btnTranslate = (Button)findViewById(R.id.translate);
       Button btnAlpha = (Button)findViewById(R.id.alpha);
       Button btnScale = (Button)findViewById(R.id.scale);
       Button btnRotate = (Button)findViewById(R.id.rotate);
      
       btnTranslate.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   arg0.startAnimation(animTranslate);
  }});
      
       btnAlpha.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   arg0.startAnimation(animAlpha);
  }});
      
       btnScale.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   arg0.startAnimation(animScale);
  }});
      
       btnRotate.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   arg0.startAnimation(animRotate);
  }});
   }
}

Call JavaScript inside WebView from Android activity, with parameter passed.

Call JavaScript inside WebView from Android activity, with parameter passed.

The last exercise "Run Android Java code from Webpage" show how to call from WebView JavaScript to Android activity. Here will show how to call in reverse direction: Call JavaScript inside WebView from Android activity, with parameter passed.

Call JavaScript inside WebView from Android activity, with parameter passed.

/assets/mypage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>
<p id="mytext">Hello!</p>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<input type="button" value="Open Dialog" onClick="openAndroidDialog()" />
<script language="javascript">
   function showAndroidToast(toast) {
       AndroidFunction.showToast(toast);
   }

   function openAndroidDialog() {
       AndroidFunction.openAndroidDialog();
   }
  
   function callFromActivity(msg){
 document.getElementById("mytext").innerHTML = msg;
   }
</script>

</body>
</html>


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"
   />
<EditText
   android:id="@+id/msg"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content" />
<Button
 android:id="@+id/sendmsg"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Msg to JavaScript"
   />
<WebView
   android:id="@+id/mybrowser"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
  />
</LinearLayout>


main code:
package com.exercise.AndroidHTML;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidHTMLActivity extends Activity {
 
 WebView myBrowser;
 EditText Msg;
 Button btnSendMsg;
 
 /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       myBrowser = (WebView)findViewById(R.id.mybrowser);
      
       final MyJavaScriptInterface myJavaScriptInterface
        = new MyJavaScriptInterface(this);
       myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
      
       myBrowser.getSettings().setJavaScriptEnabled(true); 
       myBrowser.loadUrl("file:///android_asset/mypage.html");
      
       Msg = (EditText)findViewById(R.id.msg);
    btnSendMsg = (Button)findViewById(R.id.sendmsg);
    btnSendMsg.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    String msgToSend = Msg.getText().toString();
    myBrowser.loadUrl("javascript:callFromActivity(\""+msgToSend+"\")");
    
   }});

   }
  
 public class MyJavaScriptInterface {
  Context mContext;

     MyJavaScriptInterface(Context c) {
         mContext = c;
     }
    
     public void showToast(String toast){
         Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
     }
    
     public void openAndroidDialog(){
      AlertDialog.Builder myDialog
      = new AlertDialog.Builder(AndroidHTMLActivity.this);
      myDialog.setTitle("DANGER!");
      myDialog.setMessage("You can do what you want!");
      myDialog.setPositiveButton("ON", null);
      myDialog.show();
     }

 }
}

Run Android Java code from Web Page

Run Android Java code from Web Page



Run Android Java code from Webpage



Modify /assets/mypage.html to add two button to call JavascriptInterface in Android Java code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
 function showAndroidToast(toast) {
     AndroidFunction.showToast(toast);
 }
</script>

<input type="button" value="Open Dialog" onClick="openAndroidDialog()" />

<script type="text/javascript">
 function openAndroidDialog() {
     AndroidFunction.openAndroidDialog();
 }
</script>

</body>
</html>



Main code, to add our JavascriptInterface.
package com.exercise.AndroidHTML;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

public class AndroidHTMLActivity extends Activity {

WebView myBrowser;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     myBrowser = (WebView)findViewById(R.id.mybrowser);
     myBrowser.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidFunction");
  
     myBrowser.getSettings().setJavaScriptEnabled(true);
     myBrowser.loadUrl("file:///android_asset/mypage.html");

 }

public class MyJavaScriptInterface {
 Context mContext;

    MyJavaScriptInterface(Context c) {
        mContext = c;
    }

    public void showToast(String toast){
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
 
    public void openAndroidDialog(){
     AlertDialog.Builder myDialog
     = new AlertDialog.Builder(AndroidHTMLActivity.this);
     myDialog.setTitle("DANGER!");
     myDialog.setMessage("You can do what you want!");
     myDialog.setPositiveButton("ON", null);
     myDialog.show();
    }

}
}

Example of using PopupWindow

Example of using PopupWindow

android.widget.PopupWindow can be used to display an arbitrary view. The popup windows is a floating container that appears on top of the current activity.

Example of PopupWindow

Create /res/layout/popup.xml to define the view of the PopupWindow.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@android:color/background_light">
 <LinearLayout 
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:orientation="vertical" 
     android:layout_margin="1dp"
     android:background="@android:color/darker_gray">
     >
     <LinearLayout 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="vertical" 
      android:layout_margin="20dp">
      <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="It's a PopupWindow" />
      <ImageView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:src="@drawable/ic_launcher" />
      <Button
          android:id="@+id/dismiss"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Dismiss" />
      </LinearLayout>
 </LinearLayout>
</LinearLayout>


Main activity Java code to handle the PopupWindow
package com.exercise.AndroidPopupWindow;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;

public class AndroidPopupWindowActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button btnOpenPopup = (Button)findViewById(R.id.openpopup);
        btnOpenPopup.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    LayoutInflater layoutInflater 
     = (LayoutInflater)getBaseContext()
      .getSystemService(LAYOUT_INFLATER_SERVICE);  
    View popupView = layoutInflater.inflate(R.layout.popup, null);  
             final PopupWindow popupWindow = new PopupWindow(
               popupView, 
               LayoutParams.WRAP_CONTENT,  
                     LayoutParams.WRAP_CONTENT);  
             
             Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
             btnDismiss.setOnClickListener(new Button.OnClickListener(){

     @Override
     public void onClick(View v) {
      // TODO Auto-generated method stub
      popupWindow.dismiss();
     }});
               
             popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
         
   }});
    }
}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/openpopup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Open Popup Window" />
    
</LinearLayout>

Example of using Timer and TimerTask on Android

Example of using Timer and TimerTask on Android

This exercise show how to use java.util.Timer and java.util.TimerTask in Android programming.

java.util.Timer is a facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. java.util.TimerTask is a task that can be scheduled for one-time or repeated execution by a Timer.

Example of using Timer and TimerTask


package com.example.androidtimer;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {
 
 CheckBox optSingleShot;
 Button btnStart, btnCancel;
 TextView textCounter;
 
 Timer timer;
 MyTimerTask myTimerTask;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  optSingleShot = (CheckBox)findViewById(R.id.singleshot);
  btnStart = (Button)findViewById(R.id.start);
  btnCancel = (Button)findViewById(R.id.cancel);
  textCounter = (TextView)findViewById(R.id.counter);
  
  btnStart.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {

    if(timer != null){
     timer.cancel();
    }
    
    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();
    
    if(optSingleShot.isChecked()){
     //singleshot delay 1000 ms
     timer.schedule(myTimerTask, 1000);
    }else{
     //delay 1000ms, repeat in 5000ms
     timer.schedule(myTimerTask, 1000, 5000);
    }
   }});
  
  btnCancel.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    if (timer!=null){
     timer.cancel();
     timer = null;
    }
   }
  });
  
 }

 class MyTimerTask extends TimerTask {

  @Override
  public void run() {
   Calendar calendar = Calendar.getInstance();
   SimpleDateFormat simpleDateFormat = 
     new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
   final String strDate = simpleDateFormat.format(calendar.getTime());
   
   runOnUiThread(new Runnable(){

    @Override
    public void run() {
     textCounter.setText(strDate);
    }});
  }
  
 }

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <CheckBox 
        android:id="@+id/singleshot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Single Shot"/>
 <Button 
     android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start"/>
 <Button 
     android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel"/>
    <TextView
     android:id="@+id/counter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:textStyle="bold"/>
</LinearLayout>

Android Server/Client example - client side using Socket

Android Server/Client example - client side using Socket

It's the client side implementation of our Server/Client example, the server side is listed in last post "server side using ServerSocket".

Android client side using Socket
Android client side using Socket

package com.example.androidclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

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

public class MainActivity extends Activity {
 
 TextView textResponse;
 EditText editTextAddress, editTextPort; 
 Button buttonConnect, buttonClear;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  editTextAddress = (EditText)findViewById(R.id.address);
  editTextPort = (EditText)findViewById(R.id.port);
  buttonConnect = (Button)findViewById(R.id.connect);
  buttonClear = (Button)findViewById(R.id.clear);
  textResponse = (TextView)findViewById(R.id.response);
  
  buttonConnect.setOnClickListener(buttonConnectOnClickListener);
  
  buttonClear.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    textResponse.setText("");
   }});
 }
 
 OnClickListener buttonConnectOnClickListener = 
   new OnClickListener(){

    @Override
    public void onClick(View arg0) {
     MyClientTask myClientTask = new MyClientTask(
       editTextAddress.getText().toString(),
       Integer.parseInt(editTextPort.getText().toString()));
     myClientTask.execute();
    }};

 public class MyClientTask extends AsyncTask<Void, Void, Void> {
  
  String dstAddress;
  int dstPort;
  String response = "";
  
  MyClientTask(String addr, int port){
   dstAddress = addr;
   dstPort = port;
  }

  @Override
  protected Void doInBackground(Void... arg0) {
   
   Socket socket = null;
   
   try {
    socket = new Socket(dstAddress, dstPort);
    
    ByteArrayOutputStream byteArrayOutputStream = 
                  new ByteArrayOutputStream(1024);
    byte[] buffer = new byte[1024];
    
    int bytesRead;
    InputStream inputStream = socket.getInputStream();
    
    /*
     * notice:
     * inputStream.read() will block if no data return
     */
             while ((bytesRead = inputStream.read(buffer)) != -1){
                 byteArrayOutputStream.write(buffer, 0, bytesRead);
                 response += byteArrayOutputStream.toString("UTF-8");
             }

   } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    response = "UnknownHostException: " + e.toString();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    response = "IOException: " + e.toString();
   }finally{
    if(socket != null){
     try {
      socket.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {
   textResponse.setText(response);
   super.onPostExecute(result);
  }
  
 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <EditText 
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="dstAddress" />
    <EditText 
        android:id="@+id/port"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="dstPort" />
    <Button 
        android:id="@+id/connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connect..."/>
    <Button 
        android:id="@+id/clear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Clear"/>
    <TextView
        android:id="@+id/response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

Apply LruCache on GridView

Apply LruCache on GridView

Reference: http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#memory-cache

GridView with LruCache


To using android.util.LruCache in the code, targetSdkVersion of "13" is needed to be specified in AndroidManifest.xml.

The layout file, refer to the post "GridView loading photos from SD Card".

package com.example.androidgridview;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    public class ImageAdapter extends BaseAdapter {
     
     private Context mContext;
     ArrayList<String> itemList = new ArrayList<String>();
     
     public ImageAdapter(Context c) {
      mContext = c; 
     }
     
     void add(String path){
      itemList.add(path); 
     }

  @Override
  public int getCount() {
   return itemList.size();
  }

  @Override
  public Object getItem(int arg0) {
   // TODO Auto-generated method stub
   return null;
  }

  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return 0;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   ImageView imageView;
         if (convertView == null) {  // if it's not recycled, initialize some attributes
             imageView = new ImageView(mContext);
             imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
             imageView.setPadding(8, 8, 8, 8);
         } else {
             imageView = (ImageView) convertView;
         }

         //Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
         
         // Use the path as the key to LruCache
         final String imageKey = itemList.get(position);
           final Bitmap bm = getBitmapFromMemCache(imageKey);
           
         if (bm == null){
          BitmapWorkerTask task = new BitmapWorkerTask(imageView);
          task.execute(imageKey);
         };

         imageView.setImageBitmap(bm);
         return imageView;
  }
  
  public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
   
   Bitmap bm = null;
   // First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(path, options);
       
   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
       
   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   bm = BitmapFactory.decodeFile(path, options); 
       
   return bm;   
  }
  
  public int calculateInSampleSize(
    
   BitmapFactory.Options options, int reqWidth, int reqHeight) {
   // Raw height and width of image
   final int height = options.outHeight;
   final int width = options.outWidth;
   int inSampleSize = 1;
   
   if (height > reqHeight || width > reqWidth) {
    if (width > height) {
     inSampleSize = Math.round((float)height / (float)reqHeight);    
    } else {
     inSampleSize = Math.round((float)width / (float)reqWidth);    
    }   
   }
   
   return inSampleSize;    
  }
  
  class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap>{
   
   private final WeakReference<ImageView> imageViewReference;
   
   public BitmapWorkerTask(ImageView imageView) {
    // Use a WeakReference to ensure the ImageView can be garbage collected
    imageViewReference = new WeakReference<ImageView>(imageView); 
   }
   
   @Override
   protected Bitmap doInBackground(String... params) {
    final Bitmap bitmap = decodeSampledBitmapFromUri(params[0], 200, 200);
    addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
    return bitmap;
   }

   @Override
   protected void onPostExecute(Bitmap bitmap) {
    if (imageViewReference != null && bitmap != null) {
     final ImageView imageView = (ImageView)imageViewReference.get();
     if (imageView != null) {
      imageView.setImageBitmap(bitmap); 
     } 
    } 
   }
  }

 }
    
    ImageAdapter myImageAdapter;
    
    private LruCache<String, Bitmap> mMemoryCache;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        GridView gridview = (GridView) findViewById(R.id.gridview);
        myImageAdapter = new ImageAdapter(this);
        gridview.setAdapter(myImageAdapter);
        
        String ExternalStorageDirectoryPath = Environment
          .getExternalStorageDirectory()
          .getAbsolutePath();
        
        String targetPath = ExternalStorageDirectoryPath + "/test/";
        
        Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
        File targetDirector = new File(targetPath);
        
        File[] files = targetDirector.listFiles();
        for (File file : files){
         myImageAdapter.add(file.getAbsolutePath());
        } 
        
        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        final int memClass 
         = ((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE))
          .getMemoryClass();
        
        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = 1024 * 1024 * memClass / 8;
        
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
         
         @Override
         protected int sizeOf(String key, Bitmap bitmap) {
          // The cache size will be measured in bytes rather than number of items.
          return bitmap.getByteCount(); 
         }
        };
    }
 
 public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
  if (getBitmapFromMemCache(key) == null) {
   mMemoryCache.put(key, bitmap); 
  } 
 }
 
 public Bitmap getBitmapFromMemCache(String key) {
  return (Bitmap) mMemoryCache.get(key); 
 }

}

GridView loading photos from SD Card

GridView loading photos from SD Card

Previous exercises described how to implement "Gallery-like HorizontalScrollView" and "Vertical Gallery-like ScrollView". Alternatively, it can be displayed in GridView.

GridView


Add a <GridView> in layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>

</LinearLayout>


Main code:
package com.example.androidgridview;

import java.io.File;
import java.util.ArrayList;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    public class ImageAdapter extends BaseAdapter {
     
     private Context mContext;
     ArrayList<String> itemList = new ArrayList<String>();
     
     public ImageAdapter(Context c) {
      mContext = c; 
     }
     
     void add(String path){
      itemList.add(path); 
     }

  @Override
  public int getCount() {
   return itemList.size();
  }

  @Override
  public Object getItem(int arg0) {
   // TODO Auto-generated method stub
   return null;
  }

  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return 0;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   ImageView imageView;
         if (convertView == null) {  // if it's not recycled, initialize some attributes
             imageView = new ImageView(mContext);
             imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
             imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
             imageView.setPadding(8, 8, 8, 8);
         } else {
             imageView = (ImageView) convertView;
         }

         Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);

         imageView.setImageBitmap(bm);
         return imageView;
  }
  
  public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
   
   Bitmap bm = null;
   // First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(path, options);
       
   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
       
   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   bm = BitmapFactory.decodeFile(path, options); 
       
   return bm;   
  }
  
  public int calculateInSampleSize(
    
   BitmapFactory.Options options, int reqWidth, int reqHeight) {
   // Raw height and width of image
   final int height = options.outHeight;
   final int width = options.outWidth;
   int inSampleSize = 1;
   
   if (height > reqHeight || width > reqWidth) {
    if (width > height) {
     inSampleSize = Math.round((float)height / (float)reqHeight);    
    } else {
     inSampleSize = Math.round((float)width / (float)reqWidth);    
    }   
   }
   
   return inSampleSize;    
  }

 }
    
    ImageAdapter myImageAdapter;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        GridView gridview = (GridView) findViewById(R.id.gridview);
        myImageAdapter = new ImageAdapter(this);
        gridview.setAdapter(myImageAdapter);
        
        String ExternalStorageDirectoryPath = Environment
          .getExternalStorageDirectory()
          .getAbsolutePath();
        
        String targetPath = ExternalStorageDirectoryPath + "/test/";
        
        Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
        File targetDirector = new File(targetPath);
        
        File[] files = targetDirector.listFiles();
        for (File file : files){
         myImageAdapter.add(file.getAbsolutePath());
        } 
    }

}

Donate