Bu dersimizde gson kütüphanesini generic data type’larda nasıl kullanacağımızı ve generic data type tipindeki nesneleri sharedpreference dosyamıza nasıl yazıp okuyacağımızı öğreneceğiz.
Generic data type kavramını kısaca özetleyelim. Farklı veri tipleri ile çalışan bir algoritmanın,her veri tipi için ayrı ayrı yazılmasını engeller. Yazılacak algoritma tek bir çatı altında toplanarak farklı veri tiplerinin bu çatıyı(class,sınıf) kullanması hem tasarım sadeliğini,hem de yazılım geliştirme hızını ciddi oranda arttırmaktadır. Bizim örneğimizde TumPersonel çatısı oluşturulmuştur. Bunun içinde sadece Calisan tipinde nesneler değil, farklı sınıfların nesneleri de saklanabilir.
Generic tipleri dosyamıza kaydetme kodu şu şekildedir:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Calisan yeniCalisan=calisanOlustur(); TumPersonel<Calisan> personel=new TumPersonel<>(); personel.setObject(yeniCalisan); SharedPreferences sharedPreferences=getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); Gson gson=new Gson(); Type type=new TypeToken<TumPersonel<Calisan>>(){}.getType(); String jsonStr=gson.toJson(personel, type); editor.putString("generic_type_key", jsonStr); editor.apply(); |
Bu kodda öncelikle yeni bir çalışan nesnesi oluşturuyoruz. Ve bu nesneyi generic type olan TumPersonel’e set ediyoruz. Şu durumda personel generic typenın içinde bir tane calisan nesnesi bulunuyor.
Şu durumda personel nesnesini gson ile toJson dediğimizde hata çıkacaktır.
1 |
gson<span class="pl-k">.</span>toJson(personel); // May not serialize foo.value correctly |
Bu nesnenin tipini(type değerini) düzgün bir şekilde belirtmek için Type sınıfını kullandık.
1 |
Type type=new TypeToken<TumPersonel<Calisan>>(){}.getType(); |
Bu sayede nesnemizi düzgün bir şekilde serialization işlemine tabi tutup dosyamıza json stringini eklemiş oluyoruz.
Bu verileri yine gson kütüphanesini kullanıp deserialization işlemine tabi tutup kullanıcıya gösteriyoruz.
1 2 3 4 5 6 7 8 9 |
SharedPreferences sharedPreferences=getPreferences(MODE_PRIVATE); String jsonStr=sharedPreferences.getString("generic_type_key", ""); Gson gson=new Gson(); Type type=new TypeToken<TumPersonel<Calisan>>(){}.getType(); TumPersonel<Calisan> calisan= gson.fromJson(jsonStr, type); Calisan calisanEleman=calisan.getObject(); calisanGoster(calisanEleman); |
Bu derste yazılan kodlar aşağıda belirtilmiştir. SharedPreferencewithGson projesinin bitmiş son halini buradaki linkten indirebilirsiniz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
public class MainActivity extends AppCompatActivity { private TextView tvData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvData= (TextView) findViewById(R.id.data); } public void saveCustomClassObject(View view) { Calisan calisan=calisanOlustur(); SharedPreferences sharedPreferences=getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); Gson gson=new Gson(); String jsonStr= gson.toJson(calisan, Calisan.class); Log.i("emre", "Save: "+jsonStr); editor.putString("calisan_key", jsonStr); editor.apply(); } public void loadCustomClassObject(View view) { SharedPreferences sharedPreferences=getPreferences(MODE_PRIVATE); String jsonStr= sharedPreferences.getString("calisan_key", ""); Log.i("emre", "Load :" +jsonStr); Gson gson=new Gson(); Calisan calisan=gson.fromJson(jsonStr, Calisan.class); calisanGoster(calisan); } private void calisanGoster(Calisan calisan) { String goster= calisan.getIsim() + "\n" + calisan.getMeslek() + "\n" + calisan.getId() + "\n" + (calisan.getAktif() ? "Çalışıyor" : "Çalışmıyor") + "\n" + calisan.getGorev().toString(); tvData.setText(goster); } private Calisan calisanOlustur(){ Calisan calisan=new Calisan(); calisan.setIsim("Emre"); calisan.setMeslek("Mühendis"); calisan.setAktif(true); calisan.setId(150); calisan.setGorev(Arrays.asList("Yönetici", "Developer")); return calisan; } public void saveGenericType(View view) { Calisan yeniCalisan=calisanOlustur(); TumPersonel<Calisan> personel=new TumPersonel<>(); personel.setObject(yeniCalisan); SharedPreferences sharedPreferences=getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); Gson gson=new Gson(); Type type=new TypeToken<TumPersonel<Calisan>>(){}.getType(); String jsonStr=gson.toJson(personel, type); editor.putString("generic_type_key", jsonStr); editor.apply(); Log.i("emre", "Kaydedilen :"+jsonStr); } public void loadGenericType(View view) { SharedPreferences sharedPreferences=getPreferences(MODE_PRIVATE); String jsonStr=sharedPreferences.getString("generic_type_key", ""); Gson gson=new Gson(); Type type=new TypeToken<TumPersonel<Calisan>>(){}.getType(); TumPersonel<Calisan> calisan= gson.fromJson(jsonStr, type); Calisan calisanEleman=calisan.getObject(); calisanGoster(calisanEleman); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/pageLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="20dp" tools:context="com.example.emrealtunbilek.sharedprefereneswithgson.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Calisan Sınıf Nesnesi" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:onClick="saveCustomClassObject" android:text="KAYDET"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="loadCustomClassObject" android:text="GETİR"/> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Generic Type Nesnesi" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:onClick="saveGenericType" android:text="KAYDET"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="loadGenericType" android:text="GETİR"/> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/data" android:layout_marginTop="40dp" android:textSize="20sp" android:layout_gravity="center" android:text="DATA" android:textStyle="bold" /> </LinearLayout> |
1 2 3 4 5 6 7 8 9 10 11 12 |
public class TumPersonel<T> { private T object; public T getObject() { return object; } public void setObject(T object) { this.object = object; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import java.util.List; public class Calisan { private String isim; private String meslek; private Integer id; private List<String> gorev; private Boolean aktif; public String getIsim() { return isim; } public void setIsim(String isim) { this.isim = isim; } public String getMeslek() { return meslek; } public void setMeslek(String meslek) { this.meslek = meslek; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List<String> getGorev() { return gorev; } public void setGorev(List<String> gorev) { this.gorev = gorev; } public Boolean getAktif() { return aktif; } public void setAktif(Boolean aktif) { this.aktif = aktif; } } |