Mehmet Ethem SULAN :: Android :: Android SharedPreferences Sample

Android içinde SahredPreferences verileri tutumak için kullanışlı bir yapıdır. Emülatörde /data/data/com.share.preferance/shared_prefs/ethem.xml olarak bakabilirisniz. Bazı uygulamalarda datalarınızı xml olarak tutma ihtiyacı için geliştirilmiş bir yapıtır. Buraya boolean, string, int, long ve float gibi veri tiplerini ekleyebilirsiniz. Aşağıdaki kod ile her activity create edildiğinde önceki verileri siliyorum.

        shEditor=sharedPreferences.edit();
        shEditor.clear();
        shEditor.commit();


ethem.xml dosyasını export etmek için aşağıdaki resimde kırmızı alanı tıklayın.

İçerik te aşağıdaki gibidir.

SharePrefereanceActivity.java

package com.share.preferance;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SharePrefereanceActivity extends Activity {
	SharedPreferences sharedPreferences;
	SharedPreferences.Editor shEditor;
	Button button_save, button_show;
	static final private int share_pref_dialog = 1;
	StringBuilder stringBuilder;
	EditText editText_name, editText_age, editText_address;
	static int i=1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button_save=(Button) findViewById(R.id.button1_save);
        button_show=(Button) findViewById(R.id.button2_show);
        editText_name=(EditText) findViewById(R.id.editText1_name);
        editText_age=(EditText) findViewById(R.id.editText2_age);
        editText_address=(EditText) findViewById(R.id.editText3_address);
        
        stringBuilder=new StringBuilder();
//ethem isminde bir xml oluşturuyor ve .edit() mtodu ile ekleme,silme ve güncelleme izni veriyoruz.
        sharedPreferences=getSharedPreferences("ethem", Activity.MODE_PRIVATE);
        shEditor=sharedPreferences.edit();
//Bu metod ile daha önceki kayıtları siliyoruz.
        shEditor.clear();
        shEditor.commit();
        button_save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int age=0;
				String name=editText_name.getText().toString();
				if(editText_age.getText().toString().length()>0)
				{
				age=Integer.parseInt(editText_age.getText().toString());
				}
				String address=editText_address.getText().toString();
				if(name.length()>0 && age>0 && address.length()>0)
				{
				create_share_preferences(name, age, address);
				}else{
					Toast.makeText(getApplicationContext(), "Check your inputs", Toast.LENGTH_LONG).show();
				}
			}
		});
        
        
        button_show.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//BUtton tıklanınca onCreateDialog() metodu içindeki dialog açılıyor.
				showDialog(share_pref_dialog);
				
			}
		});
        
        
        
        
    }
	private String reterieve_share_preferences() {
//.xml içindeki bütün kayıtları stringbuildera atıyoruz.
		 Map<String, ?> all_record = sharedPreferences.getAll();
		 Set set=all_record.entrySet();
		 Iterator it=set.iterator();
		 while (it.hasNext()) {
			 	Map.Entry map =(Map.Entry)it.next();
				stringBuilder.append(map.getKey()+" : "+map.getValue()+"n");
				if(i%3==0)
				{
					stringBuilder.append("************n");
				}
				i++;
		}
		

		return stringBuilder.toString();
	}
	private void create_share_preferences(String name,int age, String address) {
//Girilen kayıtları xml olarak kayıdediyor.
		shEditor.putString("name", name);
        shEditor.putInt("age", age);
        shEditor.putString("address", address);
        shEditor.commit();
        editText_name.setText("");
        editText_age.setText("");
        editText_address.setText("");
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		
		Builder alBuilder;
		switch(id) {
		case (share_pref_dialog) :
			alBuilder = new AlertDialog.Builder(this);
			alBuilder.setTitle("Do you want to show all records").
			setCancelable(false).setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
//ok seçilirse toast ile ekranda gösteriyorum.
									Toast.makeText(getApplicationContext(), reterieve_share_preferences(), Toast.LENGTH_LONG).show();

								}
							}).setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();

								}
							});
		return alBuilder.create();
		}
		return super.onCreateDialog(id);

	}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TableLayout android:layout_width="fill_parent" android:id="@+id/tableLayout1" android:layout_height="wrap_content">
        <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Name :" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1"></TextView>
            <EditText android:id="@+id/editText1_name" android:layout_width="wrap_content" android:layout_height="wrap_content">
                <requestFocus></requestFocus>
            </EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView2" android:text="Age :"></TextView>
            <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:inputType="number" android:id="@+id/editText2_age"></EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView3" android:text="Address :"></TextView>
            <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:inputType="textPostalAddress" android:id="@+id/editText3_address"></EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow4" android:layout_width="wrap_content" android:layout_height="wrap_content">
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save Input" android:id="@+id/button1_save"></Button>
            <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Records" android:id="@+id/button2_show"></Button>
        </TableRow>
    </TableLayout>
</LinearLayout>

Bu arada com.share.preferance paket ismini yanlış yazmışım:)

Download SharePrefereance.zip

Comments

There is one comment for this post.

  1. tolgahan on Ekim 20, 2011 8:14 am

    çok iyi ama biraz da cok commet istiyoruz.

Write a Comment

Let me know what you think?