Showing posts with label Android Applications. Show all posts
Showing posts with label Android Applications. Show all posts

Thursday, 3 October 2013

Data Sharing between Android Applications

// siddhu vydyabhushana // 6 comments
In this tutorial I'm going to illustrate how we can share data between two Android applications using Shared Preference.
To implement this I used two Android applications. One is "Datawriter" and the other one is "Datareader".
"Datawriter" is to update shared data. Its' package name is com.writer.data class name is DataWriterActivity . Here is the code for DataWriterActivity class.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.writer.data;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
public class DataWriterActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dataWriter();
    }
     
    public void dataWriter(){
        String strShareValue = "Hello! this is shared data";
        SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("demostring", strShareValue);
        editor.commit();
    }
}

dataWriter method will write the string Hello! this is shared data to a shared memory.

Next application is to read shared data. The application name is  Datareader and its' package name is com.datareader class name is DataReaderActivity. Here is the code for DataReaderActivity class.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.datareader;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class DataReaderActivity extends Activity {
 String dataShared;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         dataRead();
         TextView tv = (TextView)findViewById(R.id.textView1);
         tv.setText(dataShared);
         
    }
     
    public void dataRead(){
      Context con;
         try {
             con = createPackageContext("com.writer.data", 0);
             SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
             dataShared = pref.getString("demostring", "No Value");
         }
         catch (NameNotFoundException e) {
             Log.e("Not data shared", e.toString());
         }
    }
}

"com.writer.data" in the highlighted line is the package name of the first application which we used to share data.
Following is the out put of second application :

Data Sharing between android application
Read More

Load Image from URL in Android

// siddhu vydyabhushana // 10 comments
Once I needed to display an image loading from URL in my Android application. After referring some resources I was success. Here I post what I did. This is for future references. I did this for Android 2.2 platform.

This Android application load an image from a server using HttpURLConnection and show it in image view when you click load image button.
(I have used  image located here http://www.codeincloud.tk/play.png)


Here is the layout file.

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

    <Button
        android:id="@+id/btn_imgload"
        android:layout_width="208dp"
        android:layout_height="wrap_content"
        android:layout_x="57dp"
        android:layout_y="322dp"
        android:text="Load Image" />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_x="131dp"
        android:layout_y="179dp" />

</AbsoluteLayout>

This is the java code

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class LoadImageActivity extends Activity {
 
 ImageView image_view;
 Button btnLoadImg ;
    final static String imageLocation="http://www.codeincloud.tk/play.png"; //Use any image location. 
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        image_view = (ImageView)findViewById(R.id.imageview);
        btnLoadImg = (Button)findViewById(R.id.btn_imgload);
        
        btnLoadImg.setOnClickListener(loadImage);
    }
    
    
    View.OnClickListener loadImage = new View.OnClickListener(){
     public void onClick(View view) {
         loadImage(imageLocation);
            }
     };
    
     Bitmap bitmap;
    void loadImage(String image_location){
      
          URL imageURL = null;
          
          try {
           imageURL = new URL(image_location);
           } 
          
          catch (MalformedURLException e) {
              e.printStackTrace();
           }
          
          try {
           HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
           connection.setDoInput(true);
           connection.connect();
              InputStream inputStream = connection.getInputStream();
               
              bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
              image_view.setImageBitmap(bitmap);
          }
          catch (IOException e) {
              
               e.printStackTrace();
          }
    }
  }

Add internet permission to Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tutorial.imageload"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".LoadImageActivity"
            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>
Read More

Wednesday, 2 October 2013

Android : how to check if device has camera

// siddhu vydyabhushana // 6 comments
In Android, you can use PackageManager , hasSystemFeature() method to check if a device has camera, gps or other features.
See full example of using PackageManager in an activity class.
package com.mkyong.android;
 
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
 
public class FlashLightActivity extends Activity {
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.main);
 
		Context context = this;
		PackageManager packageManager = context.getPackageManager();
 
		// if device support camera?
		if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			//yes
			Log.i("camera", "This device has camera!");
		}else{
			//no
			Log.i("camera", "This device has no camera!");
		}
 
 
	}
}
Read More

How to Send SMS Message Android

// siddhu vydyabhushana // 7 comments
n Android, you can use SmsManager API or device’s Built-in SMS application to send a SMS message. In this tutorial, we show you two basic examples to send SMS message :
  1. SmsManager API
    	SmsManager smsManager = SmsManager.getDefault();
    	smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
  2. Built-in SMS application
    	Intent sendIntent = new Intent(Intent.ACTION_VIEW);
    	sendIntent.putExtra("sms_body", "default content"); 
    	sendIntent.setType("vnd.android-dir/mms-sms");
    	startActivity(sendIntent);
Of course, both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />
P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Note
The Built-in SMS application solution is the easiest way, because you let device handle everything for you.

1. SmsManager Example

Android layout file to textboxes (phone no, sms message) and button to send the SMS message.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:phoneNumber="true" >
    </EditText>
 
    <TextView
        android:id="@+id/textViewSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:lines="5"
        android:gravity="top" />
 
    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />
 
</LinearLayout>
File : SendSMSActivity.java – Activity to send SMS via SmsManager.
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class SendSMSActivity extends Activity {
 
	Button buttonSend;
	EditText textPhoneNo;
	EditText textSMS;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		buttonSend = (Button) findViewById(R.id.buttonSend);
		textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
		textSMS = (EditText) findViewById(R.id.editTextSMS);
 
		buttonSend.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View v) {
 
			  String phoneNo = textPhoneNo.getText().toString();
			  String sms = textSMS.getText().toString();
 
			  try {
				SmsManager smsManager = SmsManager.getDefault();
				smsManager.sendTextMessage(phoneNo, null, sms, null, null);
				Toast.makeText(getApplicationContext(), "SMS Sent!",
							Toast.LENGTH_LONG).show();
			  } catch (Exception e) {
				Toast.makeText(getApplicationContext(),
					"SMS faild, please try again later!",
					Toast.LENGTH_LONG).show();
				e.printStackTrace();
			  }
 
			}
		});
	}
}
File : AndroidManifest.xml , need SEND_SMS permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="10" />
 
    <uses-permission android:name="android.permission.SEND_SMS" />
 
    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SendSMSActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
See demo :

2. Built-in SMS application Example

This example is using the device’s build-in SMS application to send out the SMS message.
File : res/layout/main.xml – A button only.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />
 
</LinearLayout>
File : SendSMSActivity.java – Activity class to use build-in SMS intent to send out the SMS message.
package com.mkyong.android;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
 
public class SendSMSActivity extends Activity {
 
	Button buttonSend;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		buttonSend = (Button) findViewById(R.id.buttonSend);
 
		buttonSend.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View v) {
 
				try {
 
				     Intent sendIntent = new Intent(Intent.ACTION_VIEW);
				     sendIntent.putExtra("sms_body", "default content"); 
				     sendIntent.setType("vnd.android-dir/mms-sms");
				     startActivity(sendIntent);
 
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(),
						"SMS faild, please try again later!",
						Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}
		});
	}
}
See demo :
send sms via build-in sms application
send sms via build-in sms application

Download Source Code

Download it – 1. Android-Send-SMS-Example.zip (16 KB)
send sms message via smsmanager
Read More

How to send email in android

// siddhu vydyabhushana // 4 comments
In Android, you can use Intent.ACTION_SEND to call an existing email client to send an Email.
See following code snippets :
	Intent email = new Intent(Intent.ACTION_SEND);
	email.putExtra(Intent.EXTRA_EMAIL, new String[]{"youremail@yahoo.com"});		  
	email.putExtra(Intent.EXTRA_SUBJECT, "subject");
	email.putExtra(Intent.EXTRA_TEXT, "message");
	email.setType("message/rfc822");
	startActivity(Intent.createChooser(email, "Choose an Email client :"));
P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Run & test on real device only.
If you run this on emulator, you will hit error message : “No application can perform this action“. This code only work on real device.

1. Android Layout

File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="To : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" >
 
        <requestFocus />
 
    </EditText>
 
    <TextView
        android:id="@+id/textViewSubject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subject : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextSubject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         >
    </EditText>
 
    <TextView
        android:id="@+id/textViewMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:lines="5" />
 
    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />
 
</LinearLayout>

2. Activity

Full activity class to send an Email. Read the onClick() method, it should be self-explanatory.
package com.mkyong.android;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 
public class SendEmailActivity extends Activity {
 
	Button buttonSend;
	EditText textTo;
	EditText textSubject;
	EditText textMessage;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		buttonSend = (Button) findViewById(R.id.buttonSend);
		textTo = (EditText) findViewById(R.id.editTextTo);
		textSubject = (EditText) findViewById(R.id.editTextSubject);
		textMessage = (EditText) findViewById(R.id.editTextMessage);
 
		buttonSend.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View v) {
 
			  String to = textTo.getText().toString();
			  String subject = textSubject.getText().toString();
			  String message = textMessage.getText().toString();
 
			  Intent email = new Intent(Intent.ACTION_SEND);
			  email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
			  //email.putExtra(Intent.EXTRA_CC, new String[]{ to});
			  //email.putExtra(Intent.EXTRA_BCC, new String[]{to});
			  email.putExtra(Intent.EXTRA_SUBJECT, subject);
			  email.putExtra(Intent.EXTRA_TEXT, message);
 
			  //need this to prompts email client only
			  email.setType("message/rfc822");
 
			  startActivity(Intent.createChooser(email, "Choose an Email client :"));
 
			}
		});
	}
}

3. Demo

See default scree, fill in the detail, and click on the “send” button.
send email in android
It will prompts your existing Email client to select.
send email in android
In this case, i selected Gmail, and all previous filled in detail will be populated to Gmail client automatically.
send email in android
Note
Android does not provide API to send Email directly, you have to call the existing Email client to send Email.

Download Source Code

Download it – Android-Send-Email-Example.zip (16 KB)
 
Read More

Monday, 19 August 2013

Android Application for load image from galary

// siddhu vydyabhushana // 1 comment
Since few days I am working on an Android app and learning all the nitty gritty of its APIs. I will share few How-to stuffs that we frequently require in Android.
To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.
Let us create an example with following requirement:
  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.
So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.
Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.
Open layout/main.xml in your android project and replace its content with following:
File: res/layout/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">
    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"></ImageView>
    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Load Picture"
        android:layout_gravity="center"></Button>
</LinearLayout>
So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.
Thus, on click of button we will trigger following code:
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 
startActivityForResult(i, RESULT_LOAD_IMAGE);
Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.
So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:
@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
      
     if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
         Uri selectedImage = data.getData();
         String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
         Cursor cursor = getContentResolver().query(selectedImage,
                 filePathColumn, null, null, null);
         cursor.moveToFirst();
 
         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         String picturePath = cursor.getString(columnIndex);
         cursor.close();
                      
         // String picturePath contains the path of selected Image
     }
Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.
package net.viralpatel.android.imagegalleray;
 
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
public class ImageGalleryDemoActivity extends Activity {
     
     
    private static int RESULT_LOAD_IMAGE = 1;
     
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View arg0) {
                 
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
     
     
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
 
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
             
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
         
        }
     
     
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
                                              android-gallery-intent-example
User can select an image from Image Gallery
                                                 android-gallery-intent-select-image
Once user selects an image, the same will be displayed on our main activity
                                                 android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)
Read More