PDF 2
PDF 2
PDF 2
Beta 0.8.6
1
Android Studio
1. Install Android Studio
2. Update ke jdk 7
3. Copy master . grandle di C:\Users\jessica
4. Copy master folder android-sdk di C:\Users\
jessica\AppData\Local\Android
2
Create Emulator
• Buka android studio
• Menu tools, android, AVDManager, create
• Berikut window pengaturan untuk emulator yang akan dibuat:
• Kemudian Start,Launch
3
Struktur folder
• Code java diletakkan di
dalam folder java
• Untuk tampilan diletakkan di
dalam folder layout
• Untuk menu dari halaman
diletakkan di dalam folder
menu
• Image dalam project
diletakkan dalam folder
drawable
• String dalam tampilan di
simpan dalam folder values
4
Membuat Page baru
• Klik kanan di com.example.jessica.myapplication
• New, Activity, Blank Activity
• Maka akan terbentuk file .java, .xml (layout dan menu) dan
tambahan code di AndroidManifest.xml
5
Transition, Put Extra,
UploadPhoto & Time Ago
Android Native
6
Put Extra
• Put extra digunakan untuk melempar sebuah variabel ke halaman
berikutnya. Yang perlu diperhatikan adalah penamaan dari variabel
yang akan digunakan di halaman berikutnya.
• Cara penggunaan: (Misal class A akan link ke class B. )
1. Pada halaman class A. Result adalah string yang akan dilempar.
datauser adalah nama yang akan digunakan di class B.
Intent i = new Intent(A.this, B.class);
i.putExtra(“datauser", result);
startActivity(i);
• Cara pemanggil nilai dari put extra halaman sebelumnya.
1. Pada halaman class B.
Intent i = getIntent();
result = i.getStringExtra(" datauser ");
7
Parse Array
• Jika yang dikirim melalui put extra merupakan public class ParseArrayUser {
bentuk json. Cth yang dikirim adalah data user: UserLoginData userdata;
countryid, firstname, prof_id. Berikut code nya:
public UserLoginData parsingarray (String result){
userdata = new UserLoginData();
1. Buat entity untuk menampung nilai. Ketik source if (result != null) {
code di bawah: try {
JSONArray jsonObj = new JSONArray(result);
JSONObject contacts = null;
package com.dataEntity.campaignapp;
contacts=jsonObj.getJSONObject(0);
public class UserLoginData {
userdata.setFirstname(contacts.getString("firstname"));
private String firstname;
userdata.setProf_id(contacts.getString("prof_id"));
private String prof_id; userdata.setCountry id(contacts.getString(“countryid"));
private String countryid; return userdata;
} } catch (JSONException e) {
e.printStackTrace();
return null;}
Gunakan getter and setter: klik kanan, generate,
} else {
getter and setter. Maka akan tambah code untuk
Log.e("ServiceHandler", "Couldn't get any data from
set and get. putextra");
return null; }
2. Buat class dengan nama ParseArrayUser. }
}
8
3. Pada MyActivity.java:
UserLoginData userdata;
String result;
Intent i = getIntent();
result = i.getStringExtra("datasession");
ParseArrayUser test=new ParseArrayUser();
userdata=test.parsingarray(result);
Country = userdata.getCountryid().toString()
userdata.setCountryid(“1191”)
9
Entity to String
• Cara untuk mengubah sebuah entity menjadi string
sehingga bisa digunakan untuk put extra.
• Pada MyActivity.java
UserEntitytoString session= new
public class UserEntitytoString {
UserEntitytoString();
public String UserEntitytoString(UserLoginData userdata) result =
{ session.UserEntitytoString(userdata);
JSONObject jo = new JSONObject();
try {
jo.put("prof_id", userdata.getProf_id().toString());
jo.put("firstname",
userdata.getFirstname().toString());
jo.put("countryid",
userdata.getCountryid().toString());
} catch (JSONException e) {
e.printStackTrace();
}
10
Transition
• Transition untuk mengatur animasi saat pindah halaman:
1. Code di file MyActivity.java.
Intent i = new Intent(MyActivity.this, Home.class);
i.putExtra("datasession", result);
startActivity(i);
MyActivity.this.overridePendingTransition(android.R.anim.slide_in_left,
android.R.anim.slide_out_right);
12
Upload foto
builder2.setItems(optionsGallery, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (optionsGallery[item].equals("From Internal Memory")){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}else if(optionsGallery[item].equals("From External Memory")){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}else if (optionsGallery[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder2.show();
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
13
Upload foto
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
14
Upload foto
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize=7;
Bitmap thumbnail;
thumbnail = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
15
Upload foto
FileOutputStream fos = null;
try {
bitmap=thumbnail;
viewImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
pDialog.dismiss();
}
f.delete();
} catch (Exception e) {
e.printStackTrace();
pDialog.dismiss();
}
16
Upload foto
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
pathImage=picturePath;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize=7;
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath,bitmapOptions));
Log.w("path of image from gallery......******************.........", picturePath + "");
viewImage.setImageBitmap(thumbnail);
bmpWidth = thumbnail.getWidth();
bmpHeight = thumbnail.getHeight();
bitmap=thumbnail;
viewImage.setImageBitmap(bitmap);
viewImage.setTag(picturePath);
((EditText) findViewById(R.id.changephoto)).setText("1");
}
pDialog.dismiss(); }
pDialog.dismiss(); }
17
Upload foto
• Code di atas sudah menampilkan foto dengan menggunakan Image view.
Foto dapat diambil dari camera device atau library yang terdiri dari
internal memory atau external memory.
• Kemudian pada button save dibuat code onclick sebagai berikut:
if(v.getId() == R.id.button_save){
String path = pathImage;
new ImageUploaderTask().execute(new String[]{path});
}
18
Upload foto
private class ImageUploaderTask extends AsyncTask<String, Integer, String> {
protected void onPreExecute(){
simpleWaitDialog = ProgressDialog.show(ProfileEdit.this, "Uploading Image", "Please wait...");
}
19
Upload foto
protected void onPostExecute(String result){
if (result != null) {
try {
JSONArray jsonObj = new JSONArray(result);
JSONObject contacts = null;
contacts = jsonObj.getJSONObject(0);
dataprof.setStatus(contacts.getString("status"));
if(contacts.getString("status").equals("sukses")){
userdata.setFirstname(contacts.getString("firstname"));
userdata.setCountryid(contacts.getString("countryid"));
userdata.setAvatar(contacts.getString("avatar"));
UserEntitytoString session= new UserEntitytoString();
result_new = session.UserEntitytoString(userdata);
Intent aftersave = new Intent(ProfileEdit.this, Setting.class);
aftersave.putExtra("datasession", result_new);
startActivity(aftersave);
ProfileEdit.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
simpleWaitDialog.dismiss();
}catch (Exception e){
Log.d("Background Task",e.toString());
}
}else {
simpleWaitDialog.dismiss();
}
}
}
20
Upload foto
• Buat class baru yang diberi nama ImageUploaderUtilityProfile.java. Berikut code pada halaman tersebut.
String hasil_upload="";
try {
hasil_upload = doUploadinBackground(getBytesFromFile(new File(fileNameToUpload)), fileNameToUpload,
dataeditprof);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return hasil_upload;
}
21
Upload foto
static String doUploadinBackground(final byte[] imageData, String filename, String data_edit) throws Exception{
String responseString = null;
PostMethod method;
Constanta cons= new Constanta();
UserRegisterData user_data;
user_data = new UserRegisterData();
user_data = parsingarrayreg(data_edit);
client.executeMethod(method);
responseString = method.getResponseBodyAsString();
method.releaseConnection();
Log.e("httpPost", "Response status: " + responseString);
return responseString;
}
22
Upload foto
public static UserRegisterData parsingarrayreg (String result){ public static byte[] getBytesFromFile(File file) throws IOException {
UserRegisterData userdata; InputStream is = new FileInputStream(file);
userdata = new UserRegisterData(); long length = file.length();
if (length > Integer.MAX_VALUE) {
if (result != null) { // File is too large
try { }
JSONArray jsonObj = new JSONArray(result);
JSONObject contacts = null;
byte[] bytes = new byte[(int)length];
contacts=jsonObj.getJSONObject(0);
userdata.setProfId(contacts.getString("ProfId"));
int offset = 0;
userdata.setName(contacts.getString("Name"));
int numRead = 0;
userdata.setCountry(contacts.getString("Country"));
while (offset < bytes.length
userdata.setSex(contacts.getString("Sex"));
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
userdata.setDescription(contacts.getString("Description"));
userdata.setStatusLoad(contacts.getString("StatusLoad")); offset += numRead;
userdata.setDob(contacts.getString("Dob")); }
userdata.setAvatar(contacts.getString("Avatar"));
return userdata; if (offset < bytes.length) {
throw new IOException("Could not completely read file
} catch (JSONException e) { "+file.getName());
e.printStackTrace(); }
return null;
} is.close();
} else { return bytes;
Log.e("ServiceHandler", "Couldn't get any data from putextra"); }
return null;
}
} }
23
Rotate Foto
• Buat 4 button untuk rotate (rotate 90°, rotate 180°, 270°,360°) . Berikut source code onclick pada masing2
button.
• Untuk 180, 270 dan 360 hanya diganti pada bagian yg berwarna merah, diubah sesuai derajatnya.
24
Time Ago
1. Buat class untuk perhitungan waktu, diberi nama TimeAgo.
import android.content.Context;
import android.text.format.Time;
25
Time Ago
// TODO: localize
final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "just now";
} else if (diff < 2 * MINUTE_MILLIS) {
return "a minute ago";
} else if (diff < 50 * MINUTE_MILLIS) {
return diff / MINUTE_MILLIS + " minutes ago";
} else if (diff < 90 * MINUTE_MILLIS) {
return "an hour ago";
} else if (diff < 24 * HOUR_MILLIS) {
return diff / HOUR_MILLIS + " hours ago";
} else if (diff < 48 * HOUR_MILLIS) {
return "yesterday";
} else {
return diff / DAY_MILLIS + " days ago";
}
}
}
26
Time Ago
2. Buat class DataLabel untuk mengubah tipe data tanggal.
}
}
27
Time Ago
3. Source pada main activity.
28
Selamat mencoba
29