2016-07-26 48 views
0

我想在我們的應用程序上使用Icepick庫來保存和恢復電話輪換上的捆綁包,但庫文檔我找不到好的提示保存和類實現了@Parcel註釋這是簡單的類,我發現○頁Android使用Icepick庫來保存/恢復捆綁

Example類:

@Parcel 
public class Example { 
    String name; 
    int age; 

    public Example(){ /*Required empty bean constructor*/ } 

    public Example(int age, String name) { 
     this.age = age; 
     this.name = name; 
    } 

    public String getName() { return name; } 
    public int getAge() { return age; } 

    public String setName(String name) { this.name = name; } 
    public int setAge(int age) { this.age = age; } 
} 

ExampleBundler類:

public class ExampleBundler implements Bundler<Object> { 
    @Override 
    public void put(String s, Object example, Bundle bundle) { 
     bundle.putParcelable(s, Parcels.wrap(example)); 
    } 

    @Override 
    public Object get(String s, Bundle bundle) { 
     return Parcels.unwrap(bundle.getParcelable(s)); 
    } 
} 

好吧,現在我該如何使用Activity

這是我簡單的代碼,我試圖挽救和恢復

public class MainActivity extends BaseActivity { 

    /* @State(ExampleBundler.class) String message; */ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Example example = new Example(); 
    example.setName = "HELLO WORLD"; 
    example.setAge = 99; 
    } 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
    } 

    public void onRestoreInstanceState(Bundle inState) { 
    } 
} 

你能解決我的代碼?感謝推進

+0

您還需要調用'Icepick.restoreInstanceState(這一點,savedInstanceState)'中的onCreate和'Icepick.saveInstanceState(這一點,outstate)在' onSaveInstanceState –

+0

@SahithReddy,我該如何狐狸這一行:'@State(ExampleBundler.class)字符串消息;' –

+0

如果它只是一個字符串,你甚至不需要自定義捆綁器,你可以使用@State。自定義捆綁器是,如果你想保存整個對象連同可parcelable –

回答

2

要解決你的代碼,所述捆綁必須實現的例子類不是一般的對象類,以便改變

public class ExampleBundler implements Bundler<Object> { 
    @Override 
    public void put(String s, Object example, Bundle bundle) { 
     bundle.putParcelable(s, Parcels.wrap(example)); 
    } 

    @Override 
    public Object get(String s, Bundle bundle) { 
     return Parcels.unwrap(bundle.getParcelable(s)); 
    } 
} 

這個

public class ExampleBundler implements Bundler<Example> { 
    @Override 
    public void put(String s, Example example, Bundle bundle) { 
     bundle.putParcelable(s, Parcels.wrap(example)); 
    } 

    @Override 
    public Example get(String s, Bundle bundle) { 
     return Parcels.unwrap(bundle.getParcelable(s)); 
    } 
} 

然後,你必須添加@State(ExampleBundler.class) Example example;到您的活動的頂部。在您的onCreate添加Icepick.restoreInstanceState(this, savedInstanceState)並在onSavedInstanceState添加Icepick.saveInstanceState(this,outstate)

Icepick documentationparceler