Monthly Archives: April 2011

Customizing your button or TextView or another view in ANDROID.

Beautifying our applications is one of the main features of your application’s success.
In ANDROID there are many possible ways to do this.
For eg. We need to have different colors for our buttons, However we can give backgrounds for buttons and all. But we can do many by using our custom xml files, like changing colors on button press and release, transitions etc. This tutorial explains such an example. Extend this example to create your own custom button.

Create a fresh project and copy this code to your main file.

package pack.coderzheaven;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class SelectorExample extends Activity {
    private Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("Button clicked!!");
			}
		});

        ImageButton button = (ImageButton) findViewById(R.id.button);
        TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
        drawable.startTransition(5000);

        Resources res = getResources();
        Drawable shape = res. getDrawable(R.drawable.gradient_box);

        TextView tv = (TextView)findViewById(R.id.textview);
        tv.setBackgroundDrawable(shape);
    }
}

Now the main.xml file

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

	<ImageButton android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:src="@drawable/transition">
	</ImageButton>

	<TextView
		android:id="@+id/textview"
		android:text="CoderzHeaven"
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent" />
	<Button android:id="@+id/Button01"
		android:background="@drawable/buttonhighlight"
		android:layout_height="50px"
		android:layout_width="fill_parent"
		android:text="CoderzHeaven"	>
	</Button>
</LinearLayout>

Now create an xml file named “gradient_box.xml” in your drawable folder and copy this code to it.
This xml helps you to define the shape for the view for which you are applying this.

<?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="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Now create an xml file named “transition.xml” in your drawable folder and copy this code to it.
This xml file is for applying a transition for your view

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/on" />
    <item android:drawable="@drawable/off" />
</transition>

Now the AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.selectors"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SelectorExample"
                  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>
</manifest>

Note: Make sure that you have all the images in your drawable folder as shown in the image below.

See the ImageButton transformation in the consequent pictures.


Please leave your comments if you find this post useful!

How to detect single/double/triple taps in iPhone ?

Hi,
How can you detect single/double/triple taps in iPhone using Objective C?
Use the following code to detect single or multiple taps in iPhone/iPad/iPod.
The code can also be used with Cocos2D & Box2D.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *urtouch = [touches anyObject];

    NSUInteger urtapCount = [urtouch tapCount];

    switch (urtapCount) {

       case 1:
         NSLog(@"Single Tap Detected!");
          break;

       case 2:
          NSLog(@"Double Tap Detected!");
          break;

       case 3:
        NSLog(@"Triple Tap Detected!");
        break;

      default :
       break;

   }
}

Try it out! You can even detect Quadrup!
🙂

How to use tableView in Titanium, iPhone or ANDROID?

This tutorial shows how to create a tableview in Titanium and add data to it.
How to handle a click function in the tableView and get the data from the row.


   /* Create a new window */
   var win = Titanium.UI.createWindow({
			backgroundColor:'#336699',
			backgroundImage:'images/bkg.png',
			navBarHidden:true,
			tabBarHidden:true
	});

	/* Datasource for the tableView */
    var my_data = [
		{title:'data1'},
		{title:'data2'},
		{title:'data3'},
		{title:'data4'},
		{title:'data5'}
	];

    var tableview = Titanium.UI.createTableView({
		data:my_data,
		top:0
	});

	/* Alternately you can use this to set the datasource in the tableView.
	tableview.setData(my_data);
	*/

	/* this will handle the click function in the tableView */
	tableview.addEventListener('click', function(e)
	{
		e.rowData.hasCheck = true;		 // add a checkmark to the row.
		var title = e.rowData.title;	       // get the title property of the clicked row.
                var index = e.index;                     // got the clicked index;
                Ti.API.info("Clicked on index : " + index + "with row title : " + title);
	});

	win.add(tableview); 				// add the tableview to the window.

	win.open();							// open the window.

Please leave your valuable comments.

C Sharp/C# – String Uppercase/Lowercase Conversion

Hi,

It will be very useful to know how you can convert a given string into uppercase or lowercase using program.
We are going to show you , how to convert a given string into uppercase or lowercase using C Sharp/C#. See the example given below.

using System;

class MainClass {
  public static void Main() {

    string sampleString = "CoDeRzHeAvEn";

    string strLwrCase = sampleString .ToLower();
    string strUprCase =  sampleString .ToUpper();

    Console.WriteLine("Lowercase of sampleString :n " +  strLwrCase );
    Console.WriteLine("Uppercase of sampleString :n " +  strUprCase );

  }
}

Output :
Lowercase of sampleString :
coderzheaven
Uppercase of sampleString :
CODERZHEAVEN

🙂

jQuery Hide & Show Toggle – An Example

Hi,

Want to try out a simple hide and show toggle using jQuery? The example given below shows how you can simply hide and show a paragraph in html using jQuery. Try it out!

&lt;html&gt;
&lt;head&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

$(document).ready(function(){

  $(&quot;#hideMe&quot;).click(function(){
    $(&quot;p&quot;).hide();
  });

  $(&quot;#showMe&quot;).click(function(){
    $(&quot;p&quot;).show();
  });

});

&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;p&gt;Coderz Heaven! Click 'HideMe' for hiding! Click 'ShowMe' for showing&lt;/p&gt;
&lt;button id=&quot;hideMe&quot;&gt;HideMe&lt;/button&gt;
&lt;button id=&quot;showMe&quot;&gt;ShowMe&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

🙂

jQuery Hide & Show Toggle – An Example

Hi,

Want to try out a simple hide and show toggle using jQuery? The example given below shows how you can simply hide and show a paragraph in html using jQuery. Try it out!

&lt;html&gt;
&lt;head&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

$(document).ready(function(){

  $(&quot;#hideMe&quot;).click(function(){
    $(&quot;p&quot;).hide();
  });

  $(&quot;#showMe&quot;).click(function(){
    $(&quot;p&quot;).show();
  });

});

&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;p&gt;Coderz Heaven! Click 'HideMe' for hiding! Click 'ShowMe' for showing&lt;/p&gt;
&lt;button id=&quot;hideMe&quot;&gt;HideMe&lt;/button&gt;
&lt;button id=&quot;showMe&quot;&gt;ShowMe&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

🙂

jQuery Hide & Show Toggle – An Example

Hi,

Want to try out a simple hide and show toggle using jQuery? The example given below shows how you can simply hide and show a paragraph in html using jQuery. Try it out!

&lt;html&gt;
&lt;head&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

$(document).ready(function(){

  $(&quot;#hideMe&quot;).click(function(){
    $(&quot;p&quot;).hide();
  });

  $(&quot;#showMe&quot;).click(function(){
    $(&quot;p&quot;).show();
  });

});

&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;p&gt;Coderz Heaven! Click 'HideMe' for hiding! Click 'ShowMe' for showing&lt;/p&gt;
&lt;button id=&quot;hideMe&quot;&gt;HideMe&lt;/button&gt;
&lt;button id=&quot;showMe&quot;&gt;ShowMe&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

🙂

Cocos2D CCMenu – An Example

Hi,

While using cocos2D you may need to create some scenes with menu items on it. This example given below shows , how to create a cocos2D menu scene with menu items using images. You can have your own custom fancy image text indicating menu items using this.


//Creating the three menu items.
//You can use different images for selected view & normal view.
//On clicking menu will show selectedImage
CCMenuItemImage *Item1 = [CCMenuItemImage
                        itemFromNormalImage:@"Walk.png"
                        selectedImage:@"WalkTwo.png"
                        target:self
                        selector:@selector(walkAction:)];

CCMenuItemImage *Item2 = [CCMenuItemImage
			           itemFromNormalImage:@"Run.png"
				       selectedImage:@"RunTwo.png"
				       target:self
				       selector:@selector(runAction:)];

CCMenuItemImage *Item3 = [CCMenuItemImage
				       itemFromNormalImage:@"Jump.png"
				       selectedImage:@"JumpTwo.png"
				       target:self
				       selector:@selector(jumpAction:)];

//Adding menu items to the CCMenu. Don't forget to include 'nil'
CCMenu *selectMenu= [CCMenu menuWithItems:Item1, Item2, Item3, nil];
//Aligning & Adding CCMenu child to the scene
[selectMenu alignItemsVertically];
[self addChild:selectMenu];


//Different functions on below get called according to the menu item clicked.
- (void)walkAction:(id)sender
{
    [[CCDirector sharedDirector] replaceScene:[WalkingScene node]];
}

- (void)runAction:(id)sender
{
   [[Director sharedDirector] replaceScene:[runningScene node]];
}

- (void)jumpAction:(id)sender
{
    [[Director sharedDirector] replaceScene:[jumpingScene node]];
}

🙂

Android: Conversion to Dalvik format failed: Unable to execute dex: null

This error often comes when your android project size is large.

Try the following steps to remove the error

1. Clean the project

Project > Clean

2. Increase the memory allocated in eclipse.ini

Open the eclipse.ini file in the the Eclipse folder. Then edit

-Xms128m to -Xmx512m or something higher

Hope this help you

Compare two strings in C Sharp/C# – Case Insensitive

Hi,

Sometimes you may need to check whether two strings are equal or not equal by checking case insensitive. See the example below to see how to achieve the same using C Sharp /C#.

using System;

class MainClass {
  public static void Main() {

    string strOne = "heaven";

    string strTwo = "HEAVEN";

    if(String.Compare(strOne , strTwo , true) == 0)
      Console.WriteLine(strOne + " and " + strTwo + " are equal - Case Insensitive!");

    else
      Console.WriteLine(strOne + " and " + strTwo + " are not equal - Case Insensitive!");

  }
}

Output : heaven and HEAVEN are equal – Case Insensitive!

🙂

Program to generate Fibonacci series in C Sharp/C#

Hi,

Here is a simple program to generate Fibonacci series using C Sharp /C#. It will generate Fibonacci numbers < 100. [csharp] class MainClass { public static void Main() { int oldNum = 1; int presentNum = 1; int nextNum; System.Console.Write(presentNum + ","); while (presentNum < 100) { System.Console.Write(presentNum + ","); nextNum = presentNum + oldNum; oldNum = presentNum; presentNum = nextNum; } } } [/csharp] 🙂

How to create and delete a directory in SdCard in ANDROID?

Hi all……

This is a simple example to create and delete a directory in ANDROID.
Here the directly is created in the SDCARD. So first create an SDCARD and start the emulator with the SDCARD.

Let’s look at the program.
Use can use this program to create or delete a file in ANDROID also.

package pack.coderzheaven;

import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CreateDeleteDIR_Example extends Activity {

    Button b;
    TextView t;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        t = (TextView)findViewById(R.id.tv);
        b= (Button) findViewById(R.id.Button01);
        File dir = new File("/sdcard/new_dir");
        try{
          if(dir.mkdir()) {
             System.out.println("Directory created");
             t.setText("Directory created");
          } else {
             System.out.println("Directory is not created");
             t.setText("Directory is not created");
          }
        }catch(Exception e){
          e.printStackTrace();
        }

        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File del = new File("/sdcard/new_dir");
				 boolean success = del.delete();
			        if (!success) {
			           System.out.println("Deletion of directory failed!");
			        }
			}
        });

    	/* IF THE DIRECTORY IS NOT EMPTY . USE THIS FUNCTION */
	public static boolean deleteNon_EmptyDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteNon_EmptyDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	    return dir.delete();
	}
}

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:id="@+id/tv"
    />
<Button
	android:text="Delete Directory"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Now go to File-explorer in the window menu->show View and see the result.

After directory creation.

After directory deletion.

How to place a label or textBox or anyother control inside a tableView in Titanium, ANDROID or iPhone ?

Hi all……..
This tutorial is for Titanium users. This tutorial explains how to place a textBox or anyother control inside a tableView.
A tableview requires data in the form of a array, so we create an array (here array is named “data_array“) by adding the controls like textboxes and labels inside it. You can give a large number of properties to customize the controls. i have given some of them.

                var data_array= [];  // This is the array that we are going to give to the tableView.

                /* creating a textField to place in the tableView */
                var name_tf = Titanium.UI.createTextField({
			color:'#336699',
			hintText: 'Enter Name',
			height:45,
			value: "",
			left:100,right:10,
			textAlign:'right',
			autocorrect:false,
			scrollable:false,
			clearButtonMode:Titanium.UI.INPUT_BUTTONMODE_ONFOCUS,
			borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE
		});

               var place_tf = Titanium.UI.createTextField({
			color:'#336699',
			hintText: 'Enter place',
			height:45,
			value: "",
			left:100,right:10,
			textAlign:'right',
			autocorrect:false,
			scrollable:false,
			clearButtonMode:Titanium.UI.INPUT_BUTTONMODE_ONFOCUS,
			borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE
		});

              function addFirstRow()
		{
			var row = Ti.UI.createTableViewRow({height:45});
			row.backgroundColor = '#ffffff';
			row.selectedBackgroundColor = '#ffffff';

                        /* creating a label to place in the tableView */
			var label = Titanium.UI.createLabel({
					color:'#000', height:45,left:10,text:'App Name', width:280,
					font:{fontSize:18,fontFamily:'Arial', fontWeight:'bold'}
			});

			row.add(label);
			row.add(name_tf );
			row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
			row.className = 'control';
			data_array[0] = row;
		}

               function addSecondRow()
		{
			var row = Ti.UI.createTableViewRow({height:45});
			row.backgroundColor = '#ffffff';
			row.selectedBackgroundColor = '#ffffff';

			var label = Titanium.UI.createLabel({
					color:'#000', height:45,left:10,text:'App Name', width:280,
					font:{fontSize:18,fontFamily:'Arial', fontWeight:'bold'}
			});

			row.add(label);
			row.add(place_tf );
			row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
			row.className = 'control';
			data_array[1] = row;
		}

                addFirstRow();    /* calling the above functions */
                addSecondRow();

              /* Creating a tableView and placing the TextBox and Label inside it
                  here data is the property for which we have to provide the data-source */

               var tableview = Titanium.UI.createTableView({
			data:data_array,
			height:260,
			width:320,
			backgroundColor:'transparent',
			scrollable:'false',
			style:Titanium.UI.iPhone.TableViewStyle.GROUPED,
			top:25
		});

Now you have created a tableView with 2 controls in each row.
Make sure to add this to your window to view it.
Please leave your comments if this post was useful.

Get files from a directory – C#/C Sharp

Hi,

Sometimes you may need to get the files from a specified directory using C# / C Sharp. See the sample code on how it works.

using System;
using System.IO;

class MainClass
{
  public static void Main()
  {
    string[] yourFiles = Directory.GetFiles("c:");

    foreach (string fNames in yourFiles)

      Console.WriteLine(fNames);
  }

}

This code will get you files from the root directory.

🙂

C#/C Sharp – Delete file in a folder

Hi,

Let’s see a simple example of deleting a file in a folder using c#.

using System;
using System.IO;

public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo sampleFile= new FileInfo(@"c:SamplestestFile.txt");

    sampleFile.Create();

    sampleFile.Delete();

  }
}

sampleFile.Create() will create the file in the specified folder.
sampleFile.Delete() will delete the file in the specified folder.

🙂

ANDROID – Upload an image to Server in Android Studio

Hi all,

In today’s tutorial I will show you how to send an image to server using POST method in ANDROID.

Uploading an image to server is a basic requirement in many of our application.
Sending data to server which is using a PHP Script is already explained in this example .
Now in this example I will show you how to send an image file.

For that first we have to read the file, put it in nameValuePairs and then send using HttpPost.

I have already shown you three other methods on uploading a file to server. If you want you can check these posts.

These are for downloading files from the server.

if you want to use the android using php and mysql
please check these posts.

Add Permission

Add “android.permission.INTERNET” permission to your AndroidManifest.xml file.

Note

You need to add the below to your build.gradle since Apache library is deprecated by Google.

android {
useLibrary ‘org.apache.http.legacy’
}

build.gradle

Our Sample build.gradle may look like this.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.coderzheaven.uploadimage"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

android {
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
}

Our Sample XML layout will look like this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.coderzheaven.uploadimage.MainActivity"
    tools:showIn="@layout/activity_main">

    <Button
        android:id="@+id/btnSelect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Image" />

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center" />

    <Button
        android:id="@+id/btnUpload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Upload Image" />

    <TextView
        android:id="@+id/txtStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:text=""
        android:textColor="@android:color/holo_green_light" />

</LinearLayout>

Android Source Code

We will have a separate class for sending image.

Create a class named “UploadImageApacheHttp” and copy the below contents to it.
Before that, download the Base64 file from here which encodeBytes in Base64 Format.
Add it to your project.

UploadImageApacheHttp

package com.coderzheaven.uploadimage;

import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

public class UploadImageApacheHttp {

    public static final String TAG = "Upload Image Apache";

    public void doFileUpload(final String url, final Bitmap bmp, final Handler handler){

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {

                Log.i(TAG, "Starting Upload...");
                final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("image", convertBitmapToString(bmp)));

                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(url);
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    String responseStr = EntityUtils.toString(response.getEntity());
                    Log.i(TAG, "doFileUpload Response : " + responseStr);
                    handler.sendEmptyMessage(1);
                } catch (Exception e) {
                    System.out.println("Error in http connection " + e.toString());
                    handler.sendEmptyMessage(0);
                }
            }
        });
        t.start();

    }

    public String convertBitmapToString(Bitmap bmp){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
        byte[] byte_arr = stream.toByteArray();
        String imageStr = Base64.encodeBytes(byte_arr);
        return imageStr;
    }
}

Now the Activity that implements it.

Note : Make sure you select the image from the Gallery, because this demo is designed for selecting from Gallery.

MainActivity.java

package com.coderzheaven.uploadimage;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "Upload Image";

    // I am using my local server for uploading image, you should replace it with your server address
    public static final String UPLOAD_URL = "http://coderzheaven.com/sample_file_upload/upload_image.php";

    public static final String UPLOAD_KEY = "upload_image";

    private int PICK_IMAGE_REQUEST = 100;

    private Button btnSelect, btnUpload;
    private TextView txtStatus;

    private ImageView imgView;

    private Bitmap bitmap;

    private Uri filePath;

    private String selectedFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        imgView = (ImageView) findViewById(R.id.imgView);
        btnSelect = (Button) findViewById(R.id.btnSelect);
        btnUpload = (Button) findViewById(R.id.btnUpload);
        txtStatus = (TextView) findViewById(R.id.txtStatus);

        btnSelect.setOnClickListener(this);
        btnUpload.setOnClickListener(this);

    }

    Handler handler = handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG, "Handler " + msg.what);
            if (msg.what == 1) {
                txtStatus.setText("Upload Success");
            } else {
                txtStatus.setText("Upload Error");
            }
        }

    };

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            filePath = data.getData();
            selectedFilePath = getPath(filePath);
            Log.i(TAG, " File path : " + selectedFilePath);
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imgView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void uploadImage() {

        UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();
        uploadTask.doFileUpload(UPLOAD_URL, bitmap, handler);

    }

    @Override
    public void onClick(View v) {
        if (v == btnSelect)
            showFileChooser();
        else {
            txtStatus.setText("Uploading Started...");
            uploadImage();
        }
    }
}


Note : You should do networks operations inside a thread only.
AND you cannot modify UI elements inside a UIThread only.

< Upload Image

Add Base64.java to your project

However you can put in your own package but don’t forget to change the package name otherwise you will get error.

Now the server part.

Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.

I am saying the htdocs folder because I am using XAMPP. You change this according to your use.

< ?php
	$base=$_REQUEST['image'];
	 $binary=base64_decode($base);
	header('Content-Type: bitmap; charset=utf-8');
	$file = fopen('uploaded_image.jpg', 'wb');
	fwrite($file, $binary);
	fclose($file);
	echo 'Image upload complete!!, Please check your php file directory……';
?>

Now run your program and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.

If you want to upload another file in your SDCARD you have to change this line to give the exact path

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);

For example if I have to upload a file residing in my SDCARD I would change the path like this.

Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/android.jpg”);

Please send your comments to coderzheaven@gmail.com

You can download the complete Android studio Source Code from here.

Showing Twitter updates on Blogger/Blogspot

Hi,

If you want to show the latest twitter update of yours in your blogger/blogspot, then use the following steps.
1. Go to your blogger ‘Design’
2. Click ‘Add A Gadget’
3. Add ‘HTML/JavaScript’
4. Paste the following JavaScript code into it and save

<div class="twitter-desc">
<ul id="twitter_update_list"><li></li></ul>
<script src="http://twitter.com/javascripts/blogger.js" type="text/javascript"></script>
<script src="http://twitter.com/statuses/user_timeline/SampleURL.json?callback=twitterCallback2&amp;count=1" type="text/javascript"></script>
</div>

5. Done!

Note : Replace ‘SampleURL’ with your twitter id & you can set the number of twitter updates to be shown using the ‘count’, here count is set to 1.

🙂

How to get notified during an incoming call and get that number inside your program in ANDROID?

Hi all…….

In today’s tutorial I will show you how to get the incoming phone number inside your application. In many situation we may need this.
For this we need to have BoradCastReceivers. Inside this class we create an object of the TelephonyManager class ang register with the sytem service.Now we have to make another class which extends PhoneStateListener class which implements the onCallStateChange class which listens to incoming calls.The onReceive method inside the BroadcastReceiver class gets the incoming number from the intent using this line

Bundle bundle = intent.getExtras();
String phone_number = bundle.getString(“incoming_number”);

Note that this program doesnot have an UI ,since it is a service.

Now we go to the code part.
Create a new project and copy this code to it.

package pack.coderzheaven;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class MyBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

	    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
	    MyPhoneStateListener customPhoneListener = new MyPhoneStateListener();

	    telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

	    Bundle bundle = intent.getExtras();
	    String phone_number = bundle.getString("incoming_number");
	    System.out.println("Phone Number : " + phone_number);
	}

}

Now create another class and name it MyPhoneStateListener.java and copy following code to it.

package pack.coderzheaven;

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class MyPhoneStateListener extends PhoneStateListener {

	public void onCallStateChange(int state, String incomingNumber){

	       System.out.println("Icoming Number inside onCallStateChange : "  + incomingNumber);
	        switch(state){
	                case TelephonyManager.CALL_STATE_RINGING:
	                		System.out.println("PHONE RINGING.........TAKE IT.........");
	                        break;
	                case TelephonyManager.CALL_STATE_OFFHOOK:
		                	System.out.println("CALL_STATE_OFFHOOK...........");
		                    break;
	        }
	}
}

Done.
Note that all receivers have to be declared in the androidmanifest file inorder to get events.
So the androidmanifest.xml is given below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">

      <uses-permission android:name="android.permission.RECEIVE_SMS" />
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.WRITE_CONTACTS" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />

      <application android:icon="@drawable/icon" android:label="@string/app_name">
    	        <receiver android:name=".MyBroadcastReceiver">
		        <intent-filter>
		                <action android:name="android.intent.action.PHONE_STATE" />
		        </intent-filter>
		</receiver>
      </application>

</manifest>

Now what you have to do is to simulate a call to your emulator. Check these links for this

1. Simulating a call or SMS in your ANDROID Emulator

2. How to simulate an incoming call to an emulator OR Send an SMS to an emulator in ANDROID ?

Check your console for the output.

Please leave your comments if this post was useful.

How to create a text file in C# ?

Hi,

How can you create a text file in C# and write to it? Sometimes you may need to create a text file using C sharp program. Here is how you can do that.

using System;
using System.IO;

class MainClass
{
  static void Main(string[] args)
  {
    StreamWriter yourStream= null;
    string yourString= "I Love Coderz Heaven!";

    try
    {
      yourStream = File.CreateText("testFile.txt");
      yourStream.Write(yourString);
    }
    catch (IOException e)
    {
      Console.WriteLine(e);
    }
    catch (Exception e)
    {
      Console.WriteLine(e);
    }
    finally
    {
      if (yourStream!= null)
      {
          yourStream.Close();
      }
    }
  }
}

🙂

Android frame Animation

A series of frames is drawn one after the other at regular intervals.
For this create a xml which contains ImageView for showing the animation

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


   <ImageView
      android:id="@+id/Image"
       android:layout_gravity="center_horizontal"
      android:layout_width="wrap_content"
      android:background="@drawable/d1"
      android:layout_height="wrap_content"/>

      <Button
      android:id="@+id/startFAButtonId"
      android:layout_width="wrap_content"
      android:layout_gravity="center_horizontal"
      android:layout_height="wrap_content"
      android:text="Start Animation"
      />
</LinearLayout>

The main java file is

package com.coderzheaven.animation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

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

        Button b = (Button)this.findViewById(R.id.startFAButtonId);
        b.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v)
			{
				animate();
			}
		});

    }
 	   private void animate() {
 	      ImageView imgView = (ImageView)findViewById(R.id.Image);
 	      imgView.setVisibility(ImageView.VISIBLE);
 	      imgView.setBackgroundResource(R.drawable.animation_frame);

 	      AnimationDrawable frameAnimation =  (AnimationDrawable) imgView.getBackground();

 	      if (frameAnimation.isRunning()) {
 	         frameAnimation.stop();
 	      }
 	      else {
 	         frameAnimation.stop();
 	         frameAnimation.start();
 	      }
 	   }
 }

Next the main part, an xml which holds each image and duration in which each image shows.
The xml should be placed inside drawable folder

<?xml version="1.0" encoding="utf-8"?>
<animation-list
	 xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
   <item android:drawable="@drawable/d1" android:duration="50" />
   <item android:drawable="@drawable/d2" android:duration="50" />
   <item android:drawable="@drawable/d3" android:duration="50" />
   <item android:drawable="@drawable/d4" android:duration="50" />
   <item android:drawable="@drawable/d5" android:duration="50" />
</animation-list>

When i click the button the animation will start

A simple exception handling using C#

Hi,

See how a very simple exception handling works with try-catch methods using C#.

using System;

class MainClass{

    public static void Main(){

        int divOne = 0;

        try {
            int ans = 79 / divOne ;
        }

        catch (Exception e) {
            Console.WriteLine("You got the exception-> " + e.Message);
        }

    }
}

Output- “You got the exception-> Attempted to divide by zero.”

🙂

Android dialog with ListView

For implementing a ListView, we first create a xml which contains a ListView named list.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">

  <ListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>

Next we create a Dialog Object and inflate the above xml and when the listItem is clicked then a Alert Dialog windows comes
The java file is listed below


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class DialoglistView extends Activity implements OnItemClickListener{
    /** Called when the activity is first created. */
	String[] val = {"sunday","monday","tuesday","thrusday","friday","wednesday","march"};
	ListView list;
	Dialog listDialog;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         showdialog();
    }

    private void showdialog()
    {
    	listDialog = new Dialog(this);
    	listDialog.setTitle("Select Item");
    	 LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	 View v = li.inflate(R.layout.list, null, false);
    	 listDialog.setContentView(v);
    	 listDialog.setCancelable(true);
         //there are a lot of settings, for dialog, check them all out!

         ListView list1 = (ListView) listDialog.findViewById(R.id.listview);
         list1.setOnItemClickListener(this);
         list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, val));
         //now that the dialog is set up, it's time to show it
         listDialog.show();
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Delete item "+arg2)
		           .setPositiveButton("OK ", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   System.out.println("OK CLICKED");

		           }
		       });
		builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	 dialog.dismiss();
	        	 listDialog.cancel();

	           }
	       });

		AlertDialog alert = builder.create();
		alert.setTitle("Information");
		alert.show();
	}
}

The alert window look like this

When the Item is selected then