0% found this document useful (0 votes)
39 views

Laporan Praktikum Mobile Application Development: Share Preference

This document summarizes a student's report on a mobile application development practical involving shared preferences in Android. The practical had two parts: 1. Creating an Android project to store and retrieve user data like name and address using shared preferences. This involved designing an XML layout with fields to input data and buttons to save and retrieve, and writing Java code to save, retrieve and display the data. 2. Designing an XML layout for a login screen and writing Java code to save username and password to shared preferences and autofill the fields on future launches. This demonstrated using shared preferences to save login credentials.

Uploaded by

Hendra Chua
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Laporan Praktikum Mobile Application Development: Share Preference

This document summarizes a student's report on a mobile application development practical involving shared preferences in Android. The practical had two parts: 1. Creating an Android project to store and retrieve user data like name and address using shared preferences. This involved designing an XML layout with fields to input data and buttons to save and retrieve, and writing Java code to save, retrieve and display the data. 2. Designing an XML layout for a login screen and writing Java code to save username and password to shared preferences and autofill the fields on future launches. This demonstrated using shared preferences to save login credentials.

Uploaded by

Hendra Chua
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

LAPORAN

PRAKTIKUM MOBILE APPLICATION


DEVELOPMENT
Share Preference

HENDRA PRABOWO
1355301041

PROGRAM STUDI TEKNIK INFORMATIKA


POLITEKNIK CALTEX RIAU
2015
PEKANBARU
A. Tujuan

Pada praktikum kali ini mahasiswa diharapkan memahami proses penyimpanan data
di android dan memahami mekanisme Shared Preference
B. Praktikum
Latihan 1 : Share Preference
-

Buatlah sebuah android project baru bernama SharePreference


Buat sebuah file XML dengan nama activity_main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0f0f">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip">
<EditText
android:hint="nama"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/nama" />
<EditText
android:hint="alamat"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/alamat" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:text="simpan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/simpan"
android:layout_weight="0.5" />
<Button
android:text="batal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/batal"
android:layout_weight="0.5" />
</LinearLayout>
</LinearLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/list_data" />
</LinearLayout>

Edit main_activity.java hingga menyerupai dibawah ini

package com.example.sharepreference;
import java.util.HashMap;
import java.util.Map;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.app.AlertDialog;
android.content.Context;
android.content.DialogInterface;
android.content.SharedPreferences;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.AdapterView;
android.widget.AdapterView.OnItemClickListener;
android.widget.ArrayAdapter;
android.widget.Button;
android.widget.EditText;
android.widget.ListView;

public class MainActivity extends Activity {


public static final String KEY_NAMA = "nama";
public static final String KEY_ALAMAT = "alamat";
static String NM_PREF = "simple-shared"; // buat Nama
SharedPreferences sharedPref; // databasenya
SharedPreferences.Editor editSharedPref; // querynya
EditText nama, alamat;
Button simpan, batal;
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = getSharedPreferences(NM_PREF, Context.MODE_PRIVATE);
nama = (EditText) findViewById(R.id.nama);
alamat = (EditText) findViewById(R.id.alamat);
simpan = (Button) findViewById(R.id.simpan);
batal = (Button) findViewById(R.id.batal);
list = (ListView) findViewById(R.id.list_data);
simpan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (nama.getText().toString().trim().length() > 1 &&
alamat.getText().toString().trim().length() > 1){

simpanData(nama.getText().toString().trim(),
alamat.getText().toString().trim());
}
}
});
LoadData();
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
onClickList(pos);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
void deleteData(String key, boolean all) {
editSharedPref = sharedPref.edit();
if (!all){
editSharedPref.remove(key);
}
else{
editSharedPref.clear();
editSharedPref.commit();
}
}
AlertDialog alert;
public void onClickList (final int pos) {
final CharSequence[] items = new String[] {"update", "delete", "delete all"};
alert = new
AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("Pilihan").setSingleChoi
ceItems(items, 0, new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int item) {
switch(item) {
case 0:
break;
case 1:
String[] res = isiList[pos].split("#");
deleteData(res[0], false);
break;
case 2:
String[] res2 = isiList[pos].split("#");
deleteData(res2[0], false);
break;
}

alert.cancel();
LoadData();
}}).create();
alert.show();
}
String[] isiList;
Map<String, String> data = new HashMap<String, String>();
@SuppressWarnings("unchecked")
void LoadData() {
data = new HashMap<String, String>();
data = (Map<String, String>) sharedPref.getAll();
isiList = new String[data.size()];
sharedPref.getString(KEY_NAMA, "");
sharedPref.getString(KEY_ALAMAT, "");
int j = 0;
for (String s : data.keySet()) {
isiList[j] = s + "#" + data.get(s);
j++;
}
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, isiList));
}
@SuppressWarnings("unchecked")
void simpanData(String nama, String alamat) {
data = new HashMap<String, String>();
data = (Map<String, String>) sharedPref.getAll();
int size = data.size();
editSharedPref = sharedPref.edit();
String datafull = nama + "#" + alamat;
data = new HashMap<String, String>();
size++;
data.put(Integer.toString(size), datafull);
for (String s : data.keySet()) {
editSharedPref.putString(s,
data.get(s));
}
editSharedPref.commit();
LoadData();
}
}

Latihan 2 : SharePrefLogin
- Desain lah file activity_main.xml
<RelativeLayout
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" >

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="20dp"
android:layout_marginTop="50dp"
android:background="@android:color/darker_gray" >
<TextView
android:id="@+id/tvsign"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:text="Header"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/black" />
<TextView
android:id="@+id/tvusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/tvsign"
android:layout_margin="10dp"
android:text="Username"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#ff0f0f"
android:textStyle="bold" />
<EditText
android:id="@+id/etusername"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvusername"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:inputType="none" />
<TextView
android:id="@+id/tvpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etusername"
android:layout_margin="10dp"
android:text="Password"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#ff0f0f"
android:textStyle="bold" />
<EditText
android:id="@+id/etpass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvpassword"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:inputType="textPassword" />
<CheckBox

android:id="@+id/chksingin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etpass"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Tetap Masuk"
android:textColor="@android:color/black" />
<Button
android:id="@+id/btnsignin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/chksingin"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:background="@drawable/ic_launcher"
android:text="Sign"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/white" >
</Button>
<Button
android:id="@+id/btnclear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/chksingin"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/btnsignin"
android:background="@drawable/ic_launcher"
android:text="Clear Data"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/black" >
</Button>
</RelativeLayout>
</RelativeLayout>

Edit file Main_Activity.java sehingga seperti dibawah ini

package com.example.sharepreflogin;
import
import
import
import
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.content.Context;
android.content.SharedPreferences;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.CheckBox;
android.widget.EditText;
android.widget.Toast;

public class MainActivity extends Activity {


Button btnSignedIn, btnClearData;
CheckBox chkSignedIn;

EditText etUsername, etPassword;


private static final String PREFRENCES_NAME = "myprefrences";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// inisialisasiobjek
etUsername = (EditText) findViewById(R.id.etusername);
etPassword = (EditText) findViewById(R.id.etpass);
chkSignedIn = (CheckBox) findViewById(R.id.chksingin);
SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME,
Context.MODE_PRIVATE);
String name = settings.getString("name", "");
String password = settings.getString("pwd", "");
etUsername.setText(name);
etPassword.setText(password);
btnSignedIn = (Button) findViewById(R.id.btnsignin);
btnSignedIn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strName = etUsername.getText().toString();
String strPass = etPassword.getText().toString();
if (null == strName || strName.trim().length() == 0) {
etUsername.setError("Enter Your Name");
etUsername.requestFocus();
} else if (null == strPass || strPass.trim().length() == 0) {
etPassword.setError("Enter Your Password");
etPassword.requestFocus();
} else {
if (chkSignedIn.isChecked()) {
showToast("User Name and Password
Saved!!!");
SharedPreferences settings =
getSharedPreferences( PREFRENCES_NAME, Context.MODE_PRIVATE);
settings.edit().putString("name", strName)
.putString("pwd", strPass).commit();
showToast("Restart App And see it works!!!");
} else {
showToast("Tick keep me logged in!!!");
}}
} });
btnClearData = (Button) findViewById(R.id.btnclear);
btnClearData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
etUsername.setText("");
etUsername.requestFocus();
etPassword.setText("");
chkSignedIn.setChecked(false);
SharedPreferences settings = getSharedPreferences(
PREFRENCES_NAME, Context.MODE_PRIVATE);
settings.edit().clear().commit();

} });
}
private void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
}

Hasil output :
Latihan 1 :

Latihan 2:

You might also like