保存/恢复片段状态的android(Save/Restore fragments state and

2019-08-22 05:10发布

我试图创建一个使用杰克沃顿商学院的ViewPager库(应用程序在这里 )只使用图像的每个页面(类似Prix​​ing( 这里 )主屏幕)。 一切工作正常,除了在片段saveInstance。

在杰克沃顿商学院的例子,他存储在一个字符串变量文本,命名mContent,并在恢复的onCreate,但在我的情况,我该怎么办? 保存/恢复的位图? 任何客观的答案,将不胜感激!

我是很新的应用程序使用该片段,导致每一个例子,我看,只介绍的基本知识,以及它在更复杂的困难等。

PS。 如果它是有用的知道,我使用CirclePageIndicator。

当前片段代码在这里:

    public final class SpecialOfferFragment extends Fragment {

    private int imageResourceId;

    public static SpecialOfferFragment newInstance(int i) {

        //probably I'll use a bitmap(downloaded) as parameter instead of using static images
        SpecialOfferFragment fragment = new SpecialOfferFragment();

        fragment.imageResourceId = i;

        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // if ((savedInstanceState != null) { }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        ImageView image = new ImageView(getActivity());
        image.setImageResource(imageResourceId);
        image.setScaleType(ScaleType.FIT_XY);

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));

        layout.setGravity(Gravity.CENTER);
        layout.addView(image);

        return layout;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //smth to save here..
    }
}

在当前的应用程序的状态,我得到以下异常:

04-12 07:28:17.760: E/AndroidRuntime(31903): FATAL EXCEPTION: main 
04-12 07:28:17.760: E/AndroidRuntime(31903): java.lang.NullPointerException
04-12 07:28:17.760: E/AndroidRuntime(31903): at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1576)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1617)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:481)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.Activity.performSaveInstanceState(Activity.java:1113)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1188)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:2804)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.ActivityThread.handleStopActivity(ActivityThread.java:2862)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.ActivityThread.access$900(ActivityThread.java:127)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1175)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.os.Looper.loop(Looper.java:137)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at android.app.ActivityThread.main(ActivityThread.java:4511)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at java.lang.reflect.Method.invokeNative(Native Method)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at java.lang.reflect.Method.invoke(Method.java:511)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
04-12 07:28:17.760: E/AndroidRuntime(31903):    at dalvik.system.NativeStart.main(Native Method)

发生这种情况时,我暂停/停止含有本片断,就像推Home按钮的活动。

**

编辑的代码:

**

 public class MainMenu extends FragmentActivity {

    //private List<CategoriesHolder> categoriesList = new ArrayList<CategoriesHolder>();
    //private CategoriesAdapter categoriesAdapter = null;
    //private GridView gv_mainmenu_categories;

    SpecialOfferFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_mainmenu);

        linkUI();
        setAction();

        // just for testing
        String[] imagesUrls = null;

        mAdapter = new SpecialOfferFragmentAdapter(getSupportFragmentManager(),
                this, imagesUrls);

        //categoriesAdapter = new CategoriesAdapter(this, categoriesList);

        // used for Categories GridView
        //gv_mainmenu_categories.setAdapter(categoriesAdapter);

        // used for ViewPager
        mPager.setAdapter(mAdapter);
        mIndicator.setViewPager(mPager);

    }

    private void linkUI() {
        mPager = (ViewPager) findViewById(R.id.vp_mainmenu_special_offers);
        mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);

        //gv_mainmenu_categories = (GridView) findViewById(R.id.gv_mainmenu_categories);

    }

    private void setAction() {

    }
} 

    public class SpecialOfferFragmentAdapter extends FragmentPagerAdapter implements
        IconPagerAdapter {

    private int[] mCarouselImages = new int[] { R.drawable.pic1,
            R.drawable.pic2, R.drawable.pic3, R.drawable.pic4, R.drawable.pic5

    };

    private String[] imagesUrls;
    private Context context;

    public static final int[] ICONS = new int[] {
            R.drawable.perm_group_calendar, R.drawable.perm_group_camera,
            R.drawable.perm_group_device_alarms, R.drawable.perm_group_location };

    private int mCount = mCarouselImages.length;

    public SpecialOfferFragmentAdapter(FragmentManager fm, Context context,
            String[] imagesUrls) {
        super(fm);
        this.context = context;
        this.imagesUrls = imagesUrls;
    }

    @Override
    public Fragment getItem(int position) {

        return SpecialOfferFragment.newInstance(mCarouselImages[position]);
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public int getIconResId(int index) {
        return ICONS[index % ICONS.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }
}

Answer 1:

为了达到你想要的东西,你应该使用整型值来存储您的当前位置ViewPager ,之后使用这个值来合适的位置设置为您ViewPager

例如做这样的事情在你的FragmentActivity

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putInt("mMyCurrentPosition", mPager.getPosition());
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  mMyCurrentPosition = savedInstanceState.getInt("mMyCurrentPosition");
  // where mMyCurrentPosition should be a public value in your activity.
}

这将节省您的ViewPager的最后一个位置。 而在这之后你onResume()例如,你可以检查

if(mMyCurrentPosition != 0){
    mPager.setCurrentItem(mMyCurrentPosition);
}

我想,这应该工作,这不是一个好的做法,以保存图像/位图捆绑(我不认为你能做到这一点)。



Answer 2:

好了第一个ID希望搞清楚的东西了,可能解决有关savedinstancestate你的困惑。 Savedinstancestate只能处理原语(INT,双,浮点,字节..)和字符串对象。 这应该是你所需要的,但在某些情况下,你要保存的其他对象的情况下也是如此。 对于这一点,你需要一些其他的模式来完成这项工作,例如工厂模式至极保存所有的位图的数组。 例如像创建一个类ImageFactory保存位图的静态的ArrayList。 当你旋转你的设备的oncreateview和onactivitycreated方法又一次打来电话,这是检查,如果你想要从你的工厂或没有信息的那一刻。 例如

如果(!savedInstanceState = NULL){//我们有一个savedinstancestate所以有可能被保存的图像ImageFactory.getBMPs(); }

希望你可以做一些与此信息。 祝好运



Answer 3:

这个工作对我来说简单方便您的主要活动中

 @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        onCreate(savedInstanceState);
    }

和你的清单中

 <activity
            android:configChanges="orientation|screenSize"/>


Answer 4:

我已经建立了我对保存的分段数据自己的方法,而标签正在使用SharedPreference更改:

方法,如:

  public void saveData() {

    Log.d("msg", "Save Instance");
    SharedPreferences.Editor outState = getActivity().getSharedPreferences("order", Context.MODE_APPEND).edit();

    orderDate = orderDateEditText.getText().toString();
    orderBy = orderByEditText.getText().toString();
    orderMobileNo = orderMobileNoEditText.getText().toString();
    orderTransport = orderTransportEditText.getText().toString();
    orderInvoicePer = orderInvoicePerEditText.getText().toString(); 
    orderCharge = orderChargeEditText.getText().toString();
    orderGoodsDispatch = orderGoodsDispatchEditText.getText().toString();
    orderOthers = orderOthersEditText.getText().toString();
    orderIsDirect = orderIsDirectCheckBox.isChecked() ? 1 : 0;

    outState.putBoolean("saved", true);

    outState.putString("orderDate", orderDate);
    outState.putString("orderBy", orderBy);
    outState.putString("orderMobileNo", orderMobileNo);
    outState.putString("orderTransport", orderTransport);
    outState.putString("orderInvoicePer", orderInvoicePer);
    outState.putString("orderCharge", orderCharge);
    outState.putString("orderGoodsDispatch", orderGoodsDispatch);
    outState.putString("orderOthers", orderOthers);
    outState.putInt("orderIsDirect", orderIsDirect);

    outState.commit();
}

调用此方法时

    @Override
    public void onStop() {
    // TODO Auto-generated method stub
        super.onStop();

        saveData();
}

EditText上更换保存数据:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    /***** PUT DATA IN EDITTEXT is ITS AVAILABLE IN BUNDLE *****/
    SharedPreferences orderData = getActivity().getSharedPreferences("order", Context.MODE_APPEND);
    Log.d("msg", ""+orderData.getBoolean("saved", false));

    if(orderData.getBoolean("saved", false))
    {
        orderDate = orderData.getString("orderDate", "");
        orderBy = orderData.getString("orderBy", "");
        orderMobileNo = orderData.getString("orderMobileNo", "");
        orderTransport = orderData.getString("orderTransport", "");
        orderInvoicePer = orderData.getString("orderInvoicePer", ""); 
        orderCharge = orderData.getString("orderCharge", "");
        orderGoodsDispatch = orderData.getString("orderGoodsDispatch", "");
        orderOthers = orderData.getString("orderOthers", "");
        orderIsDirect = orderData.getInt("orderIsDirect", 0);

        orderDateEditText.setText(orderDate);
        orderByEditText.setText(orderBy);
        orderMobileNoEditText.setText(orderMobileNo);
        orderTransportEditText.setText(orderTransport);
        orderInvoicePerEditText.setText(orderInvoicePer);
        orderChargeEditText.setText(orderCharge);
        orderGoodsDispatchEditText.setText(orderGoodsDispatch);
        orderOthersEditText.setText(orderOthers);
        if(orderIsDirect == 0)
            orderIsDirectCheckBox.setChecked(false);
        else
            orderIsDirectCheckBox.setChecked(true);
    }
}

愿这代码对你有帮助...

谢谢...



Answer 5:

我不太清楚,如果这个问题仍然困扰着你,既然已经好几个月。 不过,我想和大家分享我如何处理这个问题。 这里是源代码:

int FLAG = 0;
private View rootView;
private LinearLayout parentView;

/**
 * The fragment argument representing the section number for this fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";

/**
 * Returns a new instance of this fragment for the given section number.
 */
public static Fragment2 newInstance(Bundle bundle) {
    Fragment2 fragment = new Fragment2();
    Bundle args = bundle;
    fragment.setArguments(args);
    return fragment;
}

public Fragment2() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    Log.e("onCreateView","onCreateView");
    if(FLAG!=12321){
        rootView = inflater.inflate(R.layout.fragment_create_new_album, container, false);
        changeFLAG(12321);
    }       
    parentView=new LinearLayout(getActivity());
    parentView.addView(rootView);

    return parentView;
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onDestroy()
 */
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Log.e("onDestroy","onDestroy");
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onStart()
 */
@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.e("onstart","onstart");
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onStop()
 */
@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    if(false){
        Bundle savedInstance=getArguments();
        LinearLayout viewParent;

        viewParent= (LinearLayout) rootView.getParent();
        viewParent.removeView(rootView);

    }
    parentView.removeView(rootView);

    Log.e("onStop","onstop");
}
@Override
public void onPause() {
    super.onPause();
    Log.e("onpause","onpause");
}

@Override
public void onResume() {
    super.onResume();
    Log.e("onResume","onResume");
}

这里是在MainActivity:

/**
 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.
 */

public static boolean fragment2InstanceExists=false;
public static Fragment2 fragment2=null;

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

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    switch(position){
    case 0:
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, Fragment1.newInstance(position+1)).commit();
        break;
    case 1:

        Bundle bundle=new Bundle();
        bundle.putInt("source_of_create",CommonMethods.CREATE_FROM_ACTIVITY);

        if(!fragment2InstanceExists){
            fragment2=Fragment2.newInstance(bundle);
            fragment2InstanceExists=true;
        }
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, fragment2).commit();

        break;
    case 2:
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, FolderExplorerFragment.newInstance(position+1)).commit();
        break;
    default: 
        break;
    }
}

该parentView是关键点。 通常情况下,当onCreateView,我们只是用回rootView。 但现在,我想补充rootView到parentView,然后返回parentView。 为了防止“指定的孩子已经有一个家长,你必须调用... removeView()”的错误,我们需要调用“parentView.removeView(rootView)”,或者我提供的方法是没有用的。 我也想和大家分享我如何找到它。 首先,我成立了一个布尔值,表示如果实例存在。 当实例存在,rootView不会再次膨胀。 但随后,logcat的给孩子已经有母的事情,所以我决定用另一个父作为中间父视图。 这就是它是如何工作的。 希望这对您有所帮助。



Answer 6:

让我写我的方式来处理这个问题。 我保持一个片段对象变量在活动,供以后的相互作用。 在onCreate()方法我检查是否有savedInstanceState(由屏幕旋转或别的东西)。

public class MainActivity extends AppCompatActivity {
PlaceAddFragment mFragment;

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

    if(savedInstanceState == null) {
        mFragment = new PlaceAddFragment();
        mFragment.setProfileImages(incomingPics);

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.form_fragment_holder, mFragment, PlaceAddFragment.TAG)
                .commit();
    }else{
        mFragment = (PlaceAddFragment) getSupportFragmentManager().findFragmentByTag(PlaceAddFragment.TAG);
    }
}

在我的片段I类的onSaveInstanceState重写方法和它只是添加setRetainInstance(真),如下图所示:

public class PlaceAddFragment extends Fragment {
public static final String TAG = ".PlaceAddFragment";
private ProfileImageAdapter mAdapter;
private List<ProfileImage> mProfileImages;
private Context mContext;

public PlaceAddFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    mContext = getContext();
    View view = inflater.inflate(R.layout.fragment_place_add, container, false);

    RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.hw_pictures_holder);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
    mAdapter = new ProfileImageAdapter(mContext, mProfileImages);
    mRecyclerView.setAdapter(mAdapter);

    return view;
}

@Override
public void onSaveInstanceState(final Bundle outState) {
    super.onSaveInstanceState(outState);
    setRetainInstance(true);
}

@Override
public void onDestroy() {
    super.onDestroy();
    mAdapter = null;
    mProfileImages = null;
}

public void setProfileImages(List<ProfileImage> incomingPics) {
    this.mProfileImages = incomingPics;
}

public List<ProfileImage> getProfileImages() {
    return this.mProfileImages;
}
}

如果你想这个代码工作,你应该实现ProfileImageAdapter mAdapter,ProfileImage对象和那些所有XML布局。



文章来源: Save/Restore fragments state android