Who are the Developers of Android?

Android powered devices like mobile phones, tablet computers and home appliances are everywhere nowadays. It is a delight for us to experience a high technology which is less expensive, more powerful and efficient. You know what Android is, you might be grateful, and now you are asking…
“Who are the developers of Android?”
Android growth in device activations. Image from Android Developers.

Who are the people behind this amazing technology? Today’s article focuses on bringing you a brief answer to that question. So here it is – I think there are three major developers of Android, they are:
  1. Google
  2. Open Handset Alliance
  3. End Users
Who are the Developers of Android? - Google

Google bought Android Inc. on August 2005, and that makes Google as the lead developer of the Android platform. Under Google, Android has seen many updates which vastly improved the operating system. Major version names were named after a sweet dessert:

  • Android 1.5 – Cupcake (April 2009)
  • Android 1.6 – Donut (September 2009)
  • Android 2.0 – Eclair (October 2009)
  • Android 2.2 – Froyo (May 2010)
  • Android 2.3 – Gingerbread (December 2010)
  • Android 3.0 – Honeycomb (February 2011)
  • Android 4.0 – Ice Cream Sandwich (October 2011)
  • Android 4.1 – Jelly Bean (July 2012)
  • Android 5.0 – Key Lime Pie (Unofficial, expected to be released this second quarter of 2013)
Where are the letters ‘A’ and ‘B’? I think they are the Android 1.0 and Android 1.1, but no official names were announced. Google also developed and maintain an online electronic store called Google Play (formerly Android Market) where users can download useful applications (a lot of them are free!) and entertainment products.
Who are the Developers of Android? - Open Handset Alliance

The Open Handset Alliance is an association of 80+ technology and mobile companies from around the world who work together for the development of Android. Now imagine what Android can achieve! I believe that these companies have the talent, resources and power to create or develop the Android technology as the best mobile operating system. Companies include:

  • Mobile Operators – Sprint Nextel, T-mobile, Telus, Vodafone, etc.
  • Handset Manufacturers – Acer Inc, HTC Corp., LG Electronics, Motorola, Samsung, etc.
  • Semiconductor Companies – Intel Corp, MediaTek, NVIDIA Corp, Qualcomm, etc.
  • Software Companies – eBay, Google, Nuance, etc.
  • and Commercialization Companies like Accenture, Wind River, Teleca AB, etc.
Who are the Developers of Android? - End Users
Some android users. Image from autocadws.

Yes, I think that we, the users have always been involved with the development of Android. The technical developers gets feedback and innovative or crazy ideas from us to make apps and the platform better. It is us that voices out what we really want to use and experience. We have the power to make Android better than we can imagine!

How to Send Data From Android to PHP Server? Android Post Request Help

Hi guys! Today we are going to code on how to send data from Android to PHP server. This is an example app that can post a file and text data to a web server with PHP file as a receiver. Having the ability to (do HTTP Post Request) post data from android app to remote server is required for most apps. Here are some example use of this functionality:

1. You want to get statistics on how your app is being used (you have to tell your user and they must agree of course!)
2. Your app has an upload file feature.
3. A user should register on your database before using more features of your app.

DOWNLOAD SOURCE CODE

Download HttpComponents Library

In this example, we are using a small library for posting a file, it is called the HttpComponents from the Apache Software Foundation. Please note that you won’t need this library if you’re just posting text data. The download can be found here: HttpComponents

  1. As of the moment, I downloaded the binary 4.2.3.zip
  2. When you extracted the zip file, find the lib folder and copy all the jar files there
  3. Copy those jar files to your project’s lib folder, here’s how to do that:
  4. Go to your workspace directory, find your project folder and inside, find the libs folder, put the jar files we extracted earlier
  5. Go back to eclipse and refresh your project files in the project explorer, now you can see the jar files inside your lib directory. See the screenshot below to visualize the goal of these 5 steps above.

Library Import - How to Send Data From Android to PHP Server?

How To Post Text Data?

// url where the data will be posted
String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);

// HttpClient
HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);

// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("firstname", "Mike"));
nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
nameValuePairs.add(new BasicNameValuePair("email", "mike@testmail.com"));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {
    
    String responseStr = EntityUtils.toString(resEntity).trim();
    Log.v(TAG, "Response: " +  responseStr);
    
    // you can add an if statement here and do other actions based on the response
}

How To Post A File?

You can use this code to post other file types such as an image.

// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
Log.v(TAG, "textFile: " + textFile);

// the URL where the file will be posted
String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);

// new HttpClient
HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);

File file = new File(textFile);
FileBody fileBody = new FileBody(file);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);

// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();

if (resEntity != null) {
    
    String responseStr = EntityUtils.toString(resEntity).trim();
    Log.v(TAG, "Response: " +  responseStr);
    
    // you can add an if statement here and do other actions based on the response
}

Complete Android Code on How to Send Data From Android to PHP Server

This is our MainActivity.java code. In this code, we are:

  • Using AsyncTask to prevent the network on main thread error.
  • To test posting the text data, you must change the actionChoice variable value to 1.
  • Else if you are to test posting a sample file, you must change the actionChoice to 2. Also, don’t forget to put a sample.txt file in your SD card root directory.
package com.example.androidpostdatatophpserver;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.app.Activity;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity.java";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // we are going to use asynctask to prevent network on main thread exception
        new PostDataAsyncTask().execute();
        
    }

    public class PostDataAsyncTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            // do stuff before posting data
        }

        @Override
        protected String doInBackground(String... strings) {
            try {

                // 1 = post text data, 2 = post file
                int actionChoice = 2;
                
                // post a text data
                if(actionChoice==1){
                    postText();
                }
                
                // post a file
                else{
                    postFile();
                }
                
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String lenghtOfFile) {
            // do stuff after posting data
        }
    }
    
    // this will post our text data
    private void postText(){
        try{
            // url where the data will be posted
            String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);
            
            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            
            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);
    
            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("firstname", "Mike"));
            nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
            nameValuePairs.add(new BasicNameValuePair("email", "mike@testmail.com"));
            
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
            
            if (resEntity != null) {
                
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);
                
                // you can add an if statement here and do other actions based on the response
            }
            
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // will post our text file
    private void postFile(){
        try{
            
            // the file to be posted
            String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
            Log.v(TAG, "textFile: " + textFile);
            
            // the URL where the file will be posted
            String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
            Log.v(TAG, "postURL: " + postReceiverUrl);
            
            // new HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            
            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);
            
            File file = new File(textFile);
            FileBody fileBody = new FileBody(file);
    
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file", fileBody);
            httpPost.setEntity(reqEntity);
            
            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();
    
            if (resEntity != null) {
                
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v(TAG, "Response: " +  responseStr);
                
                // you can add an if statement here and do other actions based on the response
            }
            
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The code above should give you a lot of clue on how to send data from Android to PHP server. But we have few more steps to do, continue to read below.

PHP file that will receive the posted data

This is the post_date_receiver.php code. You must upload it in your server and specify the URL to our MainActivity.java

<?php
// if text data was posted
if($_POST){
    print_r($_POST);
}

// if a file was posted
else if($_FILES){
    $file = $_FILES['file'];
    $fileContents = file_get_contents($file["tmp_name"]);
    print_r($fileContents);
}
?>

AndroidManifest.xml Code

Well, we are just having an INTERNET permission here.

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

    <uses-permission android:name="android.permission.INTERNET" />
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidpostdatatophpserver.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>
    </application>

</manifest>

Output Screenshots

Response is what post_date_receiver.php outputs when it receives the posted data.

android http example - posting text data output

Posting Text Data. The response array have our key-value pairs.

Posting Text File. The response is the content of my sample.txt file.

Posting Text File. The response is the content of my sample.txt file.

What do you think fo this code I came up with? If you have a better solution about how to send data from Android to PHP server, please let us know in the comments section below! We will add your solution or update this post if it deserves to, thanks!

Show ListView as Dropdown in Android – a Spinner Alternative

Our code for today will give us an alternative to using the Android spinner.

We will show ListView as dropdown in Android.

This ListView dropdown works just like a spinner but:

  • I love how it looks and response to user touch, it feels smoother and faster than a spinner.
  • It can also be easily customized, you won’t have to get stuck with default spinner look.
  • It can be triggered on any view elements such as a Button, Layout, TextView or EditText.

In this example, we are going to have a button that when it was touched, it will show a drop-down list of Dog names.

Here’s a video demo of our final output:

Show ListView as Dropdown in Android Complete Code

MainActivity.java – shows the button, set the items for the drop down list, creates the pop up window and then show it as drop down when the button was touched.

package com.example.showasdropdownexample;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;

public class MainActivity extends Activity {

    String TAG = "MainActivity.java";

    String popUpContents[];
    PopupWindow popupWindowDogs;
    Button buttonShowDropDown;

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

        // initialize pop up window items list
        
        // add items on the array dynamically
        // format is DogName::DogID
        List<String> dogsList = new ArrayList<String>();
        dogsList.add("Akita Inu::1");
        dogsList.add("Alaskan Klee Kai::2");
        dogsList.add("Papillon::3");
        dogsList.add("Tibetan Spaniel::4");

        // convert to simple array
        popUpContents = new String[dogsList.size()];
        dogsList.toArray(popUpContents);

        
        // initialize pop up window
        popupWindowDogs = popupWindowDogs();

        
        // button on click listener
        
        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {                                                                                                                                                                                                                                                                                                 

                switch (v.getId()) {

                case R.id.buttonShowDropDown:
                    // show the list view as dropdown
                    popupWindowDogs.showAsDropDown(v, -5, 0);
                    break;
                }
            }
        };

        // our button
        buttonShowDropDown = (Button) findViewById(R.id.buttonShowDropDown);
        buttonShowDropDown.setOnClickListener(handler);
    }

    public PopupWindow popupWindowDogs() {

        // initialize a pop up window type
        PopupWindow popupWindow = new PopupWindow(this);

        // the drop down list is a list view
        ListView listViewDogs = new ListView(this);
        
        // set our adapter and pass our pop up window contents
        listViewDogs.setAdapter(dogsAdapter(popUpContents));
        
        // set the item click listener
        listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());

        // some other visual settings
        popupWindow.setFocusable(true);
        popupWindow.setWidth(250);
        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        
        // set the list view as pop up window content
        popupWindow.setContentView(listViewDogs);

        return popupWindow;
    }

    /*
     * adapter where the list values will be set
     */
    private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {

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

                // setting the ID and text for every items in the list
                String item = getItem(position);
                String[] itemArr = item.split("::");
                String text = itemArr[0];
                String id = itemArr[1];

                // visual settings for the list item
                TextView listItem = new TextView(MainActivity.this);

                listItem.setText(text);
                listItem.setTag(id);
                listItem.setTextSize(22);
                listItem.setPadding(10, 10, 10, 10);
                listItem.setTextColor(Color.WHITE);
                
                return listItem;
            }
        };
        
        return adapter;
    }
}

DogsDropdownOnItemClickListener.java – triggered when an item on the drop down list was touched, it will change the text on the button and show a toast with the ID of the selected item.

package com.example.showasdropdownexample;

import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class DogsDropdownOnItemClickListener implements OnItemClickListener {

    String TAG = "DogsDropdownOnItemClickListener.java";
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {

        // get the context and main activity to access variables
        Context mContext = v.getContext();
        MainActivity mainActivity = ((MainActivity) mContext);
        
        // add some animation when a list item was clicked
        Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
        fadeInAnimation.setDuration(10);
        v.startAnimation(fadeInAnimation);
        
        // dismiss the pop up
        mainActivity.popupWindowDogs.dismiss();
        
        // get the text and set it as the button text
        String selectedItemText = ((TextView) v).getText().toString();
        mainActivity.buttonShowDropDown.setText(selectedItemText);
        
        // get the id
        String selectedItemTag = ((TextView) v).getTag().toString();
        Toast.makeText(mContext, "Dog ID is: " + selectedItemTag, Toast.LENGTH_SHORT).show();
        
    }

}

activity_main.xml – Here is the XML layout file we used for the user interface of our example.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/buttonShowDropDown"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Select your dog..." />

</RelativeLayout>

That’s the solution I got on how to show ListView as dropdown in android. If you have any other solutions or suggestions to improve or rewrite this code, please let us know in the comments section below.

Copy or Move File From One Directory to Another on Android

Today we are going to take a look at how to programmatically “copy” or “move” a file from one directory to another on Android. In case you want to be clarified about the difference, copying a file means the file will be seen on another directory (target location) without deleting the original file from the source location. Moving a file means the file will be seen in another directory and the original file will be deleted from its former location.

Logcat output when we successfuly copied a file. Click to enlarge.

Logcat output when we successfuly copied a file. Click to enlarge.

Here are some situations where I found these functionalities helpful:

  • Copying a file to another directory is useful when you have to save a file’s version or state in specific time.
  • Moving a file to another directory can be an advantage when you want to remove a file from a main folder of your application and make it an archive.

Download Code

Before running this code, you have to:

  • Place an example text file named “sample.txt” (with any text inside) in your SD card root.
  • Create a directory called “MyNewFolder” in your SD card root directory also.

Our MainActivity.java

package com.example.copyfilefromdirectorytoanother;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.app.Activity;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity.java";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // your sd card
        String sdCard = Environment.getExternalStorageDirectory().toString();
        
        // the file to be moved or copied
        File sourceLocation = new File (sdCard + "/sample.txt");
        
        // make sure your target location folder exists!
        File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");

        // just to take note of the location sources
        Log.v(TAG, "sourceLocation: " + sourceLocation);
        Log.v(TAG, "targetLocation: " + targetLocation);
        
        try {
            
            // 1 = move the file, 2 = copy the file
            int actionChoice = 2;
            
            // moving the file to another directory
            if(actionChoice==1){
                
                if(sourceLocation.renameTo(targetLocation)){
                    Log.v(TAG, "Move file successful.");
                }else{
                    Log.v(TAG, "Move file failed.");
                }
                
            }
            
            // we will copy the file
            else{
                
                // make sure the target file exists
                
                if(sourceLocation.exists()){
                    
                    InputStream in = new FileInputStream(sourceLocation);
                    OutputStream out = new FileOutputStream(targetLocation);
        
                    // Copy the bits from instream to outstream
                    byte[] buf = new byte[1024];
                    int len;
                    
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    
                    in.close();
                    out.close();
                    
                    Log.v(TAG, "Copy file successful.");
                    
                }else{
                    Log.v(TAG, "Copy file failed. Source file missing.");
                }
                
            }
            
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Logcat ouput when we move a file looks like this:

Click to enlarge.

Click to enlarge.

Logcat output when copying a file failed:

Click to enlarge.

Click to enlarge.


Thanks for reading this Copy or Move File From One Directory to Another on Android!