Nothing Special   »   [go: up one dir, main page]

PDF 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Android Studio

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);

– dimana userdata merupakan entity UserLogindata, untuk menaruh nilai dan


mendapatkan nilai berikut source codeny:

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();
}

JSONArray ja = new JSONArray();


ja.put(jo);
return ja.toString();
}
}

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);

2. Code di layout Home.xml


<?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="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.jessica.campaignapp.ContactUs">
11
Upload foto
• Pada ProfileEdit.java. (code onclick button edit pofile)

public void EditProfileOnClick(View vw){


final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

AlertDialog.Builder builder = newAlertDialog.Builder(ProfileEdit.this);


builder.setTitle("Edit Photo");
builder.setItems(options, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int item) {


if (options[item].equals("Take Photo")) {
Intent intent= newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
String name_temp = formattedDate+"temp.jpg";

File f = new File (android.os.Environment.getExternalStorageDirectory(),name_temp );


intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);

} else if (options[item].equals("Choose from Gallery")) {


final CharSequence[] optionsGallery = { "From Internal Memory","From External Memory","Cancel" };
AlertDialog.Builder builder2 = new AlertDialog.Builder(ProfileEdit.this);
builder2.setTitle("Choose from Gallery");

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) {

super.onActivityResult(requestCode, resultCode, data);


pDialog = new ProgressDialog(ProfileEdit.this);
pDialog.setMessage("Loading ....");
pDialog.setCancelable(false);
pDialog.show();

if (resultCode == RESULT_OK) {
if (requestCode == 1) {

File f = new File(android.os.Environment.getExternalStorageDirectory().toString());


Calendar c2 = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c2.getTime());
String name_temp2 = formattedDate+"temp.jpg";
for (File temp : f.listFiles()) {
if (temp.getName().equals(name_temp2)) {
f = temp;
break;
}
}

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

ContextWrapper cw = new ContextWrapper(getApplicationContext());


// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,String.valueOf(System.currentTimeMillis()) +"profile.jpg");

15
Upload foto
FileOutputStream fos = null;
try {

fos = new FileOutputStream(mypath);

thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, fos);


fos.close();
viewImage.setTag(mypath.getPath());
pathImage=mypath.getPath();

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...");
}

protected String doInBackground(String... params) {


editdata = new UserRegisterData();
editdata.setProfId(userdata.getProf_id().toString());
editdata.setName(((EditText) findViewById(R.id.edit_firstname)).getText().toString());
editdata.setDob(((EditText) findViewById(R.id.edit_dob)).getText().toString());
editdata.setCountry(((EditText) findViewById(R.id.edit_country)).getText().toString());
editdata.setSex(((EditText) findViewById(R.id.edit_gender)).getText().toString());
editdata.setDescription(((EditText) findViewById(R.id.edit_desc)).getText().toString());
editdata.setStatusLoad(((EditText) findViewById(R.id.changephoto)).getText().toString());
editdata.setAvatar(userdata.getAvatar().toString());
String kirimdata = DataEntitytoStringEdit(editdata);

ImageUploaderUtilityProfile test=new ImageUploaderUtilityProfile();


String hsl_upload=test.uploadSingleImage(params[0], kirimdata);
return hsl_upload;
}

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.

public class ImageUploaderUtilityProfile {

public String uploadSingleImage(String fileNameToUpload, String dataeditprof){

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);

method = new PostMethod(cons.baseurl+"mobileandroid/uploadprofileandro");

org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();


client.getHttpConnectionManager().getParams().setConnectionTimeout(100000);

FilePart photo = new FilePart("fileToUpload", new ByteArrayPartSource(filename, imageData));


photo.setContentType("image/jpeg");
photo.setCharSet(null);
String s = new String(imageData);
Part[] parts = {
new StringPart("profileid", user_data.getProfId().toString()),
new StringPart("firstname", user_data.getName().toString()),
new StringPart("country_id", user_data.getCountry().toString()),
new StringPart("sex", user_data.getSex().toString()),
new StringPart("dob", user_data.getDob().toString()),
new StringPart("description", user_data.getDescription().toString()),
new StringPart("status_load", user_data.getStatusLoad().toString()),
new StringPart("avatar", user_data.getAvatar().toString()),
photo
};

HttpMethodParams htp=new HttpMethodParams();


htp.setParameter("fileToUpload",photo);
method.setParams(htp);
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

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.

public void onClickPhotoProfile(View v){


if(v.getId() == R.id.rotate) {
try{
File imgFile = new File(viewImage.getTag().toString());
if(imgFile.exists()){
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),bitmapOptions);
ImageFilters imgFilter = new ImageFilters();
Bitmap xxx=myBitmap;
saveBitmap(imgFilter.applyRotate(xxx,"90"),"rotate" );
Button bt=(Button)findViewById(R.id.rotate180);
v.setVisibility(View.GONE);
bt.setVisibility(View.VISIBLE);
}
}catch (Exception ex){
ex.printStackTrace();
}
}

• 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;

public class TimeAgo {


private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;

public String getTimeAgo(long time ) {


if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}

Time tm = new Time(); tm.setToNow();


long now=(tm.toMillis(false));

if (time > now || time <= 0) {


return null;
}

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.

public class DateLabel {


public long dateToLong(String tanggal) {
java.util.Date today = new java.util.Date();
//java.sql.Timestamp ts1 = new java.sql.Timestamp(today.getTime());
java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf(tanggal);

// long tsTime1 = ts1.getTime();


long tsTime2 = ts2.getTime();
return tsTime2;

}
}
27
Time Ago
3. Source pada main activity.

DateLabel dl=new DateLabel();


long dataWaktu= dl.dateToLong(item.get("commdate"));
TimeAgo tg=new TimeAgo();
teg.setText(tg.getTimeAgo(dataWaktu));

28
Selamat mencoba

29

You might also like