Showing posts with label Android Beginner. Show all posts
Showing posts with label Android Beginner. 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

Thursday 26 September 2013

hide Title Bar in Android

// siddhu vydyabhushana // 3 comments
When you developing application some times Title Bar is looking awkward, so we have to remove it.Title bar will represents that what activity is running.

To remove TitleBar single line code we have to use within onCreate method.

Syntax:

requestWindowFeature(Window.FEATURE_NO_TITLE);
 

Show your application in the Mode of FullScreen

Use setFlags to show your application in fullscreen.

Syntax:

this.getWindow().setFlags(flags, mask);
 

Full Code:

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
  //to hide TitleBar
  requestWindowFeature(Window.FEATURE_NO_TITLE);

//for FULL SCREEN  
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
  
  setContentView(R.layout.activity_main);
 }
 

Output:

hide titlebar in android
Read More

Android SwipeView Example

// siddhu vydyabhushana // 4 comments

Swipe View Design:

First Design three Layouts with simple TextView.

swipe view in android

Design PageTitleStrip for SwipeView:


page title strip in android

Output Screen:


page title strip in android

Code for PageTilteStrip:

we have to take the support of android.support.v4 library.I included all in zip folder.

<android.support.v4.view.ViewPager 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <!--
    This title strip will display the currently visible page title, as well as the page
    titles for adjacent pages.
    -->

    <android.support.v4.view.PagerTitleStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:paddingBottom="4dp"
        android:paddingTop="4dp"
        android:textColor="#fff" />

</android.support.v4.view.ViewPager>
	

Layout1.xml

	
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is siddhu vydyabhushana" />
        

    </LinearLayout>


	

Layout2.xml

	
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is pavan" />
        

    </LinearLayout>


	

Layout3.xml

	
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is chakitha" />
        

    </LinearLayout>


	

Swipe View Folder Structure in Eclipse:

swipe view in android

MainActivity.java

package com.siddhu.swipeview;

import com.siddhu.swipeview.R;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The ViewPager that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// Create the adapter that will return a fragment for each of the three
		// primary sections
		// of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(this,
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

	}

	/**
	 * A FragmentPagerAdapter that returns a fragment corresponding to one of
	 * the primary sections of the app.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		Context c;

		public SectionsPagerAdapter(Context c, FragmentManager fm) {
			super(fm);
			this.c = c;
		}

		@Override
		public Fragment getItem(int i) {
			Fragment fragment = null;
			if (i == 0) {
				fragment = new Page1(c);
			}
			if (i == 1) {
				fragment = new Page2(c);
			}
			if (i == 2) {
				fragment = new Page3(c);
			}
			return fragment; 
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase();
			case 1:
				return getString(R.string.title_section2).toUpperCase();
			case 2:
				return getString(R.string.title_section3).toUpperCase();
			}
			return null;
		}
	}

}

	

Page1.java

package com.siddhu.swipeview;

import com.siddhu.swipeview.R;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page1 extends Fragment {
	Context c;

	public Page1(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section1, null);

		return v;
	}
}
	

Similarly as above designed Page2.java, Page3.java files too.
Read More