Posts Tagged ‘Handhelds’

My this post is based on “How to Integrate printer in android app”. the best way of doing that Google cloud printing. Google provide us Print Dialog code, we can use it in our application. 1)Login with your gamil-id in your desktop and add your printers in your browser. 2)Create a demo app and put below code. 3)Add Internet permissions…

combine

Read More »

Last exercise combine two image side-by-side. In this post, the two images overlap with alpha setting. The layout is same as in last exercise “Combine bitmap side-by-side“. Main code: package com.test.androidimageprocessing; import java.io.FileNotFoundException; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import…

Read More »

google-play-logo11

The Google Play services SDK is an extension to the Android SDK and is available as a downloadable package from the SDK Manager. The download includes the client library and code samples. To develop using the Google Play services APIs, you must download the Google Play services SDK. Google Play services is not supported on the Android emulator, a physical…

Read More »

AndroidDrawBitmap_BlurMaskFilter

This takes a mask, and blurs its edge by the specified radius. Whether or or not to include the original mask, and whether the blur goes outside, inside, or straddles, the original mask’s border, is controlled by the Blur enum. package com.example.androiddrawbitmap; import java.io.FileNotFoundException; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BlurMaskFilter; import android.graphics.Canvas;…

Read More »

 

This sample android program shows you how write and read a file from SD Card in Android. In this program four buttons are shown and a Edit box. When you type some text into the edit box and click, Save to SD Card button, the text is saved to a text file and saved to the SD Card. When you click clear button, the edit box contents are cleared. When you click, Read Sd card button the file is read from the SD card and the contents are copied to the edit box.

The FileDemo2.java file is as follows:

package com.javasamples;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class FileDemo2 extends Activity {
	// GUI controls
	EditText txtData;
	Button btnWriteSDFile;
	Button btnReadSDFile;
	Button btnClearScreen;
	Button btnClose;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
	// bind GUI elements with local controls
	txtData = (EditText) findViewById(R.id.txtData);
	txtData.setHint("Enter some lines of data here...");

	btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
	btnWriteSDFile.setOnClickListener(new OnClickListener() {

	public void onClick(View v) {
		// write on SD card file data in the text box
		try {
			File myFile = new File("/sdcard/mysdfile.txt");
			myFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter = 
									new OutputStreamWriter(fOut);
			myOutWriter.append(txtData.getText());
			myOutWriter.close();
			fOut.close();
			Toast.makeText(getBaseContext(),
					"Done writing SD 'mysdfile.txt'",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}// onClick
	}); // btnWriteSDFile

		btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
		btnReadSDFile.setOnClickListener(new OnClickListener() {

		public void onClick(View v) {
			// write on SD card file data in the text box
		try {
			File myFile = new File("/sdcard/mysdfile.txt");
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(
					new InputStreamReader(fIn));
			String aDataRow = "";
			String aBuffer = "";
			while ((aDataRow = myReader.readLine()) != null) {
				aBuffer += aDataRow + "\n";
			}
			txtData.setText(aBuffer);
			myReader.close();
			Toast.makeText(getBaseContext(),
					"Done reading SD 'mysdfile.txt'",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
		}// onClick
		}); // btnReadSDFile

		btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
		btnClearScreen.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// clear text box
				txtData.setText("");
			}
		}); // btnClearScreen

		btnClose = (Button) findViewById(R.id.btnClose);
		btnClose.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// clear text box
				finish();
			}
		}); // btnClose

	}// onCreate

}// AndSDcard

The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:


<LinearLayout
android:id="@+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>







 

Android invasion, Sydney, Australia

In this article I explain a possible cause of android.os.NetworkOnMainThreadException and how to avoid it.
From the Android site you can read:
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher…

Here is a sample developed for Gingerbread, API level 9:

  1. create an Android project called HttpClient
  2. edit the file AndroidManifest.xml
    1 <?xml version="1.0" encoding="utf-8"?>
    2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3     package="eu.lucazanini.httpclient"
    4     android:versionCode="1"
    5     android:versionName="1.0" >
    6
    7     <uses-sdk android:minSdkVersion="9" />
    8     <uses-permission android:name="android.permission.INTERNET"/>
    9
    10     <application
    11         android:icon="@drawable/ic_launcher"
    12         android:label="@string/app_name" >
    13         <activity
    14             android:name=".HttpClientActivity"
    15             android:label="@string/app_name" >
    16             <intent-filter>
    17                 <action android:name="android.intent.action.MAIN" />
    18
    19                 <category android:name="android.intent.category.LAUNCHER" />
    20             </intent-filter>
    21         </activity>
    22     </application>
    23
    24 </manifest>

    where <uses-sdk android:minSdkVersion=”9″ /> means an API version earlier to Honeycomb (Gingerbread, API level 9), and <uses-permission android:name=”android.permission.INTERNET”/> authorizes the application to perform an internet connection

  3. edit the file HttpClientActivity.java
    1 package eu.lucazanini.httpclient;
    2
    3 import java.io.IOException;
    4
    5 import org.apache.http.HttpResponse;
    6 import org.apache.http.client.ClientProtocolException;
    7 import org.apache.http.client.methods.HttpGet;
    8 import org.apache.http.impl.client.DefaultHttpClient;
    9
    10 import android.app.Activity;
    11 import android.os.Bundle;
    12 import android.util.Log;
    13
    14 public class HttpClientActivity extends Activity {
    15
    16     @Override
    17     public void onCreate(Bundle savedInstanceState) {
    18         super.onCreate(savedInstanceState);
    19         setContentView(R.layout.main);
    20
    21         connect();
    22
    23     }
    24
    25     private void connect() {
    26         try {
    27             DefaultHttpClient client = new DefaultHttpClient();
    28             HttpGet request = new HttpGet("http://www.google.com");
    29             HttpResponse response = client.execute(request);
    30         } catch (ClientProtocolException e) {
    31             Log.d("HTTPCLIENT", e.getLocalizedMessage());
    32         } catch (IOException e) {
    33             Log.d("HTTPCLIENT", e.getLocalizedMessage());
    34         }
    35     }
    36
    37 }

This app is executed without errors.

If you specify an API level after Honeycomb, such as Ice Cream Sandwich, replacing the line <uses-sdk android:minSdkVersion=”9″ /> with <uses-sdk android:minSdkVersion=”14″ /> and you launch the application, you get the exception android.os.NetworkOnMainThreadException.

An easy way to avoid the exception is to insert the following code (which requires import android.os.StrictMode):

1 StrictMode.ThreadPolicy policy = new
2 StrictMode.ThreadPolicy.Builder()
3 .permitAll().build();
4 StrictMode.setThreadPolicy(policy);

before the row connect() in HttpClientActivity.java
But this method is recommended in development environments only, the recommended method is to use the class AsyncTask.

An example is the following in which the code of the class HttpClientActivity.java is replaced by:

1 package eu.lucazanini.httpclient;
2
3 import java.io.IOException;
4
5 import org.apache.http.HttpResponse;
6 import org.apache.http.client.ClientProtocolException;
7 import org.apache.http.client.methods.HttpGet;
8 import org.apache.http.impl.client.DefaultHttpClient;
9
10 import android.app.Activity;
11 import android.os.AsyncTask;
12 import android.os.Bundle;
13 //import android.os.StrictMode;
14 import android.util.Log;
15
16 public class HttpClientActivity extends Activity {
17     /** Called when the activity is first created. */
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22
23 //      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
24 //              .permitAll().build();
25 //      StrictMode.setThreadPolicy(policy);
26
27 //      connect();
28
29         new Connection().execute();
30
31     }
32
33     private class Connection extends AsyncTask {
34
35         @Override
36         protected Object doInBackground(Object... arg0) {
37             connect();
38             return null;
39         }
40
41     }
42
43     private void connect() {
44         try {
45             DefaultHttpClient client = new DefaultHttpClient();
46             HttpGet request = new HttpGet("http://www.google.com");
47             HttpResponse response = client.execute(request);
48         } catch (ClientProtocolException e) {
49             Log.d("HTTPCLIENT", e.getLocalizedMessage());
50         } catch (IOException e) {
51             Log.d("HTTPCLIENT", e.getLocalizedMessage());
52         }
53     }
54
55 }

You can override not only doInBackground but also other methods of the AsyncTask class like OnPreExecute(), OnPostExecute(Result), publishProgress(Progress. ..).

In today’s tutorial I will show you how to open the wifisettings in android programatically.
This code comes handy when the user have not enabled the wifi and you want the user to enable it for your application to work.

Here is the code for that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.coderzheaven;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class OpenWifiSettingsDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button open = (Button)findViewById(R.id.open);
        open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openWifiSettings();
            }
        });
    }
    public void openWifiSettings(){
        final Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
        intent.setComponent(cn);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity( intent);
    }
}

Here is the layout xml– main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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="How to open Wifi Settings Demo"
    />
  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Open Wifi settings"
    android:id="@+id/open"
    />
</LinearLayout>

Wifi settings in android

Enhanced by Zemanta

It’s the simplest form of ListView, extends ListActivity. The list is displayed as a single line of plain text, using the simple Android built-in layout “android.R.layout.simple_list_item_1”.

A simple ListView, extends ListActivity

package com.exercise.AndroidList;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class AndroidList extends ListActivity {
 
 String[] DayOfWeek = {"Sunday", "Monday", "Tuesday",
   "Wednesday", "Thursday", "Friday", "Saturday"
 };
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        setListAdapter(new ArrayAdapter<String>(this, 
          android.R.layout.simple_list_item_1, DayOfWeek));
    }
}

 

 

windows-95-iphone
In this new world of smart phones, 3gs, web 2(3).0, twitter, facebook etc we hardly remember the old legacy softwares that we used in early days of technological evolution of computer world. But people come up with some strange, weird or you can say innovative idea. Like this one; the Developers of iSoft team ran windows 95 on iPhone, its done with help of Bochs emulator and original win 95 image.

Few screen shots below :)

Image Source: Goodiphone

 

Image representing Android as depicted in Crun...

Description:
This example shows you how to download a pdf file from server and display its contents.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it PDFFromServerExample.
2.) Write following code into your manifest file:

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:versionCode=”1″
android:versionName=”1.0″ package=”com.pdftest”>
<uses-sdk android:minSdkVersion=”7″ />
<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”></uses-permission>
<application android:icon=”@drawable/icon” android:label=”@string/app_name” android:debuggable=”true”>
<activity android:name=”.PDFFromServerActivity”
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>

3.) Create Downloader.java file into your package and write following code:

package com.pdftest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader {        public static void DownloadFile(String fileURL, File directory) {
try {

FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod(“GET”);
c.setDoOutput(true);
c.connect();

InputStream in = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

4.) Run for output.

Steps:

1.) Create a project named PDFFromServerExample and set the information as stated in the image.

Build Target: Android 2.2
Application Name: PDFFromServerExample
Package Name: com.pdftest
Activity Name: PDFFromServerExample
Min SDK Version: 8

2.) Open PDFFromServerActivity.java file and write following code there:

package com.pdftest;import java.io.File;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

public class PDFFromServerActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, “pdf”);
folder.mkdir();
File file = new File(folder, “Read.pdf”);
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile(“http://www.nmu.ac.in/ejournals/aspx/courselist.pdf&#8221;, file);

showPdf();
}
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+”/pdf/Read.pdf”);
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType(“application/pdf”);
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, “application/pdf”);
startActivity(intent);
}
}

3.) Compile and build the project.

Output