Monthly Archives: June 2012

Creating a custom Sliding GalleryView with Paging in android

This is a simple example showing A sliding Gallery in android. This example shows a sliding gallery with a paging Control and a changing page text which also indicate the page change.

Create a new project named “SlidingGallery” and copy this code into “SlidingGalleryDemo.java“.
My Activity name is “SlidingGalleryDemo.java” here.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SlidingGalleryDemo extends Activity {
	
	Gallery ga;
	int width, height;
	LinearLayout linear;
	LinearLayout layout;
	Integer[] pics = {
			R.drawable.android_1,
			R.drawable.android_2,
    		R.drawable.android_3,
    		R.drawable.android_4,
    		R.drawable.android_5   
    };
	ImageView paging;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
	     setContentView(R.layout.threemenu);
	     
	     layout = (LinearLayout) findViewById(R.id.imageLayout1);
	        
	     DisplayMetrics displaymetrics = new DisplayMetrics();
	     getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	     width = displaymetrics.heightPixels;
	     height = displaymetrics.widthPixels;
			
	     for(int i=0; i<pics.length; i++)
         {
          	paging = new ImageView(this);
        	paging.setId(i);
        	paging.setBackgroundResource(R.drawable.unsel);
        	layout.addView(paging);
         }
	     
	     ga = (Gallery)findViewById(R.id.thisgallery);
	     ga.setAdapter(new ImageAdapter(this));
	     
	     ga.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
				{					
					System.out.println("SELECTED : " + arg2);
				}	        	
	        });
    }

    public class ImageAdapter extends BaseAdapter {

    	private Context ctx;
    	int imageBackground;
    	int pre=-1;
    	public ImageAdapter(Context c) {
			ctx = c;
		}

		public int getCount() {
    		
    		return pics.length;
    	}

    	public View getView(int arg0, View convertView, ViewGroup arg2) {

		     ImageView iv;
		     LinearLayout layoutnew = new LinearLayout(getApplicationContext());            
		     layoutnew.setOrientation(LinearLayout.VERTICAL);
		        
             if (convertView == null) 
             {
            	iv = new ImageView(ctx);
            	iv.setImageResource(pics[arg0]);
     			iv.setScaleType(ImageView.ScaleType.FIT_XY);
     			int temp =(int) (height/1.7f);
     			int temp_y = (int) ((3*temp)/2.0f);
     			iv.setLayoutParams(new Gallery.LayoutParams(temp,temp_y));
     			iv.setBackgroundResource(imageBackground);
             }
             else
             {
            	iv = (ImageView) convertView;
             }
             TextView tv = new TextView(ctx);
 			 tv.setText("Page " + (arg0+1));
 			 tv.setTextColor(0xFFFFFFFF);
 			 tv.setPadding(0, 15, 0, 0);
 		     tv.setTextSize(18);
 			 tv.setGravity(Gravity.CENTER); 
			 layoutnew.addView(iv);
			 layoutnew.addView(tv);
    		
    		return layoutnew;
    	}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			if(pre !=-1)
    		{
    			ImageView img = (ImageView) findViewById(pre);
    			img.setBackgroundResource(R.drawable.unsel);
    		}
    		ImageView img1 = (ImageView) findViewById(position);
    		img1.setBackgroundResource(R.drawable.sel);
    		this.pre = position;
    		return position;
		}
    }
}

Now create a new class and name it “GalleryCustom.java” which extends “Gallery” and copy this code into it.

package com.coderzheaven.pack;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;

public class GalleryCustom extends Gallery {

    public GalleryCustom(Context ctx, AttributeSet attrSet) 
    {
        super(ctx,attrSet);
    }

    @SuppressWarnings("unused")
	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2)
    { 
           return e2.getX() > e1.getX(); 
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
      return true;  
    }
}

Now we will create the layout for the page. Copy this code to the main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true"  
    android:background="@drawable/Hotpink">
    
    <LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout1"
	    android:layout_marginBottom="5dip"
	    android:layout_alignParentBottom="true"
	    android:gravity="center_horizontal|center_vertical"
	    android:orientation="horizontal"
	    android:layout_height="wrap_content">  
	 </LinearLayout>
	 
	<LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout"
	    android:gravity="center"
	    android:layout_alignParentTop="true"
	    android:layout_above="@+id/imageLayout"
	    android:layout_height="fill_parent" >
    
		<com.coderzheaven.pack.GalleryCustom
		    android:id="@+id/thisgallery"
		    android:spacing="60dip"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content" />
		    
    </LinearLayout>
    
</RelativeLayout>

OK Its done. Now run the project and see the result.

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Please comment and share this post if you like it.

How to delete a contact in android?

Hello all previously I have shown how to list all contacts in your phone and in another post I showed how to programatically create a contact in android.
In today’s tutorial I will show you how to delete a contact in android programatically.

This simple code does that.

 public static boolean deleteContact(Context ctx, String phone, String name) {
        Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
        try {
            if (cur.moveToFirst()) {
                do {
                    if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
                        String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                        ctx.getContentResolver().delete(uri, null, null);
                        return true;
                    }

                } while (cur.moveToNext());
            }

        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return false;
    }

Microsoft Introduces Surface – May be an iPad Killer.

when Microsoft unveiled the Surface tablet (actually a pair of them) Monday, the software company clearly had one ultimate goal: to make a tablet that’s better than the iPad.

Unlike some hasty competitors, Microsoft took its time getting into the tablet game. Earlier this year, the company rolled out the Windows 8 operating system, software that is optimized for mobile and that manufacturers such as Samsung and Asus are already building tablets around. But Microsoft clearly wanted to control at least one version of the hardware, a move it has largely shied away from during its history.

Check out the Microsoft Surface Review here..

http://www.techradar.com/reviews/pc-mac/tablets/microsoft-surface-tablet-1085839/review

Microsoft Surface

See it in action at surface.com

How to add a new contact programmatically in android?

We all know how to add a new contact to our android devices without programming right.
OK that’s a normal man’s use.
But what from a programmer’s view.

This is the sample java code that helps you to add contact programatically.

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Contacts.People;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.Toast;

public class AddContactDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addContact("Coderz","1234567890");
        addContact("James","5656215521");
        addContact("John","4545454545");
        addContact("Mary","9632587410");
        addContact("Peter","4561237890");
    }
   private void addContact(String name, String phone) {
        ContentValues values = new ContentValues();
        values.put(People.NUMBER, phone);
        values.put(People.TYPE, Phone.TYPE_CUSTOM);
        values.put(People.LABEL, name);
        values.put(People.NAME, name);
        Uri dataUri = getContentResolver().insert(People.CONTENT_URI, values);
        Uri updateUri = Uri.withAppendedPath(dataUri, People.Phones.CONTENT_DIRECTORY);
        values.clear();
        values.put(People.Phones.TYPE, People.TYPE_MOBILE);
        values.put(People.NUMBER, phone);
        updateUri = getContentResolver().insert(updateUri, values);
      }
}

After running this programs please switch to contacts application on your device to see the result.

Add Contacts

Please leave your comments and also share it if you like it.

Placing Controls in a Widget in Android and Listening to the events from them.

Hello everyone..

I have already shown how to create a simple widget and add it to the home screen in my previous posts. If you have missed these posts please check it here.

How to create a widget in android?

In the next post I showed you how to listen to a widget delete action and delete the widget.

Now in today’s tutorial I am going to show how to place controls like buttons inside the widget and listen to their events and respond to it.

I am proceeding the same as the previous tutorials.

First I will create a new project named “ControlsInWidget” and name the activity “MyActivity.java”.

Now we will create a layout for this main activity. settings.xml

These are the contents of settings.xml

<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:id="@+id/tv1"
	android:text="CoderzHeaven Widget Settings Activity"
	android:textColor="@android:color/white"
	android:textSize="15dip"
	android:textStyle="bold"
	android:layout_marginTop="5dip"/>
</TableLayout>

This is the MyActivity. java that uses “settings.xml”

package com.coderzheaven.widgetpack;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
	}	
}

Now we will create the class for the widget which is named “MyWidget.java”.
please follow the instructions in the link while creating this class for the widget.

How to create a widget in android?

Now replace the contents inside MyWidget.java with this one.

package com.coderzheaven.widgetpack;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class MyWidget extends AppWidgetProvider {
	
	public static String WIDGET_SETTINGS_ACTION = "SettingsForWidget";
	public static String WIDGET_RECEIVER_ACTION = "WidgetActionReceiver";
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
		Log.d("DEBUG","onUpdate");
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		Intent configIntent = new Intent(context, MyActivity.class);
		configIntent.setAction(WIDGET_SETTINGS_ACTION);
		Intent active = new Intent(context, MyWidget.class);
		active.setAction(WIDGET_RECEIVER_ACTION);
		active.putExtra("Message", "Message for Button 1");
		PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
		PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
		remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(
			AppWidgetManager.EXTRA_APPWIDGET_ID,
			AppWidgetManager.INVALID_APPWIDGET_ID);
		if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
			this.onDeleted(context, new int[] { appWidgetId });
			}
		} else {
		// check, if our Action was called
		if (intent.getAction().equals(WIDGET_RECEIVER_ACTION)) {
			String msg = "";
			try {
				msg = intent.getStringExtra("Message");
			} catch (NullPointerException e) {
				Log.e("Error", "No Message");
			}
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
			NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification noty = new Notification(R.drawable.icon, "Button in the Widget Clicked.",System.currentTimeMillis());
			noty.setLatestEventInfo(context, "Notification from Widget", msg, contentIntent);
			notificationManager.notify(1, noty);
		}
		super.onReceive(context, intent);
		}
	}
}

Here we have two actions “WIDGET_SETTINGS_ACTION” and “WIDGET_RECEIVER_ACTION” which will be set as action for the two buttons inside the widget.

Now here is the main.xml which is the layout for the widget that contains the controls.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:orientation="horizontal"
	android:background="@drawable/yellow_bkg"
	android:layout_gravity="center"
	android:layout_height="wrap_content">
<Button 
	android:text="Button1" 
	android:id="@+id/button_one"
	android:layout_weight="1"
	android:layout_gravity="center_horizontal|center"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"/>
<Button 
	android:text="Button2" 
	android:id="@+id/button_two"
	android:layout_weight="1"
	android:layout_gravity="center_horizontal|center"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"/>
</LinearLayout>

Widget

If you want the time to be updated every second, your have to modify simple_widget.xml
file and set updatePerdiodMillis to 1000.
The android update 1.6 unfortunately does not support any update periode that is less then 30
minutes.

Please go through this tutorial for setting up the xml for the widget.

How to create a widget in android?

Inside the onReceive we are checking this to ensure which button is clicked. You can write anything inside this function – like a http call or something to update the widget.

if (intent.getAction().equals(WIDGET_RECEIVER_ACTION)) {

}

The second button in the widget launches the activity “MyActivity” and the first one send a notification and doesn’t have a user interface.

Widget

Widget

Widget

You can download the complete eclipse java android source code from here.

Please leave your comments on this post and also share it and like it if this post was useful.

iOS 6 Has Been Jailbroken

That didn’t take very long. Just three days after being announced, iOS 6 has been, as the cool kids say, pwned by the Dev-Team with Redsn0W 0.9.13dev1. As hinted earlier this week the jailbreak doesn’t work with the iPhone 4S, but only the iPhone 4, iPod touch 4G, and the iPhone 3GS. There are some downsides to the jailbreak, but this news should be music to developer’s ears.

More news from here…

http://techcrunch.com/2012/06/14/ios-6-has-been-jailbroken/

Android hits 900k activations per day

The Google Android Army is coming again…

Google’s Android platform sees 900,000 activations a day, according to a tweet from Android head Andy Rubin. The statistic, of course, doesn’t distinguish between smartphones and tablets, so it’s hard to get a clear picture of the Android ecosystem.

Google Android

See more about this new from here.

http://www.washingtonpost.com/business/technology/android-hits-900k-activations-per-day/2012/06/11/gJQA1tlfUV_story.html

How to get Notified when a widget is deleted?

I have already covered a tutorial on how to start with widgets and how to create a simple widget here..

http://www.coderzheaven.com/2012/06/07/create-widget-android/

Today I will show you how to get notified when a widget is deleted.

if you have already gone through my previous post, then there is only a small change in the “MyWidget.java” file.

we have to add the onReceive() method to the class like this.

package com.coderzheaven.pack;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyWidget extends AppWidgetProvider {
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
	}
	@Override
	public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
				final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
																AppWidgetManager.INVALID_APPWIDGET_ID);
				if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
					this.onDeleted(context, new int[] { appWidgetId });
				}
				Toast.makeText(context, "Widget deleted", Toast.LENGTH_LONG).show();
			} else {
				super.onReceive(context, intent);
			}
			
	}
}

onReceive is always called before onUpdate is called. This code snipped checks the called action
and decides wheather to just run the receive method or the delete method.

I have already shown how to add a widget to the home screen, now for deleting simply press and hold the widget and drag to the delete icon on the bottom of the screen.

When you do this the onReceive() method will be called and a toast will appear saying “Widget Deleted”.

Widgets Android

You can download the complete android source code of the above post from here.

Please leave your valuable comments on this post.

Phone storage is getting low problem solved OR How to install apps on the SDCARD by default in your android device?

Often our android phones may get warning that “Phone storage is getting low” because your apps dont have space to be installed on the phone.
I too had this problem. Then I found out the answer, after doing this all apps installed will go to the sdcard.

First you have to enable USB debugging on your Android device
For that Go to

Settings > Applications > Development > USB debugging.

Note : These are only for “Froyo” Devices

Now you need to download and install the Android SDK on your computer from http://developer.android.com/sdk/. Once you’ve downloaded and extracted the package to the folder of your choice, Click and run SDK Setup.exe and click on Available Packages to the left. If you get an error message at this point, enable “Force https://…” in the Settings. From the list of available packages, select “Usb Driver package”, click on the Install Selected button in the bottom right corner and follow the prompts.
Connect your phone to your computer with a USB-cable. Your OS will prompt you to install new drivers. Choose to install them from the android-sdk/usb_driver folder. Do not mount your device; you only need to plug-in the cable.
Next, if you are on windows open the command prompt by opening the run console and typing cmd.

Navigate to the Android-SDK\tools folder.

In the Android-SDK\tools folder, type in

adb devices

and it should detect your connected device.

All you have to do next is entering

adb shell pm setInstallLocation 2.

and , you’re done! Android will now install apps to the SD card by default.

To switch back to storing software on the internal memory, enter

adb shell pm setInstallLocation 0.

See the screenshot.

Install on SDCARD by default in android device.

How to create a widget in android?

Hello everyone…

Today I will show you how to create a simple widget in android?

First create a new project and name it “Widget1” and name the activity “WidgetDemo1“.
Actually we dont need the activity class here. You can delete it and delete the corresponding entry of it from the AndroidManifest file also.

Now we will make the layout for the widget.

We will make the layout to be the main.xml.
So modify the contents of 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:orientation="vertical"
	android:background="@drawable/yellow_bkg"
	android:layout_gravity="center"
	android:layout_height="wrap_content">
<TextView android:id="@+id/widget_textview"
	android:text="Hello CoderzHeaven"
	android:layout_height="wrap_content"
	android:layout_width="wrap_content"
	android:layout_gravity="center"
	android:layout_margin="5dip"
	android:padding="10dip"
	android:textColor="@android:color/black"/>
</LinearLayout>

Now you may have some errors like resource not found etc.

So now create an xml inside res/drawable folder and name it “yellow_bkg.xml” and copy this code into it.

This will be the background for our widget. However you can have your own background.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#f3ae1b" />
            <stroke
                android:width="1dp"
                android:color="#bb6008" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#f3ae1b"
                android:endColor="#bb6008"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#bb6008" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Now modify the AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- This part is for the Widget -->
        <receiver android:name=".MyWidget" android:label="@string/app_name">
			<intent-filter>
			<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
			</intent-filter>
			<meta-data android:name="android.appwidget.provider"
			android:resource="@xml/simple_widget" />
		</receiver>
    </application>
</manifest> 

The meta-tag tells android about your widget provider. In this case, the widget provider is located at
res/xml/simple_widget.xml. The provider.xml is pretty much self explaining:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider 
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:minWidth="150dip"
	android:minHeight="70dip"
	android:updatePeriodMillis="10000"
	android:initialLayout="@layout/main"
/>

updatePerdiodMillis is the time in milliseconds to update your widget. In our
case, this is unimportant and we don’t need it because we don’t do any update on our widget.

Now create a new class and name it “MyWidget” and set AppWidgetProvider as super class.
Look at the screenshot.

Widget 1

MyWidget.java will look like this.

package com.coderzheaven.pack;

import android.appwidget.AppWidgetProvider;

public class MyWidget extends AppWidgetProvider {

}

These are the contents of strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, WidgetDemo!</string>
    <string name="app_name">Simple Widget</string>
</resources>

Now we have created the widget and you can now run the application.

Widget 1

Widget 1

Widget 1

Please comment if this post was useful.
please share it so that it can be useful to others.

How to upload files to server using the new FileUpload control in C#/C-Sharp ?

Hi,

For uploading files to server using the new FileUpload control in C#,


<%@ Page Language="C#"%>

<script runat="server">
 protected void Button1_Click(object sender, EventArgs e)
 {
 if (FileUpload1.HasFile)
 try {
 FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
 Label1.Text = "File name: " +
 FileUpload1.PostedFile.FileName + "<br>" +
 FileUpload1.PostedFile.ContentLength + " kb<br>" +
 "Content type: " +
 FileUpload1.PostedFile.ContentType;
 }
 catch (Exception ex) {
 Label1.Text = "ERROR: " + ex.Message.ToString();
 }
 else
 {
 Label1.Text = "You have not specified a file.";
 }
 }
</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
 <title>FileUpload Server Control</title>
</head>
<body>
 <form id="form1" runat="server">
 <asp:FileUpload ID="FileUpload1" Runat="server" />

 <asp:Button ID="Button1" Runat="server" Text="Upload"
 OnClick="Button1_Click" />

 <asp:Label ID="Label1" Runat="server"></asp:Label>
 </form>
</body>
</html>

Uploading Files to Server in C#/C-Sharp

Hi,

For uploading files to server in C#/C Sharp,


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UploadFile" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:FileUpload ID="Uploader" runat="server" Height="24px" Width="472px" />&nbsp;
 <asp:Button ID="cmdUpload" runat="server" Height="24px" OnClick="cmdUpload_Click"
 Text="Upload" Width="88px" /><br />
 <br />
 <asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-Bold="True"></asp:Label></div>
 </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class UploadFile : System.Web.UI.Page
{
 private string uploadDirectory;
 protected void Page_Load(object sender, EventArgs e)
 {
 uploadDirectory = Path.Combine(Request.PhysicalApplicationPath, "Uploads");
 }

protected void cmdUpload_Click(object sender, EventArgs e)
 {
 if (Uploader.PostedFile.FileName == "")
 {
 lblInfo.Text = "No file specified.";
 }
 else
 {
 string extension = Path.GetExtension(Uploader.PostedFile.FileName);
 switch (extension.ToLower())
 {
 case ".png":
 case ".jpg":
 break;
 default:
 lblInfo.Text = "This file type is not allowed.";
 return;
 }
 string serverFileName = Path.GetFileName(Uploader.PostedFile.FileName);
 string fullUploadPath = Path.Combine(uploadDirectory,serverFileName);

try
 {
 Uploader.PostedFile.SaveAs(fullUploadPath);

lblInfo.Text = "File " + serverFileName;
 lblInfo.Text += " uploaded successfully to ";
 lblInfo.Text += fullUploadPath;
 }
 catch (Exception err)
 {
 lblInfo.Text = err.Message;
 }
 }
 }
}

CoderzHeaven on Facebook, New Fan Page

Hai Friends..

PLease find us on Facebook for more updates.

This is our new Fab page Url.

http://www.facebook.com/CoderzHeavenFans

By adding us on Facebook, you can get access to our new updates fast and get answers to your questions quickly.

So please add us on Facebook.

Please find us on Twitter also.

https://twitter.com/coderzheaven

How to Check whether is GPS is enabled in your android device?

This simple code checks whether GPS in enabled in your android device or not.
If the GPS is not enabled the user is redirected to the settings page.

  LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER); 

        // Check if enabled and if not send user to the GPS settings
        if (!enabled) {
        	Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        	startActivity(intent);
        }

Turn off the GPS on your device and running it will display this screen.

Please test GPS on the device because emulators don’t have GPS. But anyway you can simulate Longitude and Latitude which I will show in the coming posts.

GPS

How to override hardware Home button in android? OR How to listen to home button click in android?

Hello everyone…

In this post I will show you how to listen to hardware button in an android smartphone.

This post especially shows how to listen to the home button in android. But my advice is never override the home button in your app.
Home button is to move the currently running process to background. But you can override the Backbutton and other buttons, android allows that on the keyDown Method. But if you try to match the “Home” button in the keyDown method it will not work. For that we have to follow another way which is shown in this post.

This simple java code handles the button pressed.

package test.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;

public class Test2Activity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_HOME)) {
        	System.out.println("KEYCODE_HOME");
        	showDialog("'HOME'");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	System.out.println("KEYCODE_BACK");
        	showDialog("'BACK'");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
        	System.out.println("KEYCODE_MENU");
        	showDialog("'MENU'");
            return true;
        }
        return false;
    }
    
    void showDialog(String the_key){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?")
    		  .setCancelable(true)
    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   dialog.cancel();
    	        	   finish();
    	           }
    	       })
    	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.setTitle("CoderzHeaven.");
    	alert.show();
    }
    
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
    }
    
    public void onUserLeaveHint() { // this only executes when Home is selected.
    	// do stuff
    	super.onUserLeaveHint();
    	System.out.println("HOMEEEEEEEEE");
    }
}

When “onUserLeaveHint()” function is defined you can actually listen to the home button press and do some saving of data or something.

 public void onUserLeaveHint() { // this only executes when Home is selected.
    	// do stuff
    	super.onUserLeaveHint();
    	System.out.println("HOMEEEEEEEEE");
    }

Home button override

Home button override

Home button override

Please leave your comments on this post and share it on the social Networks.

WaterProof, DustProof and scratch resistant Smartphones arriving in the market – Xperia Go and Xperia Acro S

Sony has introduced two new durable and waterproof handsets. For once, rugged doesn’t equate with bad design. The two Android-powered handsets are svelte and streamlined but feature extra protection like scratch-resistant displays and wet finger tracking.

Sony announces Xperia S, Xeria P, Xperia U and Xperia Sola in India
Sony Xperia U goes on sale online
scratch-resistant displays and wet finger tracking.

Xperia Go Specifications

Xperia Go

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 900 / 2100 – ST27i
HSDPA 850 / 1900 / 2100 – ST27a
Announced 2012, May
Status Coming soon. Exp. release 2012, Q3
BODY Dimensions 111 x 60.3 x 9.8 mm
Weight 110 g
– Touch-sensitive controls
DISPLAY Type LED-backlit LCD, capacitive touchscreen, 16M colors
Size 320 x 480 pixels, 3.5 inches (~165 ppi pixel density)
Multitouch Yes, up to 4 fingers
Protection Scratch-resistant glass
– Sony Mobile BRAVIA Engine
– IP67 certified – dust and water proof (up to 1m for 30 mins)
SOUND Alert types Vibration; MP3 ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot microSD, up to 32 GB
Internal 8 GB storage (4 GB user available), 512 MB RAM
DATA GPRS Up to 107 kbps
EDGE Up to 296 kbps
Speed HSDPA, 14.4 Mbps; HSUPA, 5.76 Mbps
WLAN Wi-Fi 802.11 b/g/n, Wi-Fi Direct, DLNA, Wi-Fi hotspot
Bluetooth Yes, v3.0 with A2DP, EDR
USB Yes, microUSB v2.0, USB On-the-go support
CAMERA Primary 5 MP, 2592 x 1944 pixels, autofocus, LED flash
Features Geo-tagging, touch focus, face and smile detection, 3D sweep panorama
Video Yes, 720p@30fps, continuous autofocus, video light, video stabilizer
Secondary No
FEATURES OS Android OS, v2.3 (Gingerbread), planned upgrade to v4.0
Chipset NovaThor U8500
CPU Dual-core 1 GHz Cortex-A9
GPU Mali-400
Sensors Accelerometer, proximity, compass
Messaging SMS(threaded view), MMS, Email, Push Email, IM
Browser HTML5, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors White, Black, Yellow
– SNS integration
– MP4/H.263/H.264/WMV player
– MP3/eAAC+/WMA/WAV player
– TrackID music recognition
– Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk
– Document viewer
– Voice memo/dial/commands
– Predictive text input

Xperia Acro Specifications

Xperia Acro

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 850 / 900 / 1900 / 2100
Announced 2012, May
Status Coming soon. Exp. release 2012, Q3
BODY Dimensions 126 x 66 x 11.9 mm
Weight 147 g
– Touch-sensitive controls
DISPLAY Type LED-backlit LCD, capacitive touchscreen, 16M colors
Size 720 x 1280 pixels, 4.3 inches (~342 ppi pixel density)
Multitouch Yes, up to 10 fingers
Protection Scratch-resistant shatter proof glass
– Sony Mobile BRAVIA Engine
– IP67 certified – dust and water proof (up to 1m for 30 mins)
SOUND Alert types Vibration; MP3 ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot microSD, up to 32 GB
Internal 16 GB storage (11 GB user available), 1 GB RAM
DATA GPRS Up to 86 kbps
EDGE Up to 237 kbps
Speed HSDPA, 14.4 Mbps; HSUPA, 5.8 Mbps
WLAN Wi-Fi 802.11 b/g/n, Wi-Fi Direct, DLNA, Wi-Fi hotspot
Bluetooth Yes, v3.0 with A2DP, EDR
NFC Yes
USB Yes, microUSB v2.0, USB On-the-go support
CAMERA Primary 12 MP, 4000×3000 pixels, autofocus, LED flash
Features Geo-tagging, touch focus, face and smile detection, 3D sweep panorama, image stabilization
Video Yes, 1080p@30fps, continuous autofocus, video light, video stabilizer
Secondary Yes, 1.3 MP, 720p@30fps
FEATURES OS Android OS, v4.0 (Ice Cream Sandwich)
Chipset Qualcomm MSM8260 Snapdragon
CPU Dual-core 1.5 GHz Scorpion
GPU Adreno 220
Sensors Accelerometer, gyro, proximity, compass
Messaging SMS (threaded view), MMS, Email, IM, Push Email
Browser HTML5, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support and GLONASS
Java Yes, via Java MIDP emulator
Colors White, Black, Pink
– SNS integration
– HDMI port
– Active noise cancellation with dedicated mic
– MP4/H.263/H.264/WMV player
– MP3/eAAC+/WMA/WAV player
– TrackID music recognition
– Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk
– Document viewer
– Voice memo/dial/commands
– Predictive text input

Check this link for the official ad.

http://www.hindustantimes.com/technology/PersonalTech-Updates/Sony-Xperia-go-Xperia-acro-S-waterproof-phones-hit-markets/SP-Article1-864267.aspx