Tuesday, December 10, 2013

FTP Multiple files download in android


Here is the full source code,To Connect,authenticate and get files from FTP Server.Below requirements are needed for successfully connections.

Requirements:

  1. FTP server URL
  2. Username and Password

Steps:

  1. First of all we need to connect the FTP server using its URL.
  2. after successfully connection you need to authenticate and access your files.
  3. After login you can get all files and directories list.
  4. Now the main part is to get files one by one and save in your local device.

Here is the full source code for this operation, check below source code carefully.

import java.io.File;
import java.io.FileOutputStream;
import java.net.InetAddress;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class Downloads implements Runnable{

String TAG = "Downloads";
int fl = 0;
Context c ;
public Downloads(Context context) {
try {
final FTPClient ftp = new FTPClient();
final File dir = new File(Environment.getExternalStorageDirectory()
+ "/Android_guide");

if (!dir.exists()) {
dir.mkdir();
}
FTPFile[] filesList = null;
                        //FTP Server connection
ftp.connect(InetAddress.getByName("FTP file URL"));
//FTP username and password authentication
                        ftp.login("Username", "Password");
ftp.enterLocalPassiveMode();
//To change directory of FTP Server 
                        // ftp.changeWorkingDirectory("/");
filesList = ftp.listFiles("");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
Log.v("Coneection and login", "Successfully");
// -----------------------------
while (fl < filesList.length) {
try {
Log.v("File name", filesList[fl].getName());
boolean status = false;
try {
                          FileOutputStream desFileStream = new FileOutputStream(
dir+ dir.separator+ filesList[fl].getName());

status = ftp.retrieveFile(filesList[fl].getName(),desFileStream);
Log.v("status", "" + status);
desFileStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
              e.printStackTrace();
}
fl++;
}
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}

  • Thats it. But dont forget to give permission for WRITE EXTERNAL STORAGE
Add following permission in android menifest file.

android.permission.WRITE_EXTERNAL_STORAGE


To configure your project with FTP, You need to download following libraries.

  1. org.apache.commons.net_2.0.0.v200905272248.jar
  2. commons-net-1.4.1.jar

Download above libraries Here

Monday, December 9, 2013

Seekbar in android

Here is the full tutorial for seekbar in android.It is used to set range of value.You can also set background image of seekbar for some value.

Here is the tutorial for seekbar,It displays the value of seekbar in Edittext and also change the color of seekbar.

Source Code:


  • Create one project and copy below code in activity_main.xml file

activity_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:layout_height="fill_parent"
    android:orientation="horizontal"
    android:gravity="center"
    android:padding="20dp" >

    <SeekBar
        android:id="@+id/seek_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1.71"
        android:max="100"
        android:progress="0" />

    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.21" />

</LinearLayout>


  • Write below code in MainActivity.java file.

MainActivity.java


import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {

SeekBar sb;
EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = (SeekBar)findViewById(R.id.seek_bar);
et= (EditText)findViewById(R.id.et);
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
et.setText(""+progress);
if(progress>=50 && progress<70){
sb.setBackgroundColor(Color.RED);
}else if(progress>=70){
sb.setBackgroundColor(Color.YELLOW);
}else if(progress<50){
sb.setBackgroundColor(Color.TRANSPARENT);
}
}
});
}
}

  • That's It. Now run the project and see the output.


Sunday, November 24, 2013

Download file in Android application


You can download files in your android application without UI freeze.If your application has download file then you have to use threading or AsyncTask function.Which process in back end and without freeze the UI.

Here is the full tutorial,How to set download file function without freeze the UI.


  • First of all create new project named it 'Download file'.
  • Open activity_main.xml file and add below code in it.

activity_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:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File"
        android:layout_marginTop="50dip"/>

</LinearLayout>




  • Now Open MainActivity.java file and add below code.

MainActivity.java


public class MainActivity extends Activity {

Button btnShowProgress;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0; 
private static String file_url = "https://docs.google.com/uc?export=download&id=0B9w-wpPugvRfUUZDdWhtNU5qN1k";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
btnShowProgress.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
new DownloadFileFromURL().execute(file_url);
}
});
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}

@Override
protected String doInBackground(String... f_url) {
int count;
       try {
           URL url = new URL(f_url[0]);
           URLConnection conection = url.openConnection();
           conection.connect();
           // getting file length
           int lenghtOfFile = conection.getContentLength();

           // input stream to read file - with 8k buffer
           InputStream input = new BufferedInputStream(url.openStream(), 8192);
           
           // Output stream to write file
           OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");

           byte data[] = new byte[1024];

           long total = 0;

           while ((count = input.read(data)) != -1) {
               total += count;
               // publishing the progress....
               // After this onProgressUpdate will be called
               publishProgress(""+(int)((total*100)/lenghtOfFile));
               
               // writing data to file
               output.write(data, 0, count);
           }

           // flushing output
           output.flush();
           
           // closing streams
           output.close();
           input.close();
           
       } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
       }
       
       return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
}

}
}


  • Add Internet and Write Eternal Storage permissions in AndroidMenifest file.

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Wednesday, September 25, 2013

ListView with Checkbox android example



Download Full Source Code : Source Code



  • Create new project named "ListviewWithCheckbox".
  • add following code in activity_main.xml file.

activity_main.xml


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Country Codes"
        android:textSize="20sp" />

    <Button
        android:id="@+id/findSelected"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Selected Items" />

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

</LinearLayout>


  • Add below code in MainActivity.java file.

MainActivity.java



public class MainActivity extends Activity {

MyCustomAdapter dataAdapter = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Generate list View from ArrayList
displayListView();

checkButtonClick();

}

private void displayListView() {

// Array list of countries
ArrayList<States> stateList = new ArrayList<States>();

States _states = new States("91", "India", false);
stateList.add(_states);
_states = new States("61", "Australia", true);
stateList.add(_states);
_states = new States("55", "Brazil", false);
stateList.add(_states);
_states = new States("86", "China", true);
stateList.add(_states);
_states = new States("49", "Germany", true);
stateList.add(_states);
_states = new States("36", "Hungary", false);
stateList.add(_states);
_states = new States("39", "Italy", false);
stateList.add(_states);
_states = new States("1", "US", false);
stateList.add(_states);
_states = new States("44", "UK", false);
stateList.add(_states);

// create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this, R.layout.state_info, stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);

listView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
States state = (States) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Clicked on : " + state.getName(), Toast.LENGTH_LONG)
.show();
}
});
}

private class MyCustomAdapter extends ArrayAdapter<States> {

private ArrayList<States> stateList;

public MyCustomAdapter(Context context, int textViewResourceId,

ArrayList<States> stateList) {
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
}

private class ViewHolder {
TextView code;
CheckBox name;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

Log.v("ConvertView", String.valueOf(position));

if (convertView == null) {

LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = vi.inflate(R.layout.state_info, null);

holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView
.findViewById(R.id.checkBox1);

convertView.setTag(holder);

holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();

Toast.makeText(
getApplicationContext(),
"Checkbox: " + cb.getText() + " -> "
+ cb.isChecked(), Toast.LENGTH_LONG)
.show();

_state.setSelected(cb.isChecked());
}
});

} else {
holder = (ViewHolder) convertView.getTag();
}

States state = stateList.get(position);

holder.code.setText(" (" + state.getCode() + ")");
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());

holder.name.setTag(state);

return convertView;
}

}

private void checkButtonClick() {

Button myButton = (Button) findViewById(R.id.findSelected);

myButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

StringBuffer responseText = new StringBuffer();
responseText.append("Selected Countries are...\n");

ArrayList<States> stateList = dataAdapter.stateList;

for (int i = 0; i < stateList.size(); i++) {
States state = stateList.get(i);

if (state.isSelected()) {
responseText.append("\n" + state.getName());
}
}

Toast.makeText(getApplicationContext(), responseText,
Toast.LENGTH_LONG).show();
}
});
}

}



  • Create new POJO java class,Which is used for getters and setters methods.Named it States.java. 

States.java



public class States {

String code = null;
String name = null;
boolean selected = false;

public States(String code, String name, boolean selected) {
super();
this.code = code;
this.name = name;
this.selected = selected;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

}

  • Create new XML layout file, which is used to integrate CheckBox and TextView in ListView.Named it state_info.xml.

state_info.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="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="checkbox"
        android:textColor="#B40404" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/checkBox1"
        android:layout_alignBottom="@id/checkBox1"
        android:layout_toRightOf="@id/checkBox1"
        android:text="textview"
        android:textColor="#ff000000" />

</RelativeLayout>


  • Done ! Now run the project.


Download Full Source Code : Source Code



Tuesday, September 24, 2013

Check internet connection using broadcast receiver

In android device basically 2 types of internet connectivity.

1. Mobile internet (GPRS)
2. Wifi internet connectivity

If we need to perform some operation on internet connectivity change,Here is the full code for it.It is very useful to sync application data in offline and online mode also.


Let's Start 


  • First of all give below permission just above <application> tag.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


  • We are using broadcast receiver for notification. Broadcast receiver provides the functionality of background process.
  • It is running in back end continuously and will give notification.For this purpose we need to register our broadcast receiver in AndroidMenifest.xml file.  
  • Write down below code before completion of </application> tag(In <Application> tag).
<receiver
            android:name="<package_name>.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>


  • Full AndroidMenifest.xml is given below:

AndroidMenifest.xml


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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.broadcast_internetcheck.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.example.broadcast_internetcheck.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


  • Now Create on global file for check internet connectivity.It will return the result of which internet connectivity is currently active.
  • Create new java class file and named it, NetworkUtil.java

NetworkUtil.java


public class NetworkUtil {

public static int TYPE_WIFI = 1;
   public static int TYPE_MOBILE = 2;
   public static int TYPE_NOT_CONNECTED = 0;
    
    
   public static int getConnectivityStatus(Context context) {
       ConnectivityManager cm = (ConnectivityManager) context
               .getSystemService(Context.CONNECTIVITY_SERVICE);
 
       NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
       if (null != activeNetwork) {
           if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
               return TYPE_WIFI;
            
           if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
               return TYPE_MOBILE;
       } 
       return TYPE_NOT_CONNECTED;
   }
    
   public static String getConnectivityStatusString(Context context) {
       int conn = NetworkUtil.getConnectivityStatus(context);
       String status = null;
       if (conn == NetworkUtil.TYPE_WIFI) {
           status = "Wifi enabled";
       } else if (conn == NetworkUtil.TYPE_MOBILE) {
           status = "Mobile data enabled";
       } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
           status = "Not connected to Internet";
       }
       return status;
   }
}


  • If you get some error,than press Ctrl + Shift + O. It will import missing inbuilt library.
  • Create new java class file and named it, NetworkChangeReceiver.java and write down below code. It extends BroadcastReceiver. We have already registered it on AndroidMenifest.xml file.

NetworkChangeReceiver.java



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver{

@Override
   public void onReceive(final Context context, final Intent intent) {
 
       String status = NetworkUtil.getConnectivityStatusString(context);
 
       Toast.makeText(context, status, Toast.LENGTH_LONG).show();
   }
}

  • Now run this project and get output. Remember that for Wifi result run it on real device. It may not give the gesult of WIFI Connectivity.

Monday, September 9, 2013

ShakeListener Example

Android device has advance function,It has hardware to detect shake event.It can also detect the direction of shaking device.This advance function measure the value of X, Y and Z direction.Screenshot of Shake Listener is given below.

How to Develop ?

  • Create one Project named "ShakeListener".
  • Insert below code in activity_main.xml file which is stored in res/layout directory of project folder.

activity_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">

        <TableLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:stretchColumns="0|1">
        
                <TableRow>
                
                        <TextView
                                android:text="X :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/x"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="Y :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/y"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="Z :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/z"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aX :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/ax"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aY :"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/ay"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
        
                <TableRow>
                
                        <TextView
                                android:text="aZ"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="right"/>
                
                        <TextView
                                android:id="@+id/az"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_gravity="left"/>
                
                </TableRow>
                
        </TableLayout>

</LinearLayout>



  • Now Open MainActivity.java file and insert Following code in it.

MainActivity.java

public class MainActivity extends Activity implements SensorEventListener {
    
        SensorManager sensorManager = null;
    private TextView x, y, z, ax, ay, az;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        setContentView(R.layout.activity_main);
        // initialize display
        x = (TextView) findViewById(R.id.x);
        y = (TextView) findViewById(R.id.y);
        z = (TextView) findViewById(R.id.z);
        ax = (TextView) findViewById(R.id.ax);
        ay = (TextView) findViewById(R.id.ay);
        az = (TextView) findViewById(R.id.az);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_GAME);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        sensorManager.unregisterListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ORIENTATION));
        sensorManager.unregisterListener(this, 
                        sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER));
    }
    
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
        
        public void onSensorChanged(SensorEvent event) {
                synchronized (this) {
                switch (event.sensor.getType()) {
                        case SensorManager.SENSOR_ORIENTATION :
                                x.setText(String.valueOf(event.values[SensorManager.DATA_X]));
                                y.setText(String.valueOf(event.values[SensorManager.DATA_Y]));
                                z.setText(String.valueOf(event.values[SensorManager.DATA_Z]));
                                break;
                        case SensorManager.SENSOR_ACCELEROMETER :
                                ax.setText(String.valueOf(event.values[SensorManager.DATA_X]));
                                ay.setText(String.valueOf(event.values[SensorManager.DATA_Y]));
                                az.setText(String.valueOf(event.values[SensorManager.DATA_Z]));
                                break;
                }           
        }
        } 
        
}


  • If you get few errors then press CTRL+SHIFT+O. It imports all missing libraries.
  • That's It. Now run the project.

Get Full Source Code: FREE




Accelerometer full source code

Accelerometer in android, the value would show acceleration in X, Y and Z direction.Sample code is available in SDK manager.If you can't see it,Don't worry. Here is the full source code is available. 



Download Full Source Code:  FREE




Friday, September 6, 2013

Send Mail Automatically without Intent Tutorial

You can use intent to send mail.It uses inbuilt Email application to send mail.You can also send mail without using inbuilt email application.You need to have knowledge of SMTP (Simple Mail Transfer Protocol). There are many libraries available for send mail automatically.I use some of that for this tutorial.

Before we begin you need to download few library files and java class files.


  1. Auto send Mail Libraries
  2. Java Class Files

After Download above RAR, Extract it.

Here is the full description of project below, I will go through step by step.


  • Create android project named "SendEmailAuto".
  • Now Add library files (Above First Link) to your project (Right click your project > Properties > Java Build Path > Libraries > Add External JARs. Now Go to Order and Export Tab > Checked all JARs and press OK button)
  • Add Java class files (Above second link) into project src folder.Your Project Hierarchy is look like:



  • Now add following code in activity_main.xml

activity_main.xml



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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="25dp" >

        <EditText
            android:id="@+id/etemail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Enter Your Email ID"
            android:inputType="textEmailAddress"
            android:lines="1" />

        <EditText
            android:id="@+id/etPass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Enter Your Password"
            android:inputType="textPassword"
            android:lines="1" />

        <Button
            android:id="@+id/btnCompose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Compose" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            android:id="@+id/composeLinear"
            android:orientation="vertical" >

            <EditText
                android:id="@+id/etTo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="To"
                android:lines="1" >

                <requestFocus />
            </EditText>

            <EditText
                android:id="@+id/etSubject"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Subject"
                android:lines="1" />

            <EditText
                android:id="@+id/etBody"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:gravity="left|top"
                android:hint="Enter Text Here"
                android:lines="10" />

            <Button
                android:id="@+id/btnSend"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Send" />
        </LinearLayout>
    </LinearLayout>

</ScrollView>


  • Add following code in MainActivity.java

MainActivity.java


public class MainActivity extends Activity {

Button btnSend,btnCompose;
EditText etemailId,etPass,etTo,etSub,etBody;
String emailId,spass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button)findViewById(R.id.btnSend);
btnCompose = (Button)findViewById(R.id.btnCompose);
etemailId = (EditText)findViewById(R.id.etemail);
etPass = (EditText)findViewById(R.id.etPass);
etTo = (EditText)findViewById(R.id.etTo);
etSub = (EditText)findViewById(R.id.etSubject);
etBody = (EditText)findViewById(R.id.etBody);
final LinearLayout layout= (LinearLayout)findViewById(R.id.composeLinear);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String sub = etSub.getText().toString();
String to = etTo.getText().toString();
String body = etBody.getText().toString();
try {   
       GmailSender sender = new GmailSender(emailId, spass);
       sender.sendMail(sub,body,emailId,to);  
       Toast.makeText(getApplicationContext(),"Mail has been sent.",Toast.LENGTH_SHORT).show();
   } catch (Exception e) {   
    Toast.makeText(getApplicationContext(),"Error! Try again later.",Toast.LENGTH_SHORT).show();
   }
}
});
btnCompose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
emailId = etemailId.getText().toString();
spass = etPass.getText().toString();
if(emailId.equals("") || spass.equals("")){
Toast.makeText(getApplicationContext(),"Email ID and Password fields are mandatory.",Toast.LENGTH_SHORT).show();
}else{
layout.setVisibility(View.VISIBLE);
}
}
});
}
}

  • If you get error,Don't worry. Just press Ctrl + Shift + O button. It will import all missing libraries.
  • Don't forget to give internet permission in AndroidMenifest.xml file.
  • Open AndroidMenifest.xml file and add below permissions, before <application> tag.

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  • Done ! Now run the project.
NOTE : Don't use Android emulator for testing,It will not work on Android emulator. Use real android device for testing.Before run this project check your emailID and password.  

Download Full Source code : Download