Minggu, 24 Mei 2015

Materi Pertemuan 14 (Map 1)

Latitude, Longitude
Layout
 <LinearLayout
    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"
    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"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="@string/lonText"
        >      
    </TextView>
    <TextView
        android:text="unknown"
        android:id="@+id/longitutdeTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >      
    </TextView>
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="@string/latText"
        >      
    </TextView>
    <TextView
        android:text="unknown"
        android:id="@+id/latitudeTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >      
    </TextView>

</LinearLayout>

Java
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private LocationManager lm;
    private LocationListener locListener;
    private TextView latTxt,lonTxt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        latTxt = (TextView) findViewById(R.id.latitudeTxt);
        lonTxt = (TextView) findViewById(R.id.longitutdeTxt);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locListener = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 200, locListener);
    }
    private class MyLocationListener implements LocationListener {
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                latTxt.setText(String.valueOf(loc.getLatitude()));
                lonTxt.setText(String.valueOf(loc.getLongitude()));
                Toast.makeText(getBaseContext(), "Location Changed : Lat " + loc.getLatitude() + "lgt: "+loc.getLongitude(), Toast.LENGTH_SHORT).show();
            }
        }
        public void onProviderDisabled(String arg0) {}
        public void onProviderEnabled(String arg0) {}
        public void onStatusChanged(String provider, int status, Bundle extras){}
    }
}

Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


MAP
Layout
<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"
    tools:context=".MainActivity" >
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>

Java
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class Map2 extends FragmentActivity {
    private GoogleMap map;

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

    private void setupMapIfNeeded() {
        if (map == null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
                    .findFragmentById(R.id.map);
            map = supportMapFragment.getMap();

            if (map != null) {
                setupMap();
            }
        }

    }

    private void setupMap() {
        map.setMyLocationEnabled(true);
        moveToMyLocation();
    }

    private void moveToMyLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager
                .getLastKnownLocation(locationManager.getBestProvider(criteria,
                        false));
        if (location != null) {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
                    location.getLatitude(), location.getLongitude()), 13));
        }
    }

}


Manifest
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.example.belajarmap.MAPS_RECEIVE" />

    <permission
        android:name="com.example.belajarmap.MAPS_RECEIVE"
        android:protectionLevel="signature" >
    </permission>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />


<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="Google API Key" />

<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />


Library google_play_services
vending
gms

Minggu, 10 Mei 2015

Materi Pertemuan 13 (Multimedia 2)

KAMERA
Layout
 <?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/camera"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="AMBIL FOTO" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

Java
import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class KameraActivity extends Activity {
    private static int TAKE_PICTURE = 1;
    private Uri tmpgambar;   
    private Button tmbkamera;
    private String strFile;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kamera);
        tmbkamera = (Button)findViewById(R.id.camera);       
        tmbkamera.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                buatFolder();
                ambilFoto(v);
            }
        });
    }
   
    private void ambilFoto(View v){       
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        strFile = Environment.getExternalStorageDirectory()+ "/ContohDataMultimedia/fileFoto.jpg";
        File foto = new File(strFile);
        tmpgambar = Uri.fromFile(foto);       
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpgambar);
        startActivityForResult(intent, TAKE_PICTURE);       
    }
   
    private void buatFolder(){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path+"/ContohDataMultimedia/");
        if(!file.exists()){
            file.mkdir();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            try { // Kalau2 fotonya gak ke save
                Bitmap bitmap = BitmapFactory.decodeFile(strFile);
                ((ImageView)findViewById(R.id.imageView1)).setImageBitmap(bitmap);   
            } catch (Exception e) {
                e.printStackTrace();
            }               
        }       
    }
}

VIDEO
Create

 <?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/video"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Buat Video" /> 

</LinearLayout>

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class BuatVideoActivity extends Activity {
    private static int TAKE_PICTURE = 1;
    private Uri tmpvideo;   
    private Button tmbvideo;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buat_video);
        tmbvideo = (Button)findViewById(R.id.video);       
        tmbvideo.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                buatFolder();
                ambilVideo(v);
            }
        });
    }
   
    private void ambilVideo(View v){       
        Intent intent = new Intent("android.media.action.VIDEO_CAPTURE");
        File video = new File(Environment.getExternalStorageDirectory()+ "/ContohDataMultimedia/fileVideo.3gp");       
        tmpvideo = Uri.fromFile(video);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpvideo);
        startActivityForResult(intent, TAKE_PICTURE);       
    }
   
    private void buatFolder(){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path+"/ContohDataMultimedia/");
        if(!file.exists()){
            file.mkdir();
        }
    }
}

List
 <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp"
    android:textSize="25dp" >
</TextView>

import java.io.File;
import java.io.FilenameFilter;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DaftarVideoActivity extends ListActivity {
    ArrayAdapter<String>adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       
        adapter = new ArrayAdapter<String>(this, R.layout.daftarvideo, getVideo());
        setListAdapter(adapter);
        ListView listView = getListView();
        listView.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
                String tempat = parent.getItemAtPosition(position).toString();
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), VideoActivity.class);
                intent.putExtra("video", tempat);
                startActivity(intent);
            }
           
        });
    }
   
    static String [] nmFile=null;
    public static String [] getVideo(){       
        File video = new File(Environment.getExternalStorageDirectory()+"/ContohDataMultimedia/");       
        File [] daftarVideo =  video.listFiles(new FilenameFilter(){
            public boolean accept(File dir, String name) {
                return (((name.endsWith(".mp3"))||(name.endsWith(".MP3"))||(name.endsWith(".mp4"))||
                        (name.endsWith(".MP4"))||(name.endsWith(".avi"))||(name.endsWith(".AVI"))||
                        (name.endsWith(".3gp"))||(name.endsWith(".mkv"))||(name.endsWith(".MKV"))||
                        (name.endsWith(".wmv"))||(name.endsWith(".WMV"))||(name.endsWith(".flv"))||
                        (name.endsWith(".FLV"))));
            }
        });
        nmFile = new String[daftarVideo.length];
        for(int i=0; i<daftarVideo.length; i++){
            nmFile[i] = daftarVideo[i].getAbsolutePath();
        }
        return nmFile;
    }   

}

Play
<?xml version="1.0" encoding="utf-8"?>
<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="80dp"
    android:paddingRight="80dp"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video);
        Bundle bundle = getIntent().getExtras();
        String tempat = bundle.getString("video");
        VideoView videoView = (VideoView)findViewById(R.id.videoView1);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        Uri uri = Uri.parse(tempat);
        videoView.setVideoURI(uri);
        videoView.setMediaController(mediaController);
        videoView.start();
        videoView.requestFocus();
    }   

}


AUDIO
Layout
 <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=".RecordActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="..."
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="Mulai Rekam"
        android:textSize="30dp" />
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="10dp"
        android:text="Stop Rekam"
        android:textSize="30dp"/>
    <Button
        android:id="@+id/button3"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="10dp"
        android:text="Putar"
        android:textSize="30dp"/>
    <Button
        android:id="@+id/button4"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignRight="@+id/button3"
        android:layout_below="@+id/button3"
        android:layout_marginTop="10dp"
        android:text="Stop"
        android:textSize="30dp"/>
</RelativeLayout>

Java
import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RekamActivity extends Activity {
    private Button rekam, stopr, putar, stopp;
    private TextView txt;
    private MediaPlayer mp;
    private MediaRecorder mr;
    private String tempat;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rekam);
        tempat = Environment.getExternalStorageDirectory() + "/ContohDataMultimedia/fileRekam.3gpp";
        txt = (TextView)findViewById(R.id.textView1);
        rekam = (Button)findViewById(R.id.button1);
        rekam.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                buatFolder();
                startRekam();
                txt.setText("Sedang Merekam...");
                rekam.setEnabled(false);
                stopr.setEnabled(true);
                putar.setEnabled(false);
                stopp.setEnabled(false);
            }
        });
        stopr = (Button)findViewById(R.id.button2);
        stopr.setEnabled(false);
        stopr.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopRekam();
                txt.setText("");
                rekam.setEnabled(true);
                stopr.setEnabled(false);
                putar.setEnabled(true);
                stopp.setEnabled(false);
            }
        });
        putar = (Button)findViewById(R.id.button3);
        putar.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startHasil();
                txt.setText("Sedang Memutar...");
                rekam.setEnabled(false);
                stopr.setEnabled(false);
                putar.setEnabled(false);
                stopp.setEnabled(true);
            }
        });
        stopp = (Button)findViewById(R.id.button4);
        stopp.setEnabled(false);
        stopp.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopHasil();
                txt.setText("");
                rekam.setEnabled(true);
                stopr.setEnabled(false);
                putar.setEnabled(true);
                stopp.setEnabled(false);
            }
        });
    }
   
    private void buatFolder(){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path+"/ContohDataMultimedia/");
        if(!file.exists()){
            file.mkdir();
        }
    }
   
    public void startRekam(){
        if(mr != null){
            mr.release();
        }
        File fout = new File(tempat);
        if(fout != null){
            fout.delete();
        }
        mr = new MediaRecorder();
        mr.setAudioSource(MediaRecorder.AudioSource.MIC);
        mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mr.setOutputFile(tempat);
        try {
            mr.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mr.start();
    }
    public void stopRekam(){
        if(mr != null){
            mr.stop();
            mr.release();
            mr = null;
        }
    }
    public void startHasil(){
        mp = new MediaPlayer();
        try {
            mp.setDataSource(tempat);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void stopHasil(){
        if(mp != null){
            if(mp.isPlaying())
                mp.stop();
            mp.release();
            mp = null;
        }
    }
   
}

FILE
Layout
<?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"
    android:padding="10dp" >

    <EditText
        android:id="@+id/editNama"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Nama"
        />
    <TextView
            android:id="@+id/txtStatusGambar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#fff"
            android:text="Gambar Belum Dipilih" >
    </TextView>
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center_horizontal" >
    <Button
            android:id="@+id/btnChooseImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Select Image" >
    </Button>
    <Button
            android:id="@+id/btnAddImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Upload Image" >
    </Button>  
    </LinearLayout>
</LinearLayout>

Java
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    Button upload,add;
    TextView status;
    EditText nama;
  
    //variable for upload data into http
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;
  
    Bitmap bm;

    static String pathToOurFile = "",format;
    String urlServer = "http://kelasandroid.net16.net/imageupload/upload.php";   
    String lineEnd = "\r\n",twoHyphens = "--",boundary =  "*****";
  
    private static final int SELECT_PICTURE = 0;

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_upload);
        upload=(Button)findViewById(R.id.btnChooseImage);
        upload.setOnClickListener(this);
        add=(Button)findViewById(R.id.btnAddImage);
        add.setOnClickListener(this);
        status=(TextView)findViewById(R.id.txtStatusGambar);
        nama=(EditText)findViewById(R.id.editNama);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btnChooseImage:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
            break;
        case R.id.btnAddImage:
            try {
                bm = BitmapFactory.decodeFile(pathToOurFile);
                new UploadFile().execute("");               
                } catch (Exception e) {
                    Log.e(e.getClass().getName(), e.getMessage());
                }
            break;
        default:
            break;
        }
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            status.setText(data.getData().toString());
            String[] projection = { MediaStore.Images.Media.DATA };          
            Cursor cursor = managedQuery(data.getData(), projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String filePath = cursor.getString(column_index);
            //cursor.close();
            pathToOurFile=filePath;
            format = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
        }      
    }  
   
    class UploadFile extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... params) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(urlServer);
                ByteArrayBody bab = new ByteArrayBody(data, nama.getText().toString()+"."+format);
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("uploaded", bab);
                reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }               
                return "Success";               
            } catch (Exception e) {               
                e.printStackTrace();               
            }   
            return null;
        }
        @Override
        protected void onPostExecute(String result) {           
            super.onPostExecute(result);
            if("Success".equals(result)){
                Toast.makeText(FileUploadActivity.this, "Penambahan data berhasil", 1).show();
            }else{
                Toast.makeText(FileUploadActivity.this, "Penambahan data GAGAL", 1).show();
            }           
        }
    }   
  
}

Php
<?php
$target_path  = "./upload/";
$target_path = $target_path . basename( $_FILES['uploaded']['name']);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploaded']['name']).
" has been uploaded";
} else{
echo "Gagal Bung!";
}
?>

Download library untuk upload file
httpclient
httpmime

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

Minggu, 03 Mei 2015

Materi Pertemuan 12 (Multimedia 1)


Speech To Text
Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Speech To Text English" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Speak" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

</LinearLayout>

Java
 import java.util.ArrayList;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class EnglishActivity extends Activity {

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

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

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

                try {
                    startActivityForResult(intent, 1);

                    EditText editText1 = (EditText) findViewById(R.id.editText1);
                    editText1.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Device Not Supported", Toast.LENGTH_SHORT);
                    t.show();
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        case 1: {
            if (resultCode == RESULT_OK && null != data) {

                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                EditText editText1 = (EditText) findViewById(R.id.editText1);
                editText1.setText(text.get(0));
            }
            break;
        }

        }
    }
}



Session
Create
 import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SessionActivity extends Activity {
    SharedPreferences sharedPreferences;
    final static String SHARED_NAME_STRING="sharedp";
    final static String NAME_STRING="user";
    EditText editText;
    Button vOK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_session);
        editText = (EditText)findViewById(R.id.nama);
        sharedPreferences=getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
        String nameString = sharedPreferences.getString(NAME_STRING, "");      
              
        vOK = (Button) findViewById(R.id.ok);
        vOK.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editText.getText().toString();
                Intent intent = new Intent(SessionActivity.this, SessionGetActivity.class);
                intent.putExtra("user", string);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(NAME_STRING, string);
                editor.commit();
                startActivity(intent);
                finish();
            }
        });
    }

}

Layoutnya
<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=".SessionActivity" >   
   
    <EditText
        android:id="@+id/nama"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="5dp"
        android:hint="Please Enter Your Name"
        android:background="#0fffff"
        android:ems="10" >
    </EditText>

    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nama"
        android:layout_below="@+id/nama"
        android:text="OK" />

</RelativeLayout>


Get 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SessionGetActivity extends Activity {
    SharedPreferences sharedPreferences;
    TextView userTextView;
    Button vBACK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_session_get);       
        userTextView = (TextView)findViewById(R.id.personTextView);
        userTextView.setText("Name: "+getIntent().getStringExtra(SessionActivity.NAME_STRING));
        vBACK = (Button) findViewById(R.id.back);
        vBACK.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sharedPreferences = getSharedPreferences(SessionActivity.NAME_STRING, MODE_PRIVATE);
                sharedPreferences.edit().clear().commit();
                Intent intent = new Intent(SessionGetActivity.this, SessionActivity.class);           
                startActivity(intent);       
                finish();
            }
        });
    }

}

Layoutnya
<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=".SessionGetActivity" >

    <TextView
            android:id="@+id/personTextView"
            android:gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"          
            android:text="Medium Text" />

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/personTextView"
        android:layout_below="@+id/personTextView"
        android:text="BACK" />

</RelativeLayout>

MP3
Layout
<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:background="#4a4a4a">
   
    <!-- Player Header -->
   
    <!-- Song Thumbnail Image -->

 <WebView
     android:id="@+id/my_webview"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_above="@+id/player_footer_bg"
     android:layout_weight="0.84"
     android:background="@drawable/bg" />
   
    <!-- Player Footer -->

    <LinearLayout
        android:id="@+id/player_footer_bg"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"       
        android:gravity="center" >
       
        <!-- Player Buttons -->

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical"           
            android:paddingLeft="10dp"
            android:paddingRight="10dp">
            <!-- Previous Button -->
            <!-- Backward Button -->
            <!-- Play Button -->

            <ImageButton
                android:id="@+id/btnPlay"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@null"
                android:src="@drawable/btn_play" />

            <!-- Forward Button -->
            <!-- Next Button -->
        </LinearLayout>
    </LinearLayout>
   
    <!-- Progress Bar/Seek bar -->
   
    <!-- Timer Display -->
   
    <!-- Repeat / Shuffle buttons -->

    <ImageView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="131dp"
        android:src="@drawable/a" />

</RelativeLayout>

Java
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;

public class Mp3Activity extends Activity implements AnimationListener {
    private MediaPlayer mp;   
    private ImageButton btnPlay;
    String content;
    Animation animFadein;
    Animation animFadeOut;
    private ImageView    tes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mp3);
        btnPlay = (ImageButton) findViewById(R.id.btnPlay);
        tes = (ImageView) findViewById(R.id.textView1);
        content = "file:///android_asset/aku.html";
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                 WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setTitle("Aku Suka Caramu");
        mp = MediaPlayer.create(this, R.raw.akusukacaramu);
        animFadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
        animFadein.setAnimationListener(this);
        animFadeOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);       
        animFadeOut.setAnimationListener(this);
        final WebView wv;
        wv = (WebView) findViewById(R.id.my_webview);
        WebSettings webSettings = wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
        btnPlay.setOnClickListener(new View.OnClickListener() {           
            @Override
            public void onClick(View arg0) {               
                if(mp.isPlaying()){
                    if(mp!=null){
                        mp.pause();
                        wv.startAnimation(animFadeOut);
                        tes.startAnimation(animFadein);
                        // Changing button image to play button
                        btnPlay.setImageResource(R.drawable.btn_play);
                    }
                }else{
                    // Resume song
                    if(mp!=null){
                        mp.start();
                        wv.loadUrl(content);
                        wv.startAnimation(animFadein);
                        tes.startAnimation(animFadeOut);
                        // Changing button image to pause button
                        btnPlay.setImageResource(R.drawable.btn_pause);
                    }
                }
               
            }
        });
    }

    public void onBackPressed() {
        mp.stop();
        finish();
    }

    @Override
    public void onAnimationStart(Animation animation) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        // TODO Auto-generated method stub
    }

}
File Pendukung
Buat Folder bernama 'anim'
Berikut file 'fade_in.xml'
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true" >

    <alpha
        android:duration="1000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />

</set>

Berikut file 'fade_out.xml'
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true" >

    <alpha
        android:duration="1000"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="0.0" />

</set>

Simpan file 'aku.html'  pada folder assets
Download di sini

Simpan file 'akusukacaramu.mpe' pada folder raw
Download di sini


Button Play
Download di sini
Button Pause
di sini
Image pause
di sini
Image pause pressed
di sini
Image play
di sini
Image play press
di sini


Text To Speech
Layout
 <?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:background="#ffffff"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="15dip"
        android:text="Text To Speech"
        android:textColor="#0587d9"
        android:textSize="26dip"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:layout_marginTop="20dip"
        android:hint="Enter some text to speak" />

    <Button
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="Speak Out" />

</LinearLayout>

Java
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class TTSActivity extends Activity implements OnInitListener {
    /** Called when the activity is first created. */
    private TextToSpeech tts;
    private Button btnSpeak;
    private EditText txtText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tts);
        tts = new TextToSpeech(this, this);
        btnSpeak = (Button) findViewById(R.id.btnSpeak);
        txtText = (EditText) findViewById(R.id.txtText);
        // button on click event
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                speakOut();
            }
        });
    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    public void onInit(int status) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.US);
            // tts.setPitch(5); // set pitch level
            // tts.setSpeechRate(2); // set speech speed rate
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "Language is not supported");
            } else {
                btnSpeak.setEnabled(true);
                speakOut();
            }
        } else {
            Log.e("TTS", "Initilization Failed");
        }
    }

    private void speakOut() {
        // TODO Auto-generated method stub
        String text = txtText.getText().toString();
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}

Minggu, 26 April 2015

Contoh Aplikasi Dialog

Layout Main
 <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"
    tools:context=".HitungBangun" >

    <Button
        android:id="@+id/btnBangunDatar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Bangun Datar"
        tools:ignore="HardcodedText" />

</RelativeLayout>

Layout Segitiga
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical" >

    <EditText
        android:id="@+id/txtSisi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Sisi"
        android:inputType="numberDecimal"
        tools:ignore="HardcodedText" >

        <requestFocus />
    </EditText>

</LinearLayout>

Class MainActivity
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    Button buttonBangunDatar;
    CharSequence jenisBangunDatar[]={"Segitiga","Persegi"};
    Context context=this;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
buttonBangunDatar=(Button)findViewById(R.id.btnBangunDatar);
      
        buttonBangunDatar.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dialogBangunDatar();
            }
        });
    }

    public void dialogBangunDatar(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
      
        builder.setTitle("Bangun Datar");
        builder.setItems(jenisBangunDatar,new DialogInterface.OnClickListener() {
          
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if(jenisBangunDatar[arg1].equals("Segitiga")){
                    LayoutInflater inflater=getLayoutInflater();
                    RumusActivity.hitungSegitiga(context, inflater);
                }else{
                    //tampil error message. lihat materi pertemuan 10
                }
            }
        } );
      
        AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }
    
  
}

Class RumusActivity
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

public class RumusActivity {
   
      public static void hitungSegitiga(final Context context, LayoutInflater inflater){
            
            AlertDialog.Builder builder=new AlertDialog.Builder(context);
           
            final View viewSegitiga=inflater.inflate(R.layout.activity_rumus_segitiga, null);
           
            builder.setTitle("Segitiga");
            builder.setView(viewSegitiga);
           
            builder.setPositiveButton("Luas", new DialogInterface.OnClickListener() {
               
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    EditText alas=(EditText)viewSegitiga.findViewById(R.id.txtAlas);
                    EditText tinggi=(EditText)viewSegitiga.findViewById(R.id.txtTinggi);
       
                    double a=Double.parseDouble(alas.getText().toString());
                    double t=Double.parseDouble(tinggi.getText().toString());
                   
                    double luas=a*t/2;
                   
                    RumusActivity.hasil("Luas", luas, context);
                }
            });
           
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
               
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    // TODO Auto-generated method stub
                    arg0.cancel();
                }
            });
           
            AlertDialog alertDialog=builder.create();
            alertDialog.show();
        }

public static void hasil(String title,double hasil,Context context){
            AlertDialog.Builder builder=new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(hasil+"");
            builder.setNeutralButton("Oke", new DialogInterface.OnClickListener() {
               
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.cancel();
                }
            }).create().show();
        }
}